-
Notifications
You must be signed in to change notification settings - Fork 245
/
python.ts
3420 lines (3005 loc) · 98.2 KB
/
python.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as spec from '@jsii/spec';
import * as assert from 'assert';
import { CodeMaker, toSnakeCase } from 'codemaker';
import * as crypto from 'crypto';
import * as escapeStringRegexp from 'escape-string-regexp';
import * as fs from 'fs-extra';
import * as reflect from 'jsii-reflect';
import {
TargetLanguage,
RosettaTabletReader,
enforcesStrictMode,
ApiLocation,
} from 'jsii-rosetta';
import * as path from 'path';
import { Generator, GeneratorOptions } from '../generator';
import { warn } from '../logging';
import { md2rst } from '../markdown';
import { Target, TargetOptions } from '../target';
import { shell } from '../util';
import { VERSION } from '../version';
import { renderSummary, PropertyDefinition } from './_utils';
import {
NamingContext,
toTypeName,
PythonImports,
mergePythonImports,
toPackageName,
} from './python/type-name';
import { die, toPythonIdentifier } from './python/util';
import { toPythonVersionRange, toReleaseVersion } from './version-utils';
import { TargetName } from './index';
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-require-imports
const spdxLicenseList = require('spdx-license-list');
const requirementsFile = path.resolve(
__dirname,
'python',
'requirements-dev.txt',
);
// we use single-quotes for multi-line strings to allow examples within the
// docstrings themselves to include double-quotes (see https://github.com/aws/jsii/issues/2569)
const DOCSTRING_QUOTES = "'''";
const RAW_DOCSTRING_QUOTES = `r${DOCSTRING_QUOTES}`;
export default class Python extends Target {
protected readonly generator: PythonGenerator;
public constructor(options: TargetOptions) {
super(options);
this.generator = new PythonGenerator(options.rosetta, options);
}
public async generateCode(outDir: string, tarball: string): Promise<void> {
await super.generateCode(outDir, tarball);
}
public async build(sourceDir: string, outDir: string): Promise<void> {
// Create a fresh virtual env
const venv = await fs.mkdtemp(path.join(sourceDir, '.env-'));
const venvBin = path.join(
venv,
process.platform === 'win32' ? 'Scripts' : 'bin',
);
// On Windows, there is usually no python3.exe (the GitHub action workers will have a python3
// shim, but using this actually results in a WinError with Python 3.7 and 3.8 where venv will
// fail to copy the python binary if it's not invoked as python.exe). More on this particular
// issue can be read here: https://bugs.python.org/issue43749
await shell(process.platform === 'win32' ? 'python' : 'python3', [
'-m',
'venv',
'--system-site-packages', // Allow using globally installed packages (saves time & disk space)
venv,
]);
const env = {
...process.env,
PATH: `${venvBin}:${process.env.PATH}`,
VIRTUAL_ENV: venv,
};
const python = path.join(venvBin, 'python');
// Install the necessary things
await shell(
python,
['-m', 'pip', 'install', '--no-input', '-r', requirementsFile],
{
cwd: sourceDir,
env,
retry: { maxAttempts: 5 },
},
);
// Actually package up our code, both as a sdist and a wheel for publishing.
await shell(python, ['setup.py', 'sdist', '--dist-dir', outDir], {
cwd: sourceDir,
env,
});
await shell(
python,
['-m', 'pip', 'wheel', '--no-deps', '--wheel-dir', outDir, sourceDir],
{
cwd: sourceDir,
env,
retry: { maxAttempts: 5 },
},
);
await shell(python, ['-m', 'twine', 'check', path.join(outDir, '*')], {
cwd: sourceDir,
env,
});
}
}
// ##################
// # CODE GENERATOR #
// ##################
interface EmitContext extends NamingContext {
/** @deprecated The TypeResolver */
readonly resolver: TypeResolver;
/** Whether to emit runtime type checking code */
readonly runtimeTypeChecking: boolean;
/** Whether to runtime type check keyword arguments (i.e: struct constructors) */
readonly runtimeTypeCheckKwargs?: boolean;
/** The numerical IDs used for type annotation data storing */
readonly typeCheckingHelper: TypeCheckingHelper;
}
class TypeCheckingHelper {
#stubs = new Array<TypeCheckingStub>();
public getTypeHints(fqn: string, args: readonly string[]): string {
const stub = new TypeCheckingStub(fqn, args);
this.#stubs.push(stub);
return `typing.get_type_hints(${stub.name})`;
}
/** Emits instructions that create the annotations data... */
public flushStubs(code: CodeMaker) {
for (const stub of this.#stubs) {
stub.emit(code);
}
// Reset the stubs list
this.#stubs = [];
}
}
class TypeCheckingStub {
static readonly #PREFIX = '_typecheckingstub__';
readonly #arguments: readonly string[];
readonly #hash: string;
public constructor(fqn: string, args: readonly string[]) {
// Removing the quoted type names -- this will be emitted at the very end of the module.
this.#arguments = args.map((arg) => arg.replace(/"/g, ''));
this.#hash = crypto
.createHash('sha256')
.update(TypeCheckingStub.#PREFIX)
.update(fqn)
.digest('hex');
}
public get name(): string {
return `${TypeCheckingStub.#PREFIX}${this.#hash}`;
}
public emit(code: CodeMaker) {
code.line();
openSignature(code, 'def', this.name, this.#arguments, 'None');
code.line(`"""Type checking stubs"""`);
code.line('pass');
code.closeBlock();
}
}
const pythonModuleNameToFilename = (name: string): string => {
return path.join(...name.split('.'));
};
const toPythonMethodName = (name: string, protectedItem = false): string => {
let value = toPythonIdentifier(toSnakeCase(name));
if (protectedItem) {
value = `_${value}`;
}
return value;
};
const toPythonPropertyName = (
name: string,
constant = false,
protectedItem = false,
): string => {
let value = toPythonIdentifier(toSnakeCase(name));
if (constant) {
value = value.toUpperCase();
}
if (protectedItem) {
value = `_${value}`;
}
return value;
};
/**
* Converts a given signature's parameter name to what should be emitted in Python. It slugifies the
* positional parameter names that collide with a lifted prop by appending trailing `_`. There is no
* risk of conflicting with an other positional parameter that ends with a `_` character because
* this is prohibited by the `jsii` compiler (parameter names MUST be camelCase, and only a single
* `_` is permitted when it is on **leading** position)
*
* @param name the name of the parameter that needs conversion.
* @param liftedParamNames the list of "lifted" keyword parameters in this signature. This must be
* omitted when generating a name for a parameter that **is** lifted.
*/
function toPythonParameterName(
name: string,
liftedParamNames = new Set<string>(),
): string {
let result = toPythonIdentifier(toSnakeCase(name));
while (liftedParamNames.has(result)) {
result += '_';
}
return result;
}
const setDifference = <T>(setA: Set<T>, setB: Set<T>): Set<T> => {
const result = new Set<T>();
for (const item of setA) {
if (!setB.has(item)) {
result.add(item);
}
}
return result;
};
/**
* Prepare python members for emission.
*
* If there are multiple members of the same name, they will all map to the same python
* name, so we will filter all deprecated members and expect that there will be only one
* left.
*
* Returns the members in a sorted list.
*/
function prepareMembers(members: PythonBase[], resolver: TypeResolver) {
// create a map from python name to list of members
const map: { [pythonName: string]: PythonBase[] } = {};
for (const m of members) {
let list = map[m.pythonName];
if (!list) {
list = map[m.pythonName] = [];
}
list.push(m);
}
// now return all the members
const ret = new Array<PythonBase>();
for (const [name, list] of Object.entries(map)) {
let member;
if (list.length === 1) {
// if we have a single member for this normalized name, then use it
member = list[0];
} else {
// we found more than one member with the same python name, filter all
// deprecated versions and check that we are left with exactly one.
// otherwise, they will overwrite each other
// see https://github.com/aws/jsii/issues/2508
const nonDeprecated = list.filter((x) => !isDeprecated(x));
if (nonDeprecated.length > 1) {
throw new Error(
`Multiple non-deprecated members which map to the Python name "${name}"`,
);
}
if (nonDeprecated.length === 0) {
throw new Error(
`Multiple members which map to the Python name "${name}", but all of them are deprecated`,
);
}
member = nonDeprecated[0];
}
ret.push(member);
}
return sortMembers(ret, resolver);
}
const sortMembers = (
members: PythonBase[],
resolver: TypeResolver,
): PythonBase[] => {
let sortable = new Array<{
member: PythonBase & ISortableType;
dependsOn: Set<PythonType>;
}>();
const sorted = new Array<PythonBase>();
const seen = new Set<PythonBase>();
// The first thing we want to do, is push any item which is not sortable to the very
// front of the list. This will be things like methods, properties, etc.
for (const member of members) {
if (!isSortableType(member)) {
sorted.push(member);
seen.add(member);
} else {
sortable.push({ member, dependsOn: new Set(member.dependsOn(resolver)) });
}
}
// Now that we've pulled out everything that couldn't possibly have dependencies,
// we will go through the remaining items, and pull off any items which have no
// dependencies that we haven't already sorted.
while (sortable.length > 0) {
for (const { member, dependsOn } of sortable) {
const diff = setDifference(dependsOn, seen);
if ([...diff].find((dep) => !(dep instanceof PythonModule)) == null) {
sorted.push(member);
seen.add(member);
}
}
const leftover = sortable.filter(({ member }) => !seen.has(member));
if (leftover.length === sortable.length) {
throw new Error(
`Could not sort members (circular dependency?). Leftover: ${leftover
.map((lo) => lo.member.pythonName)
.join(', ')}`,
);
} else {
sortable = leftover;
}
}
return sorted;
};
interface PythonBase {
readonly pythonName: string;
readonly docs?: spec.Docs;
emit(code: CodeMaker, context: EmitContext, opts?: any): void;
requiredImports(context: EmitContext): PythonImports;
}
interface PythonType extends PythonBase {
// The JSII FQN for this item, if this item doesn't exist as a JSII type, then it
// doesn't have a FQN and it should be null;
readonly fqn?: string;
addMember(member: PythonBase): void;
}
interface ISortableType {
dependsOn(resolver: TypeResolver): PythonType[];
}
function isSortableType(arg: unknown): arg is ISortableType {
return (arg as Partial<ISortableType>).dependsOn !== undefined;
}
interface PythonTypeOpts {
bases?: spec.TypeReference[];
}
abstract class BasePythonClassType implements PythonType, ISortableType {
protected bases: spec.TypeReference[];
protected members: PythonBase[];
protected readonly separateMembers: boolean = true;
public constructor(
protected readonly generator: PythonGenerator,
public readonly pythonName: string,
public readonly spec: spec.Type,
public readonly fqn: string | undefined,
opts: PythonTypeOpts,
public readonly docs: spec.Docs | undefined,
) {
const { bases = [] } = opts;
this.bases = bases;
this.members = [];
}
public dependsOn(resolver: TypeResolver): PythonType[] {
const dependencies = new Array<PythonType>();
const parent = resolver.getParent(this.fqn!);
// We need to return any bases that are in the same module at the same level of
// nesting.
const seen = new Set<string>();
for (const base of this.bases) {
if (spec.isNamedTypeReference(base)) {
if (resolver.isInModule(base)) {
// Given a base, we need to locate the base's parent that is the same as
// our parent, because we only care about dependencies that are at the
// same level of our own.
// TODO: We might need to recurse into our members to also find their
// dependencies.
let baseItem = resolver.getType(base);
let baseParent = resolver.getParent(base);
while (baseParent !== parent) {
baseItem = baseParent;
baseParent = resolver.getParent(baseItem.fqn!);
}
if (!seen.has(baseItem.fqn!)) {
dependencies.push(baseItem);
seen.add(baseItem.fqn!);
}
}
}
}
return dependencies;
}
public requiredImports(context: EmitContext): PythonImports {
return mergePythonImports(
...this.bases.map((base) => toTypeName(base).requiredImports(context)),
...this.members.map((mem) => mem.requiredImports(context)),
);
}
public addMember(member: PythonBase) {
this.members.push(member);
}
public get apiLocation(): ApiLocation {
if (!this.fqn) {
throw new Error(
`Cannot make apiLocation for ${this.pythonName}, does not have FQN`,
);
}
return { api: 'type', fqn: this.fqn };
}
public emit(code: CodeMaker, context: EmitContext) {
context = nestedContext(context, this.fqn);
const classParams = this.getClassParams(context);
openSignature(code, 'class', this.pythonName, classParams);
this.generator.emitDocString(code, this.apiLocation, this.docs, {
documentableItem: `class-${this.pythonName}`,
trailingNewLine: true,
});
if (this.members.length > 0) {
const resolver = this.boundResolver(context.resolver);
let shouldSeparate = false;
for (const member of prepareMembers(this.members, resolver)) {
if (shouldSeparate) {
code.line();
}
shouldSeparate = this.separateMembers;
member.emit(code, { ...context, resolver });
}
} else {
code.line('pass');
}
code.closeBlock();
if (this.fqn != null) {
context.emittedTypes.add(this.fqn);
}
}
protected boundResolver(resolver: TypeResolver): TypeResolver {
if (this.fqn == null) {
return resolver;
}
return resolver.bind(this.fqn);
}
protected abstract getClassParams(context: EmitContext): string[];
}
interface BaseMethodOpts {
abstract?: boolean;
liftedProp?: spec.InterfaceType;
parent: spec.NamedTypeReference;
}
interface BaseMethodEmitOpts {
renderAbstract?: boolean;
forceEmitBody?: boolean;
}
abstract class BaseMethod implements PythonBase {
public readonly abstract: boolean;
protected abstract readonly implicitParameter: string;
protected readonly jsiiMethod!: string;
protected readonly decorator?: string;
protected readonly classAsFirstParameter: boolean = false;
protected readonly returnFromJSIIMethod: boolean = true;
protected readonly shouldEmitBody: boolean = true;
private readonly liftedProp?: spec.InterfaceType;
private readonly parent: spec.NamedTypeReference;
public constructor(
protected readonly generator: PythonGenerator,
public readonly pythonName: string,
private readonly jsName: string | undefined,
private readonly parameters: spec.Parameter[],
private readonly returns: spec.OptionalValue | undefined,
public readonly docs: spec.Docs | undefined,
public readonly isStatic: boolean,
private readonly pythonParent: PythonType,
opts: BaseMethodOpts,
) {
this.abstract = !!opts.abstract;
this.liftedProp = opts.liftedProp;
this.parent = opts.parent;
}
public get apiLocation(): ApiLocation {
return {
api: 'member',
fqn: this.parent.fqn,
memberName: this.jsName ?? '',
};
}
public requiredImports(context: EmitContext): PythonImports {
return mergePythonImports(
toTypeName(this.returns).requiredImports(context),
...this.parameters.map((param) =>
toTypeName(param).requiredImports(context),
),
...liftedProperties(this.liftedProp),
);
function* liftedProperties(
struct: spec.InterfaceType | undefined,
): IterableIterator<PythonImports> {
if (struct == null) {
return;
}
for (const prop of struct.properties ?? []) {
yield toTypeName(prop.type).requiredImports(context);
}
for (const base of struct.interfaces ?? []) {
const iface = context.resolver.dereference(base) as spec.InterfaceType;
for (const imports of liftedProperties(iface)) {
yield imports;
}
}
}
}
public emit(
code: CodeMaker,
context: EmitContext,
opts?: BaseMethodEmitOpts,
) {
const { renderAbstract = true, forceEmitBody = false } = opts ?? {};
const returnType: string = toTypeName(this.returns).pythonType(context);
// We cannot (currently?) blindly use the names given to us by the JSII for
// initializers, because our keyword lifting will allow two names to clash.
// This can hopefully be removed once we get https://github.com/aws/jsii/issues/288
// resolved, so build up a list of all of the prop names so we can check against
// them later.
const liftedPropNames = new Set<string>();
if (this.liftedProp?.properties != null) {
for (const prop of this.liftedProp.properties) {
liftedPropNames.add(toPythonParameterName(prop.name));
}
}
// We need to turn a list of JSII parameters, into Python style arguments with
// gradual typing, so we'll have to iterate over the list of parameters, and
// build the list, converting as we go.
const pythonParams: string[] = [];
for (const param of this.parameters) {
// We cannot (currently?) blindly use the names given to us by the JSII for
// initializers, because our keyword lifting will allow two names to clash.
// This can hopefully be removed once we get https://github.com/aws/jsii/issues/288
// resolved.
const paramName: string = toPythonParameterName(
param.name,
liftedPropNames,
);
const paramType = toTypeName(param).pythonType({
...context,
parameterType: true,
});
const paramDefault = param.optional ? ' = None' : '';
pythonParams.push(`${paramName}: ${paramType}${paramDefault}`);
}
const documentableArgs: DocumentableArgument[] = this.parameters
.map(
(p) =>
({
name: p.name,
docs: p.docs,
definingType: this.parent,
}) as DocumentableArgument,
)
// If there's liftedProps, the last argument is the struct and it won't be _actually_ emitted.
.filter((_, index) =>
this.liftedProp != null ? index < this.parameters.length - 1 : true,
)
.map((param) => ({
...param,
name: toPythonParameterName(param.name, liftedPropNames),
}));
// If we have a lifted parameter, then we'll drop the last argument to our params
// and then we'll lift all of the params of the lifted type as keyword arguments
// to the function.
if (this.liftedProp !== undefined) {
// Remove our last item.
pythonParams.pop();
const liftedProperties = this.getLiftedProperties(context.resolver);
if (liftedProperties.length >= 1) {
// All of these parameters are keyword only arguments, so we'll mark them
// as such.
pythonParams.push('*');
// Iterate over all of our props, and reflect them into our params.
for (const prop of liftedProperties) {
const paramName = toPythonParameterName(prop.prop.name);
const paramType = toTypeName(prop.prop).pythonType({
...context,
parameterType: true,
typeAnnotation: true,
});
const paramDefault = prop.prop.optional ? ' = None' : '';
pythonParams.push(`${paramName}: ${paramType}${paramDefault}`);
}
}
// Document them as keyword arguments
documentableArgs.push(
...liftedProperties.map(
(p) =>
({
name: p.prop.name,
docs: p.prop.docs,
definingType: p.definingType,
}) as DocumentableArgument,
),
);
} else if (
this.parameters.length >= 1 &&
this.parameters[this.parameters.length - 1].variadic
) {
// Another situation we could be in, is that instead of having a plain parameter
// we have a variadic parameter where we need to expand the last parameter as a
// *args.
pythonParams.pop();
const lastParameter = this.parameters.slice(-1)[0];
const paramName = toPythonParameterName(lastParameter.name);
const paramType = toTypeName(lastParameter.type).pythonType(context);
pythonParams.push(`*${paramName}: ${paramType}`);
}
const decorators = new Array<string>();
if (this.jsName !== undefined) {
decorators.push(`@jsii.member(jsii_name="${this.jsName}")`);
}
if (this.decorator !== undefined) {
decorators.push(`@${this.decorator}`);
}
if (renderAbstract && this.abstract) {
decorators.push('@abc.abstractmethod');
}
if (decorators.length > 0) {
for (const decorator of decorators) {
code.line(decorator);
}
}
pythonParams.unshift(
slugifyAsNeeded(
this.implicitParameter,
pythonParams.map((param) => param.split(':')[0].trim()),
),
);
openSignature(code, 'def', this.pythonName, pythonParams, returnType);
this.generator.emitDocString(code, this.apiLocation, this.docs, {
arguments: documentableArgs,
documentableItem: `method-${this.pythonName}`,
});
if (
(this.shouldEmitBody || forceEmitBody) &&
(!renderAbstract || !this.abstract)
) {
emitParameterTypeChecks(
code,
context,
pythonParams.slice(1),
`${this.pythonParent.fqn ?? this.pythonParent.pythonName}#${
this.pythonName
}`,
);
}
this.emitBody(
code,
context,
renderAbstract,
forceEmitBody,
liftedPropNames,
pythonParams[0],
returnType,
);
code.closeBlock();
}
private emitBody(
code: CodeMaker,
context: EmitContext,
renderAbstract: boolean,
forceEmitBody: boolean,
liftedPropNames: Set<string>,
implicitParameter: string,
returnType: string,
) {
if (
(!this.shouldEmitBody && !forceEmitBody) ||
(renderAbstract && this.abstract)
) {
code.line('...');
} else {
if (this.liftedProp !== undefined) {
this.emitAutoProps(code, context, liftedPropNames);
}
this.emitJsiiMethodCall(
code,
context,
liftedPropNames,
implicitParameter,
returnType,
);
}
}
private emitAutoProps(
code: CodeMaker,
context: EmitContext,
liftedPropNames: Set<string>,
) {
const lastParameter = this.parameters.slice(-1)[0];
const argName = toPythonParameterName(lastParameter.name, liftedPropNames);
const typeName = toTypeName(lastParameter.type).pythonType({
...context,
typeAnnotation: false,
});
// We need to build up a list of properties, which are mandatory, these are the
// ones we will specify to start with in our dictionary literal.
const liftedProps = this.getLiftedProperties(context.resolver).map(
(p) => new StructField(this.generator, p.prop, p.definingType),
);
const assignments = liftedProps
.map((p) => p.pythonName)
.map((v) => `${v}=${v}`);
assignCallResult(code, argName, typeName, assignments);
code.line();
}
private emitJsiiMethodCall(
code: CodeMaker,
context: EmitContext,
liftedPropNames: Set<string>,
implicitParameter: string,
returnType: string,
) {
const methodPrefix: string = this.returnFromJSIIMethod ? 'return ' : '';
const jsiiMethodParams: string[] = [];
if (this.classAsFirstParameter) {
if (this.parent === undefined) {
throw new Error('Parent not known.');
}
if (this.isStatic) {
jsiiMethodParams.push(
toTypeName(this.parent).pythonType({
...context,
typeAnnotation: false,
}),
);
} else {
// Using the dynamic class of `self`.
jsiiMethodParams.push(`${implicitParameter}.__class__`);
}
}
jsiiMethodParams.push(implicitParameter);
if (this.jsName !== undefined) {
jsiiMethodParams.push(`"${this.jsName}"`);
}
// If the last arg is variadic, expand the tuple
const params: string[] = [];
for (const param of this.parameters) {
let expr = toPythonParameterName(param.name, liftedPropNames);
if (param.variadic) {
expr = `*${expr}`;
}
params.push(expr);
}
const value = `jsii.${this.jsiiMethod}(${jsiiMethodParams.join(
', ',
)}, [${params.join(', ')}])`;
code.line(
`${methodPrefix}${
this.returnFromJSIIMethod && returnType
? `typing.cast(${returnType}, ${value})`
: value
}`,
);
}
private getLiftedProperties(resolver: TypeResolver): PropertyDefinition[] {
const liftedProperties: PropertyDefinition[] = [];
const stack = [this.liftedProp];
const knownIfaces = new Set<string>();
const knownProps = new Set<string>();
for (
let current = stack.shift();
current != null;
current = stack.shift()
) {
knownIfaces.add(current.fqn);
// Add any interfaces that this interface depends on, to the list.
if (current.interfaces !== undefined) {
for (const iface of current.interfaces) {
if (knownIfaces.has(iface)) {
continue;
}
stack.push(resolver.dereference(iface) as spec.InterfaceType);
knownIfaces.add(iface);
}
}
// Add all of the properties of this interface to our list of properties.
if (current.properties !== undefined) {
for (const prop of current.properties) {
if (knownProps.has(prop.name)) {
continue;
}
liftedProperties.push({ prop, definingType: current });
knownProps.add(prop.name);
}
}
}
return liftedProperties;
}
}
interface BasePropertyOpts {
abstract?: boolean;
immutable?: boolean;
isStatic?: boolean;
parent: spec.NamedTypeReference;
}
interface BasePropertyEmitOpts {
renderAbstract?: boolean;
forceEmitBody?: boolean;
}
abstract class BaseProperty implements PythonBase {
public readonly abstract: boolean;
public readonly isStatic: boolean;
protected abstract readonly decorator: string;
protected abstract readonly implicitParameter: string;
protected readonly jsiiGetMethod!: string;
protected readonly jsiiSetMethod!: string;
protected readonly shouldEmitBody: boolean = true;
private readonly immutable: boolean;
private readonly parent: spec.NamedTypeReference;
public constructor(
private readonly generator: PythonGenerator,
public readonly pythonName: string,
private readonly jsName: string,
private readonly type: spec.OptionalValue,
public readonly docs: spec.Docs | undefined,
private readonly pythonParent: PythonType,
opts: BasePropertyOpts,
) {
const { abstract = false, immutable = false, isStatic = false } = opts;
this.abstract = abstract;
this.immutable = immutable;
this.isStatic = isStatic;
this.parent = opts.parent;
}
public get apiLocation(): ApiLocation {
return { api: 'member', fqn: this.parent.fqn, memberName: this.jsName };
}
public requiredImports(context: EmitContext): PythonImports {
return toTypeName(this.type).requiredImports(context);
}
public emit(
code: CodeMaker,
context: EmitContext,
opts?: BasePropertyEmitOpts,
) {
const { renderAbstract = true, forceEmitBody = false } = opts ?? {};
const pythonType = toTypeName(this.type).pythonType(context);
code.line(`@${this.decorator}`);
code.line(`@jsii.member(jsii_name="${this.jsName}")`);
if (renderAbstract && this.abstract) {
code.line('@abc.abstractmethod');
}
openSignature(
code,
'def',
this.pythonName,
[this.implicitParameter],
pythonType,
// PyRight and MyPY both special-case @property, but not custom implementations such as our @classproperty...
// MyPY reports on the re-declaration, but PyRight reports on the initial declaration (duh!)
this.isStatic && !this.immutable
? 'pyright: ignore [reportGeneralTypeIssues,reportRedeclaration]'
: undefined,
);
this.generator.emitDocString(code, this.apiLocation, this.docs, {
documentableItem: `prop-${this.pythonName}`,
});
// NOTE: No parameters to validate here, this is a getter...
if (
(this.shouldEmitBody || forceEmitBody) &&
(!renderAbstract || !this.abstract)
) {
code.line(
`return typing.cast(${pythonType}, jsii.${this.jsiiGetMethod}(${this.implicitParameter}, "${this.jsName}"))`,
);
} else {
code.line('...');
}
code.closeBlock();
if (!this.immutable) {
code.line();
// PyRight and MyPY both special-case @property, but not custom implementations such as our @classproperty...
// MyPY reports on the re-declaration, but PyRight reports on the initial declaration (duh!)
code.line(
`@${this.pythonName}.setter${
this.isStatic ? ' # type: ignore[no-redef]' : ''
}`,
);
if (renderAbstract && this.abstract) {
code.line('@abc.abstractmethod');
}
openSignature(
code,
'def',
this.pythonName,
[this.implicitParameter, `value: ${pythonType}`],
'None',