forked from TheLartians/TypeScript2Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseTypeDefinition.ts
More file actions
80 lines (69 loc) 路 2.53 KB
/
Copy pathparseTypeDefinition.ts
File metadata and controls
80 lines (69 loc) 路 2.53 KB
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
import ts from "typescript";
import { ParserState } from "./ParserState";
import {
getDocumentationStringForDict,
parseProperty,
parsePropertyForDict,
} from "./parseProperty";
import { getDocumentationStringForType } from "./getDocumentationStringForType";
import { tryToParseInlineType } from "./parseInlineType";
import { isValidPythonIdentifier } from "./isValidPythonIdentifier";
export const parseTypeDefinition = (
state: ParserState,
name: string,
type: ts.Type,
) => {
const inlineType = tryToParseInlineType(state, type, true);
const documentation = getDocumentationStringForType(state.typechecker, type);
if (!state.knownTypes.has(type)) {
// we set the currently parsed type here to prevent recursions
state.knownTypes.set(type, name);
}
if (inlineType) {
const definition = `${name} = ${inlineType}${
documentation ? `\n"""\n${documentation}\n"""` : ""
}`;
state.statements.push(definition);
} else {
state.imports.add("TypedDict");
const allKeysAreValidPythonIdentifiers = type
.getProperties()
.map((v) => isValidPythonIdentifier(v.getName()))
.reduce((a, b) => a && b, true);
if (allKeysAreValidPythonIdentifiers) {
const properties = type
.getProperties()
.map((v) => parseProperty(state, v));
const definition = `class ${name}(TypedDict):${
documentation
? `\n """\n ${documentation.replaceAll("\n", " \n")}\n """`
: ""
}\n ${properties.length > 0 ? properties.join(`\n `) : "pass"}`;
state.statements.push(definition);
} else {
const properties = type
.getProperties()
// empty strings are not allowed for keys in TypedDicts
.filter((v) => v.getName() !== "");
const parsedProperties = properties.map((v) =>
parsePropertyForDict(state, v),
);
const propertyDocumentation = properties
.map((v) => getDocumentationStringForDict(state, v))
.filter((v) => !!v)
.map((v) => `- ${v}`.replaceAll("\n", "\n "))
.join("\n");
const innerDocstring =
(documentation ?? "").replaceAll("\n", "\n ") +
(propertyDocumentation.length > 0
? "\n## Entries\n" + propertyDocumentation
: "");
const docstring =
innerDocstring.length > 0 ? `\n"""\n${innerDocstring}\n"""` : "";
const definition = `${name} = TypedDict(${JSON.stringify(
name,
)}, {\n ${parsedProperties.join(",\n ")}\n})${docstring}`;
state.statements.push(definition);
}
}
};