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