|
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 | ) |
@@ -1498,6 +1498,7 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None: |
1498 | 1498 | self.process_typevar_declaration(s) |
1499 | 1499 | self.process_namedtuple_definition(s) |
1500 | 1500 | self.process_typeddict_definition(s) |
| 1501 | + self.process_enum_call(s) |
1501 | 1502 |
|
1502 | 1503 | if (len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) and |
1503 | 1504 | s.lvalues[0].name == '__all__' and s.lvalues[0].kind == GDEF and |
@@ -2331,6 +2332,139 @@ def is_classvar(self, typ: Type) -> bool: |
2331 | 2332 | def fail_invalid_classvar(self, context: Context) -> None: |
2332 | 2333 | self.fail('ClassVar can only be used for assignments in class body', context) |
2333 | 2334 |
|
| 2335 | + def process_enum_call(self, s: AssignmentStmt) -> None: |
| 2336 | + """Check if s defines an Enum; if yes, store the definition in symbol table.""" |
| 2337 | + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): |
| 2338 | + return |
| 2339 | + lvalue = s.lvalues[0] |
| 2340 | + name = lvalue.name |
| 2341 | + enum_call = self.check_enum_call(s.rvalue, name) |
| 2342 | + if enum_call is None: |
| 2343 | + return |
| 2344 | + # Yes, it's a valid Enum definition. Add it to the symbol table. |
| 2345 | + node = self.lookup(name, s) |
| 2346 | + if node: |
| 2347 | + node.kind = GDEF # TODO locally defined Enum |
| 2348 | + node.node = enum_call |
| 2349 | + |
| 2350 | + def check_enum_call(self, node: Expression, var_name: str = None) -> Optional[TypeInfo]: |
| 2351 | + """Check if a call defines an Enum. |
| 2352 | +
|
| 2353 | + Example: |
| 2354 | +
|
| 2355 | + A = enum.Enum('A', 'foo bar') |
| 2356 | +
|
| 2357 | + is equivalent to: |
| 2358 | +
|
| 2359 | + class A(enum.Enum): |
| 2360 | + foo = 1 |
| 2361 | + bar = 2 |
| 2362 | + """ |
| 2363 | + if not isinstance(node, CallExpr): |
| 2364 | + return None |
| 2365 | + call = node |
| 2366 | + callee = call.callee |
| 2367 | + if not isinstance(callee, RefExpr): |
| 2368 | + return None |
| 2369 | + fullname = callee.fullname |
| 2370 | + if fullname not in ('enum.Enum', 'enum.IntEnum', 'enum.Flag', 'enum.IntFlag'): |
| 2371 | + return None |
| 2372 | + items, values, ok = self.parse_enum_call_args(call, fullname.split('.')[-1]) |
| 2373 | + if not ok: |
| 2374 | + # Error. Construct dummy return value. |
| 2375 | + return self.build_enum_call_typeinfo('Enum', [], fullname) |
| 2376 | + name = cast(StrExpr, call.args[0]).value |
| 2377 | + if name != var_name or self.is_func_scope(): |
| 2378 | + # Give it a unique name derived from the line number. |
| 2379 | + name += '@' + str(call.line) |
| 2380 | + info = self.build_enum_call_typeinfo(name, items, fullname) |
| 2381 | + # Store it as a global just in case it would remain anonymous. |
| 2382 | + # (Or in the nearest class if there is one.) |
| 2383 | + stnode = SymbolTableNode(GDEF, info, self.cur_mod_id) |
| 2384 | + if self.type: |
| 2385 | + self.type.names[name] = stnode |
| 2386 | + else: |
| 2387 | + self.globals[name] = stnode |
| 2388 | + call.analyzed = EnumCallExpr(info, items, values) |
| 2389 | + call.analyzed.set_line(call.line, call.column) |
| 2390 | + return info |
| 2391 | + |
| 2392 | + def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) -> TypeInfo: |
| 2393 | + base = self.named_type_or_none(fullname) |
| 2394 | + assert base is not None |
| 2395 | + info = self.basic_new_typeinfo(name, base) |
| 2396 | + info.is_enum = True |
| 2397 | + for item in items: |
| 2398 | + var = Var(item) |
| 2399 | + var.info = info |
| 2400 | + var.is_property = True |
| 2401 | + info.names[item] = SymbolTableNode(MDEF, var) |
| 2402 | + return info |
| 2403 | + |
| 2404 | + def parse_enum_call_args(self, call: CallExpr, |
| 2405 | + class_name: str) -> Tuple[List[str], |
| 2406 | + List[Optional[Expression]], bool]: |
| 2407 | + args = call.args |
| 2408 | + if len(args) < 2: |
| 2409 | + return self.fail_enum_call_arg("Too few arguments for %s()" % class_name, call) |
| 2410 | + if len(args) > 2: |
| 2411 | + return self.fail_enum_call_arg("Too many arguments for %s()" % class_name, call) |
| 2412 | + if call.arg_kinds != [ARG_POS, ARG_POS]: |
| 2413 | + return self.fail_enum_call_arg("Unexpected arguments to %s()" % class_name, call) |
| 2414 | + if not isinstance(args[0], (StrExpr, UnicodeExpr)): |
| 2415 | + return self.fail_enum_call_arg( |
| 2416 | + "%s() expects a string literal as the first argument" % class_name, call) |
| 2417 | + items = [] |
| 2418 | + values = [] # type: List[Optional[Expression]] |
| 2419 | + if isinstance(args[1], (StrExpr, UnicodeExpr)): |
| 2420 | + fields = args[1].value |
| 2421 | + for field in fields.replace(',', ' ').split(): |
| 2422 | + items.append(field) |
| 2423 | + elif isinstance(args[1], (TupleExpr, ListExpr)): |
| 2424 | + seq_items = args[1].items |
| 2425 | + if all(isinstance(seq_item, (StrExpr, UnicodeExpr)) for seq_item in seq_items): |
| 2426 | + items = [cast(StrExpr, seq_item).value for seq_item in seq_items] |
| 2427 | + elif all(isinstance(seq_item, (TupleExpr, ListExpr)) |
| 2428 | + and len(seq_item.items) == 2 |
| 2429 | + and isinstance(seq_item.items[0], (StrExpr, UnicodeExpr)) |
| 2430 | + for seq_item in seq_items): |
| 2431 | + for seq_item in seq_items: |
| 2432 | + assert isinstance(seq_item, (TupleExpr, ListExpr)) |
| 2433 | + name, value = seq_item.items |
| 2434 | + assert isinstance(name, (StrExpr, UnicodeExpr)) |
| 2435 | + items.append(name.value) |
| 2436 | + values.append(value) |
| 2437 | + else: |
| 2438 | + return self.fail_enum_call_arg( |
| 2439 | + "%s() with tuple or list expects strings or (name, value) pairs" % |
| 2440 | + class_name, |
| 2441 | + call) |
| 2442 | + elif isinstance(args[1], DictExpr): |
| 2443 | + for key, value in args[1].items: |
| 2444 | + if not isinstance(key, (StrExpr, UnicodeExpr)): |
| 2445 | + return self.fail_enum_call_arg( |
| 2446 | + "%s() with dict literal requires string literals" % class_name, call) |
| 2447 | + items.append(key.value) |
| 2448 | + values.append(value) |
| 2449 | + else: |
| 2450 | + # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}? |
| 2451 | + return self.fail_enum_call_arg( |
| 2452 | + "%s() expects a string, tuple, list or dict literal as the second argument" % |
| 2453 | + class_name, |
| 2454 | + call) |
| 2455 | + if len(items) == 0: |
| 2456 | + return self.fail_enum_call_arg("%s() needs at least one item" % class_name, call) |
| 2457 | + if not values: |
| 2458 | + values = [None] * len(items) |
| 2459 | + assert len(items) == len(values) |
| 2460 | + return items, values, True |
| 2461 | + |
| 2462 | + def fail_enum_call_arg(self, message: str, |
| 2463 | + context: Context) -> Tuple[List[str], |
| 2464 | + List[Optional[Expression]], bool]: |
| 2465 | + self.fail(message, context) |
| 2466 | + return [], [], False |
| 2467 | + |
2334 | 2468 | def visit_decorator(self, dec: Decorator) -> None: |
2335 | 2469 | for d in dec.decorators: |
2336 | 2470 | d.accept(self) |
|
0 commit comments