def as_block(self, stmts: List[ast27.stmt], lineno: int) -> Optional[Block]: b = None if stmts: b = Block( self.fix_function_overloads(self.translate_stmt_list(stmts))) b.set_line(lineno) return b
def _dynamic_class_hook(ctx: DynamicClassDefContext) -> None: """Generate a declarative Base class when the declarative_base() function is encountered.""" _add_globals(ctx) cls = ClassDef(ctx.name, Block([])) cls.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), cls, ctx.api.cur_mod_id) cls.info = info _set_declarative_metaclass(ctx.api, cls) cls_arg = util.get_callexpr_kwarg(ctx.call, "cls", expr_types=(NameExpr, )) if cls_arg is not None and isinstance(cls_arg.node, TypeInfo): util.set_is_base(cls_arg.node) decl_class.scan_declarative_assignments_and_apply_types( cls_arg.node.defn, ctx.api, is_mixin_scan=True) info.bases = [Instance(cls_arg.node, [])] else: obj = ctx.api.named_type(names.NAMED_TYPE_BUILTINS_OBJECT) info.bases = [obj] try: calculate_mro(info) except MroError: util.fail(ctx.api, "Not able to calculate MRO for declarative base", ctx.call) obj = ctx.api.named_type(names.NAMED_TYPE_BUILTINS_OBJECT) info.bases = [obj] info.fallback_to_any = True ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info)) util.set_is_base(info)
def add_new_class_for_module( module: MypyFile, name: str, bases: List[Instance], fields: Optional[Dict[str, MypyType]] = None, no_serialize: bool = False, ) -> TypeInfo: new_class_unique_name = checker.gen_unique_name(name, module.names) # make new class expression classdef = ClassDef(new_class_unique_name, Block([])) classdef.fullname = module.fullname + "." + new_class_unique_name # make new TypeInfo new_typeinfo = TypeInfo(SymbolTable(), classdef, module.fullname) new_typeinfo.bases = bases calculate_mro(new_typeinfo) new_typeinfo.calculate_metaclass_type() # add fields if fields: for field_name, field_type in fields.items(): var = Var(field_name, type=field_type) var.info = new_typeinfo var._fullname = new_typeinfo.fullname + "." + field_name new_typeinfo.names[field_name] = SymbolTableNode( MDEF, var, plugin_generated=True, no_serialize=no_serialize) classdef.info = new_typeinfo module.names[new_class_unique_name] = SymbolTableNode( GDEF, new_typeinfo, plugin_generated=True, no_serialize=no_serialize) return new_typeinfo
def build_class_with_annotated_fields(api: 'TypeChecker', base: Type, fields: 'OrderedDict[str, Type]', name: str) -> Instance: """Build an Instance with `name` that contains the specified `fields` as attributes and extends `base`.""" # Credit: This code is largely copied/modified from TypeChecker.intersect_instance_callable and # NamedTupleAnalyzer.build_namedtuple_typeinfo from mypy.checker import gen_unique_name cur_module = cast(MypyFile, api.scope.stack[0]) gen_name = gen_unique_name(name, cur_module.names) cdef = ClassDef(name, Block([])) cdef.fullname = cur_module.fullname() + '.' + gen_name info = TypeInfo(SymbolTable(), cdef, cur_module.fullname()) cdef.info = info info.bases = [base] def add_field(var: Var, is_initialized_in_class: bool = False, is_property: bool = False) -> None: var.info = info var.is_initialized_in_class = is_initialized_in_class var.is_property = is_property var._fullname = '%s.%s' % (info.fullname(), var.name()) info.names[var.name()] = SymbolTableNode(MDEF, var) vars = [Var(item, typ) for item, typ in fields.items()] for var in vars: add_field(var, is_property=True) calculate_mro(info) info.calculate_metaclass_type() cur_module.names[gen_name] = SymbolTableNode(GDEF, info, plugin_generated=True) return Instance(info, [])
def add_method( ctx: ClassDefContext, name: str, args: List[Argument], return_type: Type, self_type: Optional[Type] = None, tvar_def: Optional[TypeVarDef] = None, ) -> None: """Adds a new method to a class. """ info = ctx.cls.info self_type = self_type or fill_typevars(info) function_type = ctx.api.named_type('__builtins__.function') args = [Argument(Var('self'), self_type, None, ARG_POS)] + args arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, 'All arguments must be fully typed.' arg_types.append(arg.type_annotation) arg_names.append(arg.variable.name()) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) if tvar_def: signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.info = info func.type = set_callable_name(signature, func) func._fullname = info.fullname() + '.' + name func.line = info.line info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True) info.defn.defs.body.append(func)
def add_method(funcname: str, ret: Type, args: List[Argument], name: Optional[str] = None, is_classmethod: bool = False, is_new: bool = False, ) -> None: if is_classmethod or is_new: first = [Argument(Var('cls'), TypeType.make_normalized(selftype), None, ARG_POS)] else: first = [Argument(Var('self'), selftype, None, ARG_POS)] args = first + args types = [arg.type_annotation for arg in args] items = [arg.variable.name() for arg in args] arg_kinds = [arg.kind for arg in args] assert None not in types signature = CallableType(cast(List[Type], types), arg_kinds, items, ret, function_type) signature.variables = [tvd] func = FuncDef(funcname, args, Block([])) func.info = info func.is_class = is_classmethod func.type = set_callable_name(signature, func) func._fullname = info.fullname() + '.' + funcname if is_classmethod: v = Var(funcname, func.type) v.is_classmethod = True v.info = info v._fullname = func._fullname dec = Decorator(func, [NameExpr('classmethod')], v) info.names[funcname] = SymbolTableNode(MDEF, dec) else: info.names[funcname] = SymbolTableNode(MDEF, func)
def add_new_class_for_module(module: MypyFile, name: str, bases: List[Instance], fields: 'OrderedDict[str, MypyType]') -> TypeInfo: new_class_unique_name = checker.gen_unique_name(name, module.names) # make new class expression classdef = ClassDef(new_class_unique_name, Block([])) classdef.fullname = module.fullname() + '.' + new_class_unique_name # make new TypeInfo new_typeinfo = TypeInfo(SymbolTable(), classdef, module.fullname()) new_typeinfo.bases = bases calculate_mro(new_typeinfo) new_typeinfo.calculate_metaclass_type() def add_field_to_new_typeinfo(var: Var, is_initialized_in_class: bool = False, is_property: bool = False) -> None: var.info = new_typeinfo var.is_initialized_in_class = is_initialized_in_class var.is_property = is_property var._fullname = new_typeinfo.fullname() + '.' + var.name() new_typeinfo.names[var.name()] = SymbolTableNode(MDEF, var) # add fields var_items = [Var(item, typ) for item, typ in fields.items()] for var_item in var_items: add_field_to_new_typeinfo(var_item, is_property=True) classdef.info = new_typeinfo module.names[new_class_unique_name] = SymbolTableNode( GDEF, new_typeinfo, plugin_generated=True) return new_typeinfo
def add_classmethod_to_class(api, cls, name, args, return_type, self_type=None, tvar_def=None): """Adds a new classmethod to a class definition.""" info = cls.info # First remove any previously generated methods with the same name # to avoid clashes and problems in the semantic analyzer. if name in info.names: sym = info.names[name] if sym.plugin_generated and isinstance(sym.node, Decorator): cls.defs.body.remove(sym.node) self_type = self_type or fill_typevars(info) class_type = api.class_type(self_type) function_type = builtin_type(api, 'function') args = [Argument(Var('cls'), class_type, None, ARG_POS)] + args arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, 'All arguments must be fully typed.' arg_types.append(arg.type_annotation) arg_names.append(arg.variable.name) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) if tvar_def: signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.type = set_callable_name(signature, func) func._fullname = info.fullname + '.' + name func.line = info.line func.is_class = True var = Var(name) var.line = info.line var.info = info var.is_classmethod = True # should we have a NameExpr in the decorator list? dec = Decorator(func, [], var) dec.line = info.line # NOTE: we would like the plugin generated node to dominate, but we still # need to keep any existing definitions so they get semantically analyzed. if name in info.names: # Get a nice unique name instead. r_name = get_unique_redefinition_name(name, info.names) info.names[r_name] = info.names[name] info.names[name] = SymbolTableNode(MDEF, dec, plugin_generated=True) info.defn.defs.body.append(dec)
def add_method(self, method_name: str, args: List[Argument], ret_type: Type, self_type: Optional[Type] = None, tvd: Optional[TypeVarDef] = None) -> None: """Add a method: def <method_name>(self, <args>) -> <ret_type>): ... to info. self_type: The type to use for the self argument or None to use the inferred self type. tvd: If the method is generic these should be the type variables. """ from mypy.semanal import set_callable_name self_type = self_type if self_type is not None else self.self_type args = [Argument(Var('self'), self_type, None, ARG_POS)] + args arg_types = [arg.type_annotation for arg in args] arg_names = [arg.variable.name() for arg in args] arg_kinds = [arg.kind for arg in args] assert None not in arg_types signature = CallableType(cast(List[Type], arg_types), arg_kinds, arg_names, ret_type, self.function_type) if tvd: signature.variables = [tvd] func = FuncDef(method_name, args, Block([PassStmt()])) func.info = self.info func.type = set_callable_name(signature, func) func._fullname = self.info.fullname() + '.' + method_name func.line = self.info.line self.info.names[method_name] = SymbolTableNode(MDEF, func) # Add the created methods to the body so that they can get further semantic analysis. # e.g. Forward Reference Resolution. self.info.defn.defs.body.append(func)
def query_callback(ctx: DynamicClassDefContext) -> TypeInfo: # todo be defensive--ctx.type is Schema[Literal[fname]] #fname = ctx.arg_types[0].value query = ctx.call.args[1].value defn = ClassDef( ctx.name, defs=Block([ mpn.AssignmentStmt( lvalues=mpn.NameExpr, rvalue=None, type=ctx.api.lookup_fully_qualified_or_none('builtins.str'), new_syntax=True) ])) defn.fullname = ctx.api.qualified_name(ctx.name) names = SymbolTable() var = Var('me', ctx.api.builtin_type('builtins.str')) var.info = var.type.type var.is_property = True names['me'] = SymbolTableNode(MDEF, var, plugin_generated=True) info = TypeInfo(names=names, defn=defn, module_name=ctx.api.cur_mod_id) obj = ctx.api.builtin_type('builtins.object') info.mro = [info, obj.type] info.bases = [obj] print(ctx.name, info) ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
def _combine_protocols(p1: Instance, p2: Instance) -> Instance: def base_repr(base): if 'pfun.Intersection' in base.type.fullname: return ', '.join([repr(b) for b in base.type.bases]) return repr(base) def get_bases(base): if 'pfun.Intersection' in base.type.fullname: bases = set() for b in base.type.bases: bases |= get_bases(b) return bases return set([base]) names = p1.type.names.copy() names.update(p2.type.names) keywords = p1.type.defn.keywords.copy() keywords.update(p2.type.defn.keywords) bases = get_bases(p1) | get_bases(p2) bases_repr = ', '.join(sorted([repr(base) for base in bases])) name = f'Intersection[{bases_repr}]' defn = ClassDef(name, Block([]), p1.type.defn.type_vars + p2.type.defn.type_vars, [NameExpr(p1.type.fullname), NameExpr(p2.type.fullname)], None, list(keywords.items())) defn.fullname = f'pfun.{name}' info = TypeInfo(names, defn, '') info.is_protocol = True info.is_abstract = True info.bases = [p1, p2] info.abstract_attributes = (p1.type.abstract_attributes + p2.type.abstract_attributes) calculate_mro(info) return Instance(info, p1.args + p2.args)
def analyze_interface_base(classdef_ctx: ClassDefContext) -> None: # Create fake constructor to mimic adaptation signature info = classdef_ctx.cls.info api = classdef_ctx.api if "__init__" in info.names: # already patched return # Create a method: # # def __init__(self, obj, alternate=None) -> None # # This will make interfaces selftp = Instance(info, []) anytp = AnyType(TypeOfAny.implementation_artifact) init_fn = CallableType( arg_types=[selftp, anytp, anytp], arg_kinds=[ARG_POS, ARG_POS, ARG_OPT], arg_names=["self", "obj", "alternate"], ret_type=NoneTyp(), fallback=api.named_type("function"), ) newinit = FuncDef("__init__", [], Block([]), init_fn) newinit.info = info info.names["__init__"] = SymbolTableNode(MDEF, newinit, plugin_generated=True)
def _dynamic_class_hook(ctx: DynamicClassDefContext) -> None: """Generate a declarative Base class when the declarative_base() function is encountered.""" cls = ClassDef(ctx.name, Block([])) cls.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), cls, ctx.api.cur_mod_id) cls.info = info _make_declarative_meta(ctx.api, cls) cls_arg = util._get_callexpr_kwarg(ctx.call, "cls") if cls_arg is not None: decl_class._scan_declarative_assignments_and_apply_types( cls_arg.node.defn, ctx.api, is_mixin_scan=True) info.bases = [Instance(cls_arg.node, [])] else: obj = ctx.api.builtin_type("builtins.object") info.bases = [obj] try: calculate_mro(info) except MroError: util.fail(ctx.api, "Not able to calculate MRO for declarative base", ctx.call) obj = ctx.api.builtin_type("builtins.object") info.bases = [obj] info.fallback_to_any = True ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
def add_static_method( ctx, function_name: str, args: ty.List[Argument], return_type: Type ) -> None: """Mostly copied from mypy.plugins.common, with changes to make it work for a static method.""" info = ctx.cls.info function_type = ctx.api.named_type("__builtins__.function") arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, "All arguments must be fully typed." arg_types.append(arg.type_annotation) arg_names.append(nameit(arg.variable)) arg_kinds.append(arg.kind) signature = CallableType( arg_types, arg_kinds, arg_names, return_type, function_type ) func = FuncDef(function_name, args, Block([PassStmt()])) func.is_static = True func.info = info func.type = set_callable_name(signature, func) func._fullname = fullname(info) + "." + function_name func.line = info.line info.names[function_name] = SymbolTableNode(MDEF, func, plugin_generated=True) info.defn.defs.body.append(func)
def dyn_class_hook(self, ctx: DynamicClassDefContext) -> TypedDictType: """Generate annotations from a JSON Schema.""" schema_path = ctx.call.args[0] if len(ctx.call.args) > 1: schema_ref = ctx.call.args[1].value else: schema_ref = '#/' try: schema = self.resolve_name(schema_path.value) except (ImportError, AttributeError): schema_path = os.path.abspath(schema_path.value) schema = self._load_schema(schema_path) make_type = TypeMaker(schema_path, schema) td_type = make_type(ctx, schema_ref) class_def = ClassDef(ctx.name, Block([])) class_def.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id) if isinstance(td_type, TypedDictType): info.typeddict_type = td_type base_type = named_builtin_type(ctx, 'dict') else: base_type = td_type mro = base_type.type.mro if not mro: mro = [base_type.type, named_builtin_type(ctx, 'object').type] class_def.info = info info.mro = mro info.bases = [base_type] ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
def make_setter_wrapper(self, name: str, typ: Type) -> FuncDef: """Create a setter wrapper for a data attribute. The setter will be of this form: . def set$name(self: C, name: typ) -> None: . self.name! = name """ scope = self.make_scope() selft = self.self_type() selfv = scope.add('self', selft) namev = scope.add(name, typ) lvalue = MemberExpr(scope.name_expr('self'), name, direct=True) rvalue = scope.name_expr(name) ret = AssignmentStmt([lvalue], rvalue) wrapper_name = 'set$' + name sig = Callable([selft, typ], [nodes.ARG_POS, nodes.ARG_POS], [None, None], Void(), False) fdef = FuncDef(wrapper_name, [selfv, namev], [nodes.ARG_POS, nodes.ARG_POS], [None, None], Block([ret]), sig) fdef.info = self.tf.type_context() return fdef
def make_type_info(name: str, is_abstract: bool = False, mro: List[TypeInfo] = None, bases: List[Instance] = None, typevars: List[str] = None) -> TypeInfo: """Make a TypeInfo suitable for use in unit tests.""" type_def = TypeDef(name, Block([]), None, []) type_def.fullname = name if typevars: v = [] # type: List[TypeVarDef] id = 1 for n in typevars: v.append(TypeVarDef(n, id, None)) id += 1 type_def.type_vars = v info = TypeInfo(SymbolTable(), type_def) if mro is None: mro = [] info.mro = [info] + mro if bases is None: if mro: # By default, assume that there is a single non-generic base. bases = [Instance(mro[0], [])] else: bases = [] info.bases = bases return info
def add_static_method_to_class( api: Union[SemanticAnalyzerPluginInterface, CheckerPluginInterface], cls: ClassDef, name: str, args: List[Argument], return_type: Type, tvar_def: Optional[TypeVarType] = None, ) -> None: """Adds a static method Edited add_method_to_class to incorporate static method logic https://github.com/python/mypy/blob/9c05d3d19/mypy/plugins/common.py """ info = cls.info # First remove any previously generated methods with the same name # to avoid clashes and problems in the semantic analyzer. if name in info.names: sym = info.names[name] if sym.plugin_generated and isinstance(sym.node, FuncDef): cls.defs.body.remove(sym.node) # For compat with mypy < 0.93 if MypyVersion.VERSION < Decimal("0.93"): function_type = api.named_type("__builtins__.function") # type: ignore else: if isinstance(api, SemanticAnalyzerPluginInterface): function_type = api.named_type("builtins.function") else: function_type = api.named_generic_type("builtins.function", []) arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, "All arguments must be fully typed." arg_types.append(arg.type_annotation) arg_names.append(arg.variable.name) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) if tvar_def: signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.is_static = True func.info = info func.type = set_callable_name(signature, func) func._fullname = f"{info.fullname}.{name}" func.line = info.line # NOTE: we would like the plugin generated node to dominate, but we still # need to keep any existing definitions so they get semantically analyzed. if name in info.names: # Get a nice unique name instead. r_name = get_unique_redefinition_name(name, info.names) info.names[r_name] = info.names[name] info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True) info.defn.defs.body.append(func)
def add_method_to_class( api: Union[SemanticAnalyzerPluginInterface, CheckerPluginInterface], cls: ClassDef, name: str, args: List[Argument], return_type: Type, self_type: Optional[Type] = None, tvar_def: Optional[TypeVarType] = None, ) -> None: """Adds a new method to a class definition.""" info = cls.info # First remove any previously generated methods with the same name # to avoid clashes and problems in the semantic analyzer. if name in info.names: sym = info.names[name] if sym.plugin_generated and isinstance(sym.node, FuncDef): cls.defs.body.remove(sym.node) self_type = self_type or fill_typevars(info) # TODO: semanal.py and checker.py seem to have subtly different implementations of # named_type/named_generic_type (starting with the fact that we have to use different names # for builtins), so it's easier to just check which one we're dealing with here and pick the # correct function to use than to try to add a named_type method that behaves the same for # both. We should probably combine those implementations at some point. if isinstance(api, SemanticAnalyzerPluginInterface): function_type = api.named_type('__builtins__.function') else: function_type = api.named_generic_type('builtins.function', []) args = [Argument(Var('self'), self_type, None, ARG_POS)] + args arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, 'All arguments must be fully typed.' arg_types.append(arg.type_annotation) arg_names.append(arg.variable.name) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) if tvar_def: signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.info = info func.type = set_callable_name(signature, func) func._fullname = info.fullname + '.' + name func.line = info.line # NOTE: we would like the plugin generated node to dominate, but we still # need to keep any existing definitions so they get semantically analyzed. if name in info.names: # Get a nice unique name instead. r_name = get_unique_redefinition_name(name, info.names) info.names[r_name] = info.names[name] info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True) info.defn.defs.body.append(func)
def transform_class_def(self, tdef: ClassDef) -> List[Node]: """Transform a type definition. The result may be one or two definitions. The first is the transformation of the original ClassDef. The second is a wrapper type, which is generated for generic types only. """ defs = [] # type: List[Node] if tdef.info.type_vars: # This is a generic type. Insert type variable slots in # the class definition for new type variables, i.e. type # variables not mapped to superclass type variables. defs.extend(self.make_tvar_representation(tdef.info)) # Iterate over definitions and transform each of them. vars = set() # type: Set[Var] for d in tdef.defs.body: if isinstance(d, FuncDef): # Implicit cast from FuncDef[] to Node[] is safe below. defs.extend(Any(self.func_tf.transform_method(d))) elif isinstance(d, VarDef): defs.extend(self.transform_var_def(d)) for n in d.items: vars.add(n) elif isinstance(d, AssignmentStmt): self.transform_assignment(d) defs.append(d) # Add accessors for implicitly defined attributes. for node in tdef.info.names.values(): if isinstance(node.node, Var): v = cast(Var, node.node) if v.info == tdef.info and v not in vars: defs.extend(self.make_accessors(v)) # For generic classes, add an implicit __init__ wrapper. defs.extend(self.make_init_wrapper(tdef)) if tdef.is_generic() or (tdef.info.bases and tdef.info.mro[1].is_generic()): self.make_instance_tvar_initializer( cast(FuncDef, tdef.info.get_method('__init__'))) if not defs: defs.append(PassStmt()) if tdef.is_generic(): gen_wrapper = self.generic_class_wrapper(tdef) tdef.defs = Block(defs) dyn_wrapper = self.make_type_object_wrapper(tdef) if not tdef.is_generic(): return [tdef, dyn_wrapper] else: return [tdef, dyn_wrapper, gen_wrapper]
def _create_intersection(args, context, api): defn = ClassDef('Intersection', Block([])) defn.fullname = 'pfun.Intersection' info = TypeInfo({}, defn, 'pfun') info.is_protocol = True calculate_mro(info) i = Instance(info, args, line=context.line, column=context.column) intersection_translator = TranslateIntersection(api, i) return i.accept(intersection_translator)
def stale_info() -> TypeInfo: suggestion = "<stale cache: consider running mypy without --quick>" dummy_def = ClassDef(suggestion, Block([])) dummy_def.fullname = suggestion info = TypeInfo(SymbolTable(), dummy_def, "<stale>") info.mro = [info] info.bases = [] return info
def missing_info(modules: Dict[str, MypyFile]) -> TypeInfo: suggestion = _SUGGESTION.format('info') dummy_def = ClassDef(suggestion, Block([])) dummy_def.fullname = suggestion info = TypeInfo(SymbolTable(), dummy_def, "<missing>") obj_type = lookup_fully_qualified_typeinfo(modules, 'builtins.object', allow_missing=False) info.bases = [Instance(obj_type, [])] info.mro = [info, obj_type] return info
def add_info_hook(ctx): class_def = ClassDef(ctx.name, Block([])) class_def.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id) class_def.info = info obj = ctx.api.builtin_type('builtins.object') info.mro = [info, obj.type] info.bases = [obj] ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info)) DECL_BASES.add(class_def.fullname)
def add_info_hook(ctx) -> None: class_def = ClassDef(ctx.name, Block([])) class_def.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id) class_def.info = info obj = ctx.api.named_type('builtins.object') info.mro = [info, obj.type] info.bases = [obj] ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info)) info.metadata['magic'] = True
def translate_stmt_list(self, stmts: Sequence[ast27.stmt], module: bool = False) -> List[Statement]: # A "# type: ignore" comment before the first statement of a module # ignores the whole module: if (module and stmts and self.type_ignores and min(self.type_ignores) < self.get_lineno(stmts[0])): self.errors.used_ignored_lines[self.errors.file].add( min(self.type_ignores)) block = Block( self.fix_function_overloads(self.translate_stmt_list(stmts))) block.is_unreachable = True return [block] res = [] # type: List[Statement] for stmt in stmts: node = self.visit(stmt) assert isinstance(node, Statement) res.append(node) return res
def stale_info(modules: Dict[str, MypyFile]) -> TypeInfo: suggestion = "<stale cache: consider running mypy without --quick>" dummy_def = ClassDef(suggestion, Block([])) dummy_def.fullname = suggestion info = TypeInfo(SymbolTable(), dummy_def, "<stale>") obj_type = lookup_qualified(modules, 'builtins.object', False) assert isinstance(obj_type, TypeInfo) info.bases = [Instance(obj_type, [])] info.mro = [info, obj_type] return info
def missing_info(modules: Dict[str, MypyFile]) -> TypeInfo: suggestion = "<missing info: *should* have gone away during fine-grained update>" dummy_def = ClassDef(suggestion, Block([])) dummy_def.fullname = suggestion info = TypeInfo(SymbolTable(), dummy_def, "<missing>") obj_type = lookup_qualified(modules, 'builtins.object', False) assert isinstance(obj_type, TypeInfo) info.bases = [Instance(obj_type, [])] info.mro = [info, obj_type] return info
def add_info_hook(ctx: DynamicClassDefContext): class_def = ClassDef(ctx.name, Block([])) class_def.fullname = ctx.api.qualified_name(ctx.name) info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id) class_def.info = info queryset_type_fullname = ctx.call.args[0].fullname queryset_info = ctx.api.lookup_fully_qualified_or_none(queryset_type_fullname).node # type: TypeInfo obj = ctx.api.named_type('builtins.object') info.mro = [info, queryset_info, obj.type] info.bases = [Instance(queryset_info, [])] ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
def add_method_to_class( api: SemanticAnalyzerPluginInterface, cls: ClassDef, name: str, args: List[Argument], return_type: Type, self_type: Optional[Type] = None, tvar_def: Optional[TypeVarDef] = None, ) -> None: """Adds a new method to a class definition. """ info = cls.info # First remove any previously generated methods with the same name # to avoid clashes and problems in the semantic analyzer. if name in info.names: sym = info.names[name] if sym.plugin_generated and isinstance(sym.node, FuncDef): cls.defs.body.remove(sym.node) self_type = self_type or fill_typevars(info) function_type = api.named_type('__builtins__.function') args = [Argument(Var('self'), self_type, None, ARG_POS)] + args arg_types, arg_names, arg_kinds = [], [], [] for arg in args: assert arg.type_annotation, 'All arguments must be fully typed.' arg_types.append(arg.type_annotation) arg_names.append(arg.variable.name) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) if tvar_def: signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.info = info func.type = set_callable_name(signature, func) func._fullname = info.fullname + '.' + name func.line = info.line # NOTE: we would like the plugin generated node to dominate, but we still # need to keep any existing definitions so they get semantically analyzed. if name in info.names: # Get a nice unique name instead. r_name = get_unique_redefinition_name(name, info.names) info.names[r_name] = info.names[name] info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True) info.defn.defs.body.append(func)
def mark_block_unreachable(block: Block) -> None: block.is_unreachable = True block.accept(MarkImportsUnreachableVisitor())
def as_block(self, stmts: List[ast35.stmt], lineno: int) -> Block: b = None if stmts: b = Block(self.visit_list(stmts)) b.set_line(lineno) return b
def as_block(self, stmts: List[ast35.stmt], lineno: int) -> Block: b = None if stmts: b = Block(self.fix_function_overloads(self.visit_list(stmts))) b.set_line(lineno) return b
def visit_block(self, node: Block) -> None: super().visit_block(node) node.body = self.replace_statements(node.body)
def mark_block_mypy_only(block: Block) -> None: block.accept(MarkImportsMypyOnlyVisitor())
def as_block(self, stmts, lineno): b = None if stmts: b = Block(self.visit(stmts)) b.set_line(lineno) return b
def as_required_block(self, stmts: List[ast27.stmt], lineno: int) -> Block: assert stmts # must be non-empty b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) b.set_line(lineno) return b
def as_block(self, stmts: List[ast27.stmt], lineno: int) -> Optional[Block]: b = None if stmts: b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) b.set_line(lineno) return b