-
Notifications
You must be signed in to change notification settings - Fork 179
/
stubgen.py
256 lines (205 loc) · 7.78 KB
/
stubgen.py
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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import re
import inspect
import textwrap
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Set, List, Tuple, Optional
ROOT_MODULE_NAME_PLACEHOLDER = "__root_module_name__"
class Writer:
"""
Writer provides utilities for writing Python stubs.
"""
root_module_name: str
path: Path
subwriters: List[Writer]
imports: Set[str]
defs: List[str]
def __init__(self, path: Path, root_module_name: str) -> None:
self.path = path
self.root_module_name = root_module_name
self.subwriters = []
self.imports = set([])
self.defs = []
def fix_path(self, path: str) -> str:
return path.replace(ROOT_MODULE_NAME_PLACEHOLDER, self.root_module_name)
def submodule(self, path: Path) -> Writer:
w = Writer(path, self.root_module_name)
self.subwriters.append(w)
return w
def include(self, path: str) -> str:
# `path` might be nested like: typing.Optional[typing.List[pokemon_service_server_sdk.model.GetPokemonSpecies]]
# we need to process every subpath in a nested path
paths = filter(lambda p: p, re.split("\\[|\\]|,| ", path))
for subpath in paths:
parts = subpath.rsplit(".", maxsplit=1)
# add `typing` to imports for a path like `typing.List`
# but skip if the path doesn't have any namespace like `str` or `bool`
if len(parts) == 2:
self.imports.add(parts[0])
return path
def fix_and_include(self, path: str) -> str:
return self.include(self.fix_path(path))
def define(self, code: str) -> None:
self.defs.append(code)
def dump(self) -> None:
for w in self.subwriters:
w.dump()
self.path.parent.mkdir(parents=True, exist_ok=True)
contents = "\n".join(map(lambda p: f"import {p}", self.imports))
contents += "\n\n"
contents += "\n".join(self.defs)
self.path.write_text(contents)
@dataclass
class DocstringParserResult:
types: List[str]
params: List[Tuple[str, str]]
rtypes: List[str]
class DocstringParser:
"""
DocstringParser provides utilities for parsing type information from docstring.
"""
@staticmethod
def parse(obj: Any) -> Optional[DocstringParserResult]:
doc = inspect.getdoc(obj)
if not doc:
return None
types: List[str] = []
params: List[Tuple[str, str]] = []
rtypes: List[str] = []
for line in doc.splitlines():
line = line.strip()
if line.startswith(":type ") and line.endswith(":"):
parts = line.split(" ", maxsplit=1)
if len(parts) != 2:
raise ValueError(
f"Invalid `:type` directive: `{line}` must be in `:type T:` format"
)
types.append(parts[1].rstrip(":"))
elif line.startswith(":param ") and line.endswith(":"):
parts = line.split(" ", maxsplit=2)
if len(parts) != 3:
raise ValueError(
f"Invalid `:param` directive: `{line}` must be in `:param name T:` format"
)
name = parts[1]
ty = parts[2].rstrip(":")
params.append((name, ty))
elif line.startswith(":rtype ") and line.endswith(":"):
parts = line.split(" ", maxsplit=1)
if len(parts) != 2:
raise ValueError(
f"Invalid `:rtype` directive: `{line}` must be in `:rtype T:` format"
)
rtypes.append(parts[1].rstrip(":"))
return DocstringParserResult(types=types, params=params, rtypes=rtypes)
@staticmethod
def parse_type(obj: Any) -> str:
result = DocstringParser.parse(obj)
if not result or len(result.types) == 0:
return "typing.Any"
return result.types[0]
@staticmethod
def parse_function(obj: Any) -> Optional[Tuple[List[Tuple[str, str]], str]]:
result = DocstringParser.parse(obj)
if not result:
return None
return (
result.params,
"None" if len(result.rtypes) == 0 else result.rtypes[0],
)
def indent(code: str, level: int) -> str:
return textwrap.indent(code, level * " ")
def is_fn_like(obj: Any) -> bool:
return (
inspect.isbuiltin(obj)
or inspect.ismethod(obj)
or inspect.isfunction(obj)
or inspect.ismethoddescriptor(obj)
)
def walk_field(writer: Writer, name: str, field: Any) -> str:
return f"{name}: {writer.fix_and_include(DocstringParser.parse_type(field))} = ..."
def make_function(writer: Writer, name: str, obj: Any, indent_level: int = 0) -> str:
res = DocstringParser.parse_function(obj)
if not res:
# Make it `Any` if we can't parse the docstring
return f"{name}: {writer.include('typing.Any')}"
params, rtype = res
receivers: List[str] = []
attrs: List[str] = []
if inspect.ismethoddescriptor(obj) or name == "__init__":
receivers.append("self")
else:
attrs.append("@staticmethod")
params = ", ".join(
receivers + [f"{n}: {writer.fix_and_include(t)} = ..." for n, t in params]
)
fn_def = ""
if len(attrs) > 0:
for attr in attrs:
fn_def += f"{attr}\n"
fn_def += f"def {name}({params}) -> {writer.fix_and_include(rtype)}: ..."
return indent(fn_def, indent_level)
def make_class(
writer: Writer, class_name: str, klass: Any, indent_level: int = 0
) -> str:
bases = ", ".join(map(lambda b: b.__name__, klass.__bases__))
definition = f"class {class_name}({bases}):\n"
is_empty = True
for (name, member) in inspect.getmembers(klass):
if name.startswith("__"):
continue
if inspect.isdatadescriptor(member):
is_empty = False
definition += (
indent(walk_field(writer, name, member), indent_level + 4) + "\n"
)
elif is_fn_like(member):
is_empty = False
definition += make_function(writer, name, member, indent_level + 4) + "\n"
# Enum variant
elif isinstance(member, klass):
is_empty = False
definition += indent(f"{name}: {class_name} = ...\n", indent_level + 4)
else:
print(f"Unknown member type={member}")
if inspect.getdoc(klass) is not None:
is_empty = False
definition += make_function(writer, "__init__", klass, indent_level + 4) + "\n"
if is_empty:
definition += indent(f"...\n", indent_level + 4)
return definition
def walk_module(writer: Writer, mod: Any):
exported = mod.__all__
for (name, member) in inspect.getmembers(mod):
if name not in exported:
continue
if inspect.ismodule(member):
walk_module(
writer.submodule(writer.path.parent / name / "__init__.pyi"), member
)
elif inspect.isclass(member):
writer.define(make_class(writer, name, member))
elif is_fn_like(member):
writer.define(make_function(writer, name, member))
else:
print(f"Unknown type: {member}")
if __name__ == "__main__":
import argparse
import importlib
parser = argparse.ArgumentParser()
parser.add_argument("module")
parser.add_argument("outdir")
args = parser.parse_args()
path = Path(args.outdir) / f"{args.module}.pyi"
writer = Writer(
path,
args.module,
)
walk_module(
writer,
importlib.import_module(args.module),
)
writer.dump()