|
64 | 64 | YieldFromExpr, NamedTupleExpr, TypedDictExpr, NonlocalDecl, SymbolNode,
|
65 | 65 | SetComprehension, DictionaryComprehension, TYPE_ALIAS, TypeAliasExpr,
|
66 | 66 | YieldExpr, ExecStmt, Argument, BackquoteExpr, ImportBase, AwaitExpr,
|
67 |
| - IntExpr, FloatExpr, UnicodeExpr, EllipsisExpr, TempNode, |
| 67 | + IntExpr, FloatExpr, UnicodeExpr, EllipsisExpr, TempNode, EnumCallExpr, |
68 | 68 | COVARIANT, CONTRAVARIANT, INVARIANT, UNBOUND_IMPORTED, LITERAL_YES, ARG_OPT, nongen_builtins,
|
69 | 69 | collections_type_aliases, get_member_expr_fullname,
|
70 | 70 | )
|
@@ -1434,6 +1434,7 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
|
1434 | 1434 | self.process_typevar_declaration(s)
|
1435 | 1435 | self.process_namedtuple_definition(s)
|
1436 | 1436 | self.process_typeddict_definition(s)
|
| 1437 | + self.process_enum_call(s) |
1437 | 1438 |
|
1438 | 1439 | if (len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) and
|
1439 | 1440 | s.lvalues[0].name == '__all__' and s.lvalues[0].kind == GDEF and
|
@@ -2263,6 +2264,139 @@ def is_classvar(self, typ: Type) -> bool:
|
2263 | 2264 | def fail_invalid_classvar(self, context: Context) -> None:
|
2264 | 2265 | self.fail('ClassVar can only be used for assignments in class body', context)
|
2265 | 2266 |
|
| 2267 | + def process_enum_call(self, s: AssignmentStmt) -> None: |
| 2268 | + """Check if s defines an Enum; if yes, store the definition in symbol table.""" |
| 2269 | + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): |
| 2270 | + return |
| 2271 | + lvalue = s.lvalues[0] |
| 2272 | + name = lvalue.name |
| 2273 | + enum_call = self.check_enum_call(s.rvalue, name) |
| 2274 | + if enum_call is None: |
| 2275 | + return |
| 2276 | + # Yes, it's a valid Enum definition. Add it to the symbol table. |
| 2277 | + node = self.lookup(name, s) |
| 2278 | + if node: |
| 2279 | + node.kind = GDEF # TODO locally defined Enum |
| 2280 | + node.node = enum_call |
| 2281 | + |
| 2282 | + def check_enum_call(self, node: Expression, var_name: str = None) -> Optional[TypeInfo]: |
| 2283 | + """Check if a call defines an Enum. |
| 2284 | +
|
| 2285 | + Example: |
| 2286 | +
|
| 2287 | + A = enum.Enum('A', 'foo bar') |
| 2288 | +
|
| 2289 | + is equivalent to: |
| 2290 | +
|
| 2291 | + class A(enum.Enum): |
| 2292 | + foo = 1 |
| 2293 | + bar = 2 |
| 2294 | + """ |
| 2295 | + if not isinstance(node, CallExpr): |
| 2296 | + return None |
| 2297 | + call = node |
| 2298 | + callee = call.callee |
| 2299 | + if not isinstance(callee, RefExpr): |
| 2300 | + return None |
| 2301 | + fullname = callee.fullname |
| 2302 | + if fullname not in ('enum.Enum', 'enum.IntEnum', 'enum.Flag', 'enum.IntFlag'): |
| 2303 | + return None |
| 2304 | + items, values, ok = self.parse_enum_call_args(call, fullname.split('.')[-1]) |
| 2305 | + if not ok: |
| 2306 | + # Error. Construct dummy return value. |
| 2307 | + return self.build_enum_call_typeinfo('Enum', [], fullname) |
| 2308 | + name = cast(StrExpr, call.args[0]).value |
| 2309 | + if name != var_name or self.is_func_scope(): |
| 2310 | + # Give it a unique name derived from the line number. |
| 2311 | + name += '@' + str(call.line) |
| 2312 | + info = self.build_enum_call_typeinfo(name, items, fullname) |
| 2313 | + # Store it as a global just in case it would remain anonymous. |
| 2314 | + # (Or in the nearest class if there is one.) |
| 2315 | + stnode = SymbolTableNode(GDEF, info, self.cur_mod_id) |
| 2316 | + if self.type: |
| 2317 | + self.type.names[name] = stnode |
| 2318 | + else: |
| 2319 | + self.globals[name] = stnode |
| 2320 | + call.analyzed = EnumCallExpr(info, items, values) |
| 2321 | + call.analyzed.set_line(call.line, call.column) |
| 2322 | + return info |
| 2323 | + |
| 2324 | + def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) -> TypeInfo: |
| 2325 | + base = self.named_type_or_none(fullname) |
| 2326 | + assert base is not None |
| 2327 | + info = self.basic_new_typeinfo(name, base) |
| 2328 | + info.is_enum = True |
| 2329 | + for item in items: |
| 2330 | + var = Var(item) |
| 2331 | + var.info = info |
| 2332 | + var.is_property = True |
| 2333 | + info.names[item] = SymbolTableNode(MDEF, var) |
| 2334 | + return info |
| 2335 | + |
| 2336 | + def parse_enum_call_args(self, call: CallExpr, |
| 2337 | + class_name: str) -> Tuple[List[str], |
| 2338 | + List[Optional[Expression]], bool]: |
| 2339 | + args = call.args |
| 2340 | + if len(args) < 2: |
| 2341 | + return self.fail_enum_call_arg("Too few arguments for %s()" % class_name, call) |
| 2342 | + if len(args) > 2: |
| 2343 | + return self.fail_enum_call_arg("Too many arguments for %s()" % class_name, call) |
| 2344 | + if call.arg_kinds != [ARG_POS, ARG_POS]: |
| 2345 | + return self.fail_enum_call_arg("Unexpected arguments to %s()" % class_name, call) |
| 2346 | + if not isinstance(args[0], (StrExpr, UnicodeExpr)): |
| 2347 | + return self.fail_enum_call_arg( |
| 2348 | + "%s() expects a string literal as the first argument" % class_name, call) |
| 2349 | + items = [] |
| 2350 | + values = [] # type: List[Optional[Expression]] |
| 2351 | + if isinstance(args[1], (StrExpr, UnicodeExpr)): |
| 2352 | + fields = args[1].value |
| 2353 | + for field in fields.replace(',', ' ').split(): |
| 2354 | + items.append(field) |
| 2355 | + elif isinstance(args[1], (TupleExpr, ListExpr)): |
| 2356 | + seq_items = args[1].items |
| 2357 | + if all(isinstance(seq_item, (StrExpr, UnicodeExpr)) for seq_item in seq_items): |
| 2358 | + items = [cast(StrExpr, seq_item).value for seq_item in seq_items] |
| 2359 | + elif all(isinstance(seq_item, (TupleExpr, ListExpr)) |
| 2360 | + and len(seq_item.items) == 2 |
| 2361 | + and isinstance(seq_item.items[0], (StrExpr, UnicodeExpr)) |
| 2362 | + for seq_item in seq_items): |
| 2363 | + for seq_item in seq_items: |
| 2364 | + assert isinstance(seq_item, (TupleExpr, ListExpr)) |
| 2365 | + name, value = seq_item.items |
| 2366 | + assert isinstance(name, (StrExpr, UnicodeExpr)) |
| 2367 | + items.append(name.value) |
| 2368 | + values.append(value) |
| 2369 | + else: |
| 2370 | + return self.fail_enum_call_arg( |
| 2371 | + "%s() with tuple or list expects strings or (name, value) pairs" % |
| 2372 | + class_name, |
| 2373 | + call) |
| 2374 | + elif isinstance(args[1], DictExpr): |
| 2375 | + for key, value in args[1].items: |
| 2376 | + if not isinstance(key, (StrExpr, UnicodeExpr)): |
| 2377 | + return self.fail_enum_call_arg( |
| 2378 | + "%s() with dict literal requires string literals" % class_name, call) |
| 2379 | + items.append(key.value) |
| 2380 | + values.append(value) |
| 2381 | + else: |
| 2382 | + # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}? |
| 2383 | + return self.fail_enum_call_arg( |
| 2384 | + "%s() expects a string, tuple, list or dict literal as the second argument" % |
| 2385 | + class_name, |
| 2386 | + call) |
| 2387 | + if len(items) == 0: |
| 2388 | + return self.fail_enum_call_arg("%s() needs at least one item" % class_name, call) |
| 2389 | + if not values: |
| 2390 | + values = [None] * len(items) |
| 2391 | + assert len(items) == len(values) |
| 2392 | + return items, values, True |
| 2393 | + |
| 2394 | + def fail_enum_call_arg(self, message: str, |
| 2395 | + context: Context) -> Tuple[List[str], |
| 2396 | + List[Optional[Expression]], bool]: |
| 2397 | + self.fail(message, context) |
| 2398 | + return [], [], False |
| 2399 | + |
2266 | 2400 | def visit_decorator(self, dec: Decorator) -> None:
|
2267 | 2401 | for d in dec.decorators:
|
2268 | 2402 | d.accept(self)
|
|
0 commit comments