-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.ts
1880 lines (1552 loc) · 66.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 path = require('path');
import { CodeMaker, toSnakeCase } from 'codemaker';
import * as escapeStringRegexp from 'escape-string-regexp';
import * as reflect from 'jsii-reflect';
import * as spec from 'jsii-spec';
import { Stability } from 'jsii-spec';
import { Generator, GeneratorOptions } from '../generator';
import { md2rst } from '../markdown';
import { propertySpec } from '../reflect-hacks';
import { Target, TargetOptions } from '../target';
import { shell } from '../util';
export default class Python extends Target {
protected readonly generator = new PythonGenerator();
constructor(options: TargetOptions) {
super(options);
}
public async build(sourceDir: string, outDir: string): Promise<void> {
// Format our code to make it easier to read, we do this here instead of trying
// to do it in the code generation phase, because attempting to mix style and
// function makes the code generation harder to maintain and read, while doing
// this here is easy.
// await shell("black", ["--py36", sourceDir], {});
// Actually package up our code, both as a sdist and a wheel for publishing.
await shell("python3", ["setup.py", "sdist", "--dist-dir", outDir], { cwd: sourceDir });
await shell("python3", ["setup.py", "bdist_wheel", "--dist-dir", outDir], { cwd: sourceDir });
}
}
// ##################
// # CODE GENERATOR #
// ##################
const PYTHON_BUILTIN_TYPES = ["bool", "str", "None"];
const PYTHON_KEYWORDS = [
"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class",
"continue", "def", "del", "elif", "else", "except", "finally", "for", "from",
"global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass",
"raise", "return", "try", "while", "with", "yield"
];
const pythonModuleNameToFilename = (name: string): string => {
return name.replace(/\./g, "/");
};
const toPythonIdentifier = (name: string): string => {
if (PYTHON_KEYWORDS.indexOf(name) > -1) {
return name + "_";
}
return name;
};
const toPythonMethodName = (name: string, protectedItem: boolean = false): string => {
let value = toPythonIdentifier(toSnakeCase(name));
if (protectedItem) {
value = "_" + value;
}
return value;
};
const toPythonPropertyName = (name: string, constant: boolean = false, protectedItem: boolean = false): string => {
let value = toPythonIdentifier(toSnakeCase(name));
if (constant) {
value = value.toUpperCase();
}
if (protectedItem) {
value = "_" + value;
}
return value;
};
const toPythonParameterName = (name: string): string => {
return toPythonIdentifier(toSnakeCase(name));
};
const setDifference = (setA: Set<any>, setB: Set<any>): Set<any> => {
const difference = new Set(setA);
for (const elem of setB) {
difference.delete(elem);
}
return difference;
};
const sortMembers = (sortable: PythonBase[], resolver: TypeResolver): PythonBase[] => {
const sorted: PythonBase[] = [];
const seen: Set<PythonBase> = new Set();
// We're going to take a copy of our sortable item, because it'll make it easier if
// this method doesn't have side effects.
sortable = sortable.slice();
// 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 item of sortable) {
if (!isSortableType(item)) {
sorted.push(item);
seen.add(item);
}
}
sortable = sortable.filter(i => !seen.has(i));
// 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 item of (sortable as Array<PythonBase & ISortableType>)) {
const itemDeps: Set<PythonBase> = new Set(item.dependsOn(resolver));
if (setDifference(itemDeps, seen).size === 0) {
sorted.push(item);
seen.add(item);
break;
}
}
const leftover = sortable.filter(i => !seen.has(i));
if (leftover.length === sortable.length) {
throw new Error("Could not sort members (circular dependency?).");
} else {
sortable = leftover;
}
}
return sorted;
};
const recurseForNamedTypeReferences = (typeRef: spec.TypeReference): spec.NamedTypeReference[] => {
if (spec.isPrimitiveTypeReference(typeRef)) {
return [];
} else if (spec.isCollectionTypeReference(typeRef)) {
return recurseForNamedTypeReferences(typeRef.collection.elementtype);
} else if (spec.isNamedTypeReference(typeRef)) {
return [typeRef];
} else if (typeRef.union) {
const types: spec.NamedTypeReference[] = [];
for (const type of typeRef.union.types) {
types.push(...recurseForNamedTypeReferences(type));
}
return types;
} else {
throw new Error("Invalid type reference: " + JSON.stringify(typeRef));
}
};
interface PythonBase {
readonly pythonName: string;
emit(code: CodeMaker, resolver: TypeResolver, opts?: any): void;
}
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 | null;
addMember(member: PythonBase): void;
}
interface ISortableType {
dependsOn(resolver: TypeResolver): PythonType[];
}
function isSortableType(arg: any): arg is ISortableType {
return arg.dependsOn !== undefined;
}
interface PythonTypeOpts {
bases?: spec.TypeReference[];
}
abstract class BasePythonClassType implements PythonType, ISortableType {
protected bases: spec.TypeReference[];
protected members: PythonBase[];
constructor(
protected readonly generator: PythonGenerator,
public readonly pythonName: string,
public readonly fqn: string | null,
opts: PythonTypeOpts,
protected readonly docs: spec.Docs | undefined) {
const {
bases = [],
} = opts;
this.bases = bases;
this.members = [];
}
public dependsOn(resolver: TypeResolver): PythonType[] {
const dependencies: 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: Set<string> = new Set();
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 addMember(member: PythonBase) {
this.members.push(member);
}
public emit(code: CodeMaker, resolver: TypeResolver) {
const classParams = this.getClassParams(resolver);
const bases = classParams.length > 0 ? `(${classParams.join(", ")})` : "";
code.openBlock(`class ${this.pythonName}${bases}`);
emitDocString(code, this.docs);
this.emitPreamble(code, resolver);
if (this.members.length > 0) {
resolver = this.fqn ? resolver.bind(this.fqn) : resolver;
for (const member of sortMembers(this.members, resolver)) {
member.emit(code, resolver);
}
} else {
code.line("pass");
}
code.closeBlock();
}
protected abstract getClassParams(resolver: TypeResolver): string[];
protected emitPreamble(_code: CodeMaker, _resolver: TypeResolver) { return; }
}
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 readonly abstract 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;
constructor(protected readonly generator: PythonGenerator,
public readonly pythonName: string,
private readonly jsName: string | undefined,
private readonly parameters: spec.Parameter[],
private readonly returns?: spec.OptionalValue,
private readonly docs?: spec.Docs,
opts: BaseMethodOpts = {}) {
this.abstract = !!opts.abstract;
this.liftedProp = opts.liftedProp;
this.parent = opts.parent;
}
public emit(code: CodeMaker, resolver: TypeResolver, opts?: BaseMethodEmitOpts) {
const { renderAbstract = true, forceEmitBody = false } = opts || {};
let returnType: string;
if (this.returns !== undefined) {
returnType = resolver.resolve(this.returns, { forwardReferences: false });
} else {
returnType = "None";
}
// 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: Set<string> = new Set();
if (this.liftedProp !== undefined
&& this.liftedProp.properties !== undefined
&& this.liftedProp.properties.length >= 1) {
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[] = [this.implicitParameter];
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.
let paramName: string = toPythonParameterName(param.name);
while (liftedPropNames.has(paramName)) {
paramName = `${paramName}_`;
}
const paramType = resolver.resolve(param, { forwardReferences: false});
const paramDefault = param.optional ? "=None" : "";
pythonParams.push(`${paramName}: ${paramType}${paramDefault}`);
}
const documentableArgs = [...this.parameters];
// 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(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.name);
const paramType = resolver.resolve(prop, { forwardReferences: false });
const paramDefault = prop.optional ? "=None" : "";
pythonParams.push(`${paramName}: ${paramType}${paramDefault}`);
}
}
// Document them as keyword arguments
documentableArgs.push(...liftedProperties);
} 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 = resolver.resolve(
lastParameter,
{ forwardReferences: false, ignoreOptional: true },
);
pythonParams.push(`*${paramName}: ${paramType}`);
}
if (this.jsName !== undefined) {
code.line(`@jsii.member(jsii_name="${this.jsName}")`);
}
if (this.decorator !== undefined) {
code.line(`@${this.decorator}`);
}
if (renderAbstract && this.abstract) {
code.line("@abc.abstractmethod");
}
code.openBlock(`def ${this.pythonName}(${pythonParams.join(", ")}) -> ${returnType}`);
emitDocString(code, this.docs, { arguments: documentableArgs });
this.emitBody(code, resolver, renderAbstract, forceEmitBody);
code.closeBlock();
}
private emitBody(code: CodeMaker, resolver: TypeResolver, renderAbstract: boolean, forceEmitBody: boolean) {
if ((!this.shouldEmitBody && !forceEmitBody) || (renderAbstract && this.abstract)) {
code.line("...");
} else {
if (this.liftedProp !== undefined) {
this.emitAutoProps(code, resolver);
}
this.emitJsiiMethodCall(code, resolver);
}
}
private emitAutoProps(code: CodeMaker, resolver: TypeResolver) {
const lastParameter = this.parameters.slice(-1)[0];
const argName = toPythonParameterName(lastParameter.name);
const typeName = resolver.resolve(lastParameter, {ignoreOptional: true });
// We need to build up a list of properties, which are mandatory, these are the
// ones we will specifiy to start with in our dictionary literal.
const liftedProps = this.getLiftedProperties(resolver).map(p => new StructField(p));
const assignments = liftedProps
.map(p => p.pythonName)
.map(v => `${v}=${v}`);
code.line(`${argName} = ${typeName}(${assignments.join(', ')})`);
code.line();
}
private emitJsiiMethodCall(code: CodeMaker, resolver: TypeResolver) {
const methodPrefix: string = this.returnFromJSIIMethod ? "return " : "";
const jsiiMethodParams: string[] = [];
if (this.classAsFirstParameter) {
if (this.parent === undefined) {
throw new Error("Parent not known.");
}
jsiiMethodParams.push(resolver.resolve({ type: this.parent }));
}
jsiiMethodParams.push(this.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);
if (param.variadic) { expr = `*${expr}`; }
params.push(expr);
}
code.line(`${methodPrefix}jsii.${this.jsiiMethod}(${jsiiMethodParams.join(", ")}, [${params.join(", ")}])`);
}
private getLiftedProperties(resolver: TypeResolver): spec.Property[] {
const liftedProperties: spec.Property[] = [];
const stack = [this.liftedProp];
let current = stack.shift();
while (current !== undefined) {
// Add any interfaces that this interface depends on, to the list.
if (current.interfaces !== undefined) {
stack.push(...current.interfaces.map(ifc => resolver.dereference(ifc) as spec.InterfaceType));
}
// Add all of the properties of this interface to our list of properties.
if (current.properties !== undefined) {
liftedProperties.push(...current.properties);
}
// Finally, grab our next item.
current = stack.shift();
}
return liftedProperties;
}
}
interface BasePropertyOpts {
abstract?: boolean;
immutable?: boolean;
}
interface BasePropertyEmitOpts {
renderAbstract?: boolean;
forceEmitBody?: boolean;
}
abstract class BaseProperty implements PythonBase {
public readonly abstract: boolean;
protected readonly abstract decorator: string;
protected readonly abstract implicitParameter: string;
protected readonly jsiiGetMethod: string;
protected readonly jsiiSetMethod: string;
protected readonly shouldEmitBody: boolean = true;
private readonly immutable: boolean;
constructor(public readonly pythonName: string,
private readonly jsName: string,
private readonly type: spec.OptionalValue,
private readonly docs: spec.Docs | undefined,
opts: BasePropertyOpts = {}) {
const {
abstract = false,
immutable = false,
} = opts;
this.abstract = abstract;
this.immutable = immutable;
}
public emit(code: CodeMaker, resolver: TypeResolver, opts?: BasePropertyEmitOpts) {
const { renderAbstract = true, forceEmitBody = false } = opts || {};
const pythonType = resolver.resolve(this.type, { forwardReferences: false });
code.line(`@${this.decorator}`);
code.line(`@jsii.member(jsii_name="${this.jsName}")`);
if (renderAbstract && this.abstract) {
code.line("@abc.abstractmethod");
}
code.openBlock(`def ${this.pythonName}(${this.implicitParameter}) -> ${pythonType}`);
emitDocString(code, this.docs);
if ((this.shouldEmitBody || forceEmitBody) && (!renderAbstract || !this.abstract)) {
code.line(`return jsii.${this.jsiiGetMethod}(${this.implicitParameter}, "${this.jsName}")`);
} else {
code.line("...");
}
code.closeBlock();
if (!this.immutable) {
code.line(`@${this.pythonName}.setter`);
if (renderAbstract && this.abstract) {
code.line("@abc.abstractmethod");
}
code.openBlock(`def ${this.pythonName}(${this.implicitParameter}, value: ${pythonType})`);
if ((this.shouldEmitBody || forceEmitBody) && (!renderAbstract || !this.abstract)) {
code.line(`return jsii.${this.jsiiSetMethod}(${this.implicitParameter}, "${this.jsName}", value)`);
} else {
code.line("...");
}
code.closeBlock();
}
}
}
class Interface extends BasePythonClassType {
public emit(code: CodeMaker, resolver: TypeResolver) {
code.line(`@jsii.interface(jsii_type="${this.fqn}")`);
// First we do our normal class logic for emitting our members.
super.emit(code, resolver);
// Then, we have to emit a Proxy class which implements our proxy interface.
resolver = this.fqn ? resolver.bind(this.fqn) : resolver;
const proxyBases: string[] = this.bases.map(b => `jsii.proxy_for(${resolver.resolve({ type: b })})`);
code.openBlock(`class ${this.getProxyClassName()}(${proxyBases.join(", ")})`);
emitDocString(code, this.docs);
code.line(`__jsii_type__ = "${this.fqn}"`);
if (this.members.length > 0) {
for (const member of this.members) {
member.emit(code, resolver, { forceEmitBody: true });
}
} else {
code.line("pass");
}
code.closeBlock();
}
protected getClassParams(resolver: TypeResolver): string[] {
const params: string[] = this.bases.map(b => resolver.resolve({ type: b }));
params.push("jsii.compat.Protocol");
return params;
}
protected emitPreamble(code: CodeMaker, _resolver: TypeResolver) {
code.line("@staticmethod");
code.openBlock("def __jsii_proxy_class__()");
code.line(`return ${this.getProxyClassName()}`);
code.closeBlock();
}
private getProxyClassName(): string {
return `_${this.pythonName}Proxy`;
}
}
class InterfaceMethod extends BaseMethod {
protected readonly implicitParameter: string = "self";
protected readonly jsiiMethod: string = "invoke";
protected readonly shouldEmitBody: boolean = false;
}
class InterfaceProperty extends BaseProperty {
protected readonly decorator: string = "property";
protected readonly implicitParameter: string = "self";
protected readonly jsiiGetMethod: string = "get";
protected readonly jsiiSetMethod: string = "set";
protected readonly shouldEmitBody: boolean = false;
}
class Struct extends BasePythonClassType {
protected directMembers = new Array<StructField>();
public addMember(member: PythonBase): void {
if (!(member instanceof StructField)) {
throw new Error('Must add StructField to Struct');
}
this.directMembers.push(member);
}
public emit(code: CodeMaker, resolver: TypeResolver) {
resolver = this.fqn ? resolver.bind(this.fqn) : resolver;
const baseInterfaces = this.getClassParams(resolver);
code.line(`@jsii.data_type(jsii_type="${this.fqn}", jsii_struct_bases=[${baseInterfaces.join(', ')}], name_mapping=${this.propertyMap()})`);
code.openBlock(`class ${this.pythonName}(${baseInterfaces.join(', ')})`);
this.emitConstructor(code, resolver);
for (const member of this.allMembers) {
this.emitGetter(member, code, resolver);
}
this.emitMagicMethods(code);
code.closeBlock();
}
protected getClassParams(resolver: TypeResolver): string[] {
return this.bases.map(b => resolver.resolve({ type: b }));
}
/**
* Find all fields (inherited as well)
*/
private get allMembers(): StructField[] {
return this.thisInterface.allProperties.map(x => new StructField(propertySpec(x)));
}
private get thisInterface() {
if (this.fqn === null) { throw new Error('FQN not set'); }
return this.generator.reflectAssembly.system.findInterface(this.fqn);
}
private emitConstructor(code: CodeMaker, resolver: TypeResolver) {
const members = this.allMembers;
const kwargs = members.map(m => m.constructorDecl(resolver));
const constructorArguments = kwargs.length > 0 ? ['self', '*', ...kwargs] : ['self'];
code.openBlock(`def __init__(${constructorArguments.join(', ')})`);
this.emitConstructorDocstring(code);
// Required properties, those will always be put into the dict
code.line('self._values = {');
for (const member of members.filter(m => !m.optional)) {
code.line(` '${member.pythonName}': ${member.pythonName},`);
}
code.line('}');
// Optional properties, will only be put into the dict if they're not None
for (const member of members.filter(m => m.optional)) {
code.line(`if ${member.pythonName} is not None: self._values["${member.pythonName}"] = ${member.pythonName}`);
}
code.closeBlock();
}
private emitConstructorDocstring(code: CodeMaker) {
const args: DocumentableArgument[] = this.allMembers.map(m => ({
name: m.pythonName,
docs: m.docs,
}));
emitDocString(code, this.docs, { arguments: args });
}
private emitGetter(member: StructField, code: CodeMaker, resolver: TypeResolver) {
code.line('@property');
code.openBlock(`def ${member.pythonName}(self) -> ${member.typeAnnotation(resolver)}`);
member.emitDocString(code);
code.line(`return self._values.get('${member.pythonName}')`);
code.closeBlock();
}
private emitMagicMethods(code: CodeMaker) {
code.openBlock(`def __eq__(self, rhs) -> bool`);
code.line('return isinstance(rhs, self.__class__) and rhs._values == self._values');
code.closeBlock();
code.openBlock(`def __ne__(self, rhs) -> bool`);
code.line('return not (rhs == self)');
code.closeBlock();
code.openBlock(`def __repr__(self) -> str`);
code.line(`return '${this.pythonName}(%s)' % ', '.join(k + '=' + repr(v) for k, v in self._values.items())`);
code.closeBlock();
}
private propertyMap() {
const ret = new Array<string>();
for (const member of this.allMembers) {
ret.push(`'${member.pythonName}': '${member.jsiiName}'`);
}
return `{${ret.join(', ')}}`;
}
}
class StructField implements PythonBase {
public readonly pythonName: string;
public readonly jsiiName: string;
public readonly docs?: spec.Docs;
private readonly type: spec.OptionalValue;
constructor(public readonly prop: spec.Property) {
this.pythonName = toPythonPropertyName(prop.name);
this.jsiiName = prop.name;
this.type = prop;
this.docs = prop.docs;
}
public get optional(): boolean {
return !!this.type.optional;
}
public isStruct(generator: PythonGenerator): boolean {
return isStruct(generator.reflectAssembly.system, this.type.type);
}
public constructorDecl(resolver: TypeResolver) {
const opt = this.optional ? '=None' : '';
return `${this.pythonName}: ${this.typeAnnotation(resolver)}${opt}`;
}
/**
* Return the Python type annotation for this type
*/
public typeAnnotation(resolver: TypeResolver) {
return resolver.resolve(
this.type,
{ forwardReferences: false }
);
}
public emitDocString(code: CodeMaker) {
emitDocString(code, this.docs);
}
public emit(code: CodeMaker, resolver: TypeResolver) {
const resolvedType = this.typeAnnotation(resolver);
code.line(`${this.pythonName}: ${resolvedType}`);
emitDocString(code, this.docs);
}
}
interface ClassOpts extends PythonTypeOpts {
abstract?: boolean;
interfaces?: spec.NamedTypeReference[];
abstractBases?: spec.ClassType[];
}
class Class extends BasePythonClassType {
private abstract: boolean;
private abstractBases: spec.ClassType[];
private interfaces: spec.NamedTypeReference[];
constructor(generator: PythonGenerator, name: string, fqn: string, opts: ClassOpts, docs: spec.Docs | undefined) {
super(generator, name, fqn, opts, docs);
const { abstract = false, interfaces = [], abstractBases = [] } = opts;
this.abstract = abstract;
this.interfaces = interfaces;
this.abstractBases = abstractBases;
}
public dependsOn(resolver: TypeResolver): PythonType[] {
const dependencies: PythonType[] = super.dependsOn(resolver);
const parent = resolver.getParent(this.fqn!);
// We need to return any ifaces that are in the same module at the same level of
// nesting.
const seen: Set<string> = new Set();
for (const iface of this.interfaces) {
if (resolver.isInModule(iface)) {
// Given a iface, we need to locate the ifaces'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 ifaceItem = resolver.getType(iface);
let ifaceParent = resolver.getParent(iface);
while (ifaceParent !== parent) {
ifaceItem = ifaceParent;
ifaceParent = resolver.getParent(ifaceItem.fqn!);
}
if (!seen.has(ifaceItem.fqn!)) {
dependencies.push(ifaceItem);
seen.add(ifaceItem.fqn!);
}
}
}
return dependencies;
}
public emit(code: CodeMaker, resolver: TypeResolver) {
// First we emit our implments decorator
if (this.interfaces.length > 0) {
const interfaces: string[] = this.interfaces.map(b => resolver.resolve({ type: b }));
code.line(`@jsii.implements(${interfaces.join(", ")})`);
}
// Then we do our normal class logic for emitting our members.
super.emit(code, resolver);
// Then, if our class is Abstract, we have to go through and redo all of
// this logic, except only emiting abstract methods and properties as non
// abstract, and subclassing our initial class.
if (this.abstract) {
resolver = this.fqn ? resolver.bind(this.fqn) : resolver;
const proxyBases: string[] = [this.pythonName];
for (const base of this.abstractBases) {
proxyBases.push(`jsii.proxy_for(${resolver.resolve({ type: base })})`);
}
code.openBlock(`class ${this.getProxyClassName()}(${proxyBases.join(', ')})`);
// Filter our list of members to *only* be abstract members, and not any
// other types.
const abstractMembers = this.members.filter(
m => (m instanceof BaseMethod || m instanceof BaseProperty) && m.abstract
);
if (abstractMembers.length > 0) {
for (const member of abstractMembers) {
member.emit(code, resolver, { renderAbstract: false });
}
} else {
code.line("pass");
}
code.closeBlock();
}
}
protected emitPreamble(code: CodeMaker, _resolver: TypeResolver) {
if (this.abstract) {
code.line("@staticmethod");
code.openBlock("def __jsii_proxy_class__()");
code.line(`return ${this.getProxyClassName()}`);
code.closeBlock();
}
}
protected getClassParams(resolver: TypeResolver): string[] {
const params: string[] = this.bases.map(b => resolver.resolve({ type: b }));
const metaclass: string = this.abstract ? "JSIIAbstractClass" : "JSIIMeta";
params.push(`metaclass=jsii.${metaclass}`);
params.push(`jsii_type="${this.fqn}"`);
return params;
}
private getProxyClassName(): string {
return `_${this.pythonName}Proxy`;
}
}
class StaticMethod extends BaseMethod {
protected readonly decorator?: string = "classmethod";
protected readonly implicitParameter: string = "cls";
protected readonly jsiiMethod: string = "sinvoke";
}
class Initializer extends BaseMethod {
protected readonly implicitParameter: string = "self";
protected readonly jsiiMethod: string = "create";
protected readonly classAsFirstParameter: boolean = true;
protected readonly returnFromJSIIMethod: boolean = false;
}
class Method extends BaseMethod {
protected readonly implicitParameter: string = "self";
protected readonly jsiiMethod: string = "invoke";
}
class AsyncMethod extends BaseMethod {
protected readonly implicitParameter: string = "self";
protected readonly jsiiMethod: string = "ainvoke";
}
class StaticProperty extends BaseProperty {
protected readonly decorator: string = "classproperty";
protected readonly implicitParameter: string = "cls";
protected readonly jsiiGetMethod: string = "sget";
protected readonly jsiiSetMethod: string = "sset";
}
class Property extends BaseProperty {
protected readonly decorator: string = "property";
protected readonly implicitParameter: string = "self";
protected readonly jsiiGetMethod: string = "get";
protected readonly jsiiSetMethod: string = "set";
}
class Enum extends BasePythonClassType {
public emit(code: CodeMaker, resolver: TypeResolver) {
code.line(`@jsii.enum(jsii_type="${this.fqn}")`);
return super.emit(code, resolver);
}
protected getClassParams(_resolver: TypeResolver): string[] {
return ["enum.Enum"];
}
}
class EnumMember implements PythonBase {
constructor(public readonly pythonName: string, private readonly value: string, private readonly docs: spec.Docs | undefined) {
this.pythonName = pythonName;
this.value = value;
}
public emit(code: CodeMaker, _resolver: TypeResolver) {
code.line(`${this.pythonName} = "${this.value}"`);
emitDocString(code, this.docs);
}
}
class Namespace extends BasePythonClassType {
protected getClassParams(_resolver: TypeResolver): string[] {
return [];
}
}
interface ModuleOpts {
assembly: spec.Assembly,
assemblyFilename: string;
loadAssembly: boolean;
}
class Module implements PythonType {
public readonly pythonName: string;
public readonly fqn: string | null;
private assembly: spec.Assembly;
private assemblyFilename: string;
private loadAssembly: boolean;
private members: PythonBase[];
constructor(name: string, fqn: string | null, opts: ModuleOpts) {
this.pythonName = name;
this.fqn = fqn;
this.assembly = opts.assembly;
this.assemblyFilename = opts.assemblyFilename;
this.loadAssembly = opts.loadAssembly;
this.members = [];
}
public addMember(member: PythonBase) {
this.members.push(member);
}
public emit(code: CodeMaker, resolver: TypeResolver) {
resolver = this.fqn ? resolver.bind(this.fqn, this.pythonName) : resolver;
// Before we write anything else, we need to write out our module headers, this
// is where we handle stuff like imports, any required initialization, etc.
code.line("import abc");
code.line("import datetime");
code.line("import enum");
code.line("import typing");
code.line();
code.line("import jsii");
code.line("import jsii.compat");
code.line("import publication");
code.line();
code.line("from jsii.python import classproperty");
// Go over all of the modules that we need to import, and import them.
this.emitDependencyImports(code, resolver);
// Determine if we need to write out the kernel load line.
if (this.loadAssembly) {