Example #1
0
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."""

    class_def = ClassDef(name, Block([]), None, [])
    class_def.fullname = name

    if typevars:
        v = []  # type: List[TypeVarDef]
        id = 1
        for n in typevars:
            v.append(TypeVarDef(n, id, None))
            id += 1
        class_def.type_vars = v

    info = TypeInfo(SymbolTable(), class_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
Example #2
0
 def visit_type_info(self, info: TypeInfo) -> None:
     save_info = self.current_info
     try:
         self.current_info = info
         if info.defn:
             info.defn.accept(self)
         if info.names:
             self.visit_symbol_table(info.names)
         if info.bases:
             for base in info.bases:
                 base.accept(self.type_fixer)
         if info._promote:
             info._promote.accept(self.type_fixer)
         if info.tuple_type:
             info.tuple_type.accept(self.type_fixer)
         if info.typeddict_type:
             info.typeddict_type.accept(self.type_fixer)
         if info.declared_metaclass:
             info.declared_metaclass.accept(self.type_fixer)
         if info.metaclass_type:
             info.metaclass_type.accept(self.type_fixer)
         if info._mro_refs:
             info.mro = [lookup_qualified_typeinfo(self.modules, name, self.quick_and_dirty)
                         for name in info._mro_refs]
             info._mro_refs = None
     finally:
         self.current_info = save_info
Example #3
0
 def visit_type_info(self, info: TypeInfo) -> None:
     save_info = self.current_info
     try:
         self.current_info = info
         if info.defn:
             info.defn.accept(self)
         if info.names:
             self.visit_symbol_table(info.names)
         if info.bases:
             for base in info.bases:
                 base.accept(self.type_fixer)
         if info._promote:
             info._promote.accept(self.type_fixer)
         if info.tuple_type:
             info.tuple_type.accept(self.type_fixer)
         if info.typeddict_type:
             info.typeddict_type.accept(self.type_fixer)
         if info.declared_metaclass:
             info.declared_metaclass.accept(self.type_fixer)
         if info.metaclass_type:
             info.metaclass_type.accept(self.type_fixer)
         if info._mro_refs:
             info.mro = [
                 lookup_qualified_typeinfo(self.modules, name,
                                           self.allow_missing)
                 for name in info._mro_refs
             ]
             info._mro_refs = None
     finally:
         self.current_info = save_info
Example #4
0
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
Example #5
0
 def visit_type_info(self, info: TypeInfo) -> None:
     save_info = self.current_info
     try:
         self.current_info = info
         if info.defn:
             info.defn.accept(self)
         if info.names:
             self.visit_symbol_table(info.names)
         if info.bases:
             for base in info.bases:
                 base.accept(self.type_fixer)
         if info._promote:
             info._promote.accept(self.type_fixer)
         if info.tuple_type:
             info.tuple_type.accept(self.type_fixer)
         if info.typeddict_type:
             info.typeddict_type.accept(self.type_fixer)
         if info.declared_metaclass:
             info.declared_metaclass.accept(self.type_fixer)
         if info.metaclass_type:
             info.metaclass_type.accept(self.type_fixer)
         if info._mro_refs:
             # If the class is a "-redefinition", then its
             # reference to itself might be busted, so just use the
             # info instead of looking up the first element. Ew.
             info.mro = [info] + [
                 lookup_qualified_typeinfo(self.modules, name,
                                           self.allow_missing)
                 for name in info._mro_refs[1:]
             ]
             info._mro_refs = None
     finally:
         self.current_info = save_info
Example #6
0
    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))
Example #7
0
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))
Example #8
0
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
Example #9
0
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
Example #10
0
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
Example #11
0
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
Example #12
0
 def strip_type_info(self, info: TypeInfo) -> None:
     info.type_vars = []
     info.bases = []
     info.abstract_attributes = []
     info.mro = []
     info.add_type_vars()
     info.tuple_type = None
     info.typeddict_type = None
     info.tuple_type = None
     info._cache = set()
     info._cache_proper = set()
Example #13
0
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
Example #14
0
def named_hook(ctx: DynamicClassDefContext) -> None:
    breakpoint()
    info = TypeInfo(SymbolTable(), ctx.call.args[1], ctx.api.cur_mod_id)
    ctx.call.args[1].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))
    print("hoi")
    return
Example #15
0
File: mro.py Project: sthagen/mypy
def calculate_mro(info: TypeInfo, obj_type: Optional[Callable[[], Instance]] = None) -> None:
    """Calculate and set mro (method resolution order).

    Raise MroError if cannot determine mro.
    """
    mro = linearize_hierarchy(info, obj_type)
    assert mro, "Could not produce a MRO at all for %s" % (info,)
    info.mro = mro
    # The property of falling back to Any is inherited.
    info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro)
    TypeState.reset_all_subtype_caches_for(info)
Example #16
0
File: fixup.py Project: python/mypy
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
Example #17
0
def calculate_mro(info: TypeInfo, obj_type: Optional[Callable[[], Instance]] = None) -> None:
    """Calculate and set mro (method resolution order).

    Raise MroError if cannot determine mro.
    """
    mro = linearize_hierarchy(info, obj_type)
    assert mro, "Could not produce a MRO at all for %s" % (info,)
    info.mro = mro
    # The property of falling back to Any is inherited.
    info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro)
    TypeState.reset_all_subtype_caches_for(info)
Example #18
0
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)
Example #19
0
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 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.builtin_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
Example #21
0
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))
Example #22
0
 def strip_type_info(self, info: TypeInfo) -> None:
     info.type_vars = []
     info.bases = []
     info.is_abstract = False
     info.abstract_attributes = []
     info.mro = []
     info.add_type_vars()
     info.tuple_type = None
     info.typeddict_type = None
     info.tuple_type = None
     TypeState.reset_subtype_caches_for(info)
     info.declared_metaclass = None
     info.metaclass_type = None
Example #23
0
def make_fake_register_class_instance(api: CheckerPluginInterface, type_args: Sequence[Type]
                                      ) -> Instance:
    defn = ClassDef(REGISTER_RETURN_CLASS, Block([]))
    defn.fullname = f'functools.{REGISTER_RETURN_CLASS}'
    info = TypeInfo(SymbolTable(), defn, "functools")
    obj_type = api.named_generic_type('builtins.object', []).type
    info.bases = [Instance(obj_type, [])]
    info.mro = [info, obj_type]
    defn.info = info

    func_arg = Argument(Var('name'), AnyType(TypeOfAny.implementation_artifact), None, ARG_POS)
    add_method_to_class(api, defn, '__call__', [func_arg], NoneType())

    return Instance(info, type_args)
Example #24
0
 def strip_type_info(self, info: TypeInfo) -> None:
     info.type_vars = []
     info.bases = []
     info.is_abstract = False
     info.abstract_attributes = []
     info.mro = []
     info.add_type_vars()
     info.tuple_type = None
     info.typeddict_type = None
     info.tuple_type = None
     info._cache = set()
     info._cache_proper = set()
     info.declared_metaclass = None
     info.metaclass_type = None
Example #25
0
    def make_type_info(self,
                       name: str,
                       module_name: Optional[str] = None,
                       is_abstract: bool = False,
                       mro: Optional[List[TypeInfo]] = None,
                       bases: Optional[List[Instance]] = None,
                       typevars: Optional[List[str]] = None,
                       variances: Optional[List[int]] = None) -> TypeInfo:
        """Make a TypeInfo suitable for use in unit tests."""

        class_def = ClassDef(name, Block([]), None, [])
        class_def.fullname = name

        if module_name is None:
            if '.' in name:
                module_name = name.rsplit('.', 1)[0]
            else:
                module_name = '__main__'

        if typevars:
            v: List[TypeVarLikeType] = []
            for id, n in enumerate(typevars, 1):
                if variances:
                    variance = variances[id - 1]
                else:
                    variance = COVARIANT
                v.append(TypeVarType(n, n, id, [], self.o, variance=variance))
            class_def.type_vars = v

        info = TypeInfo(SymbolTable(), class_def, module_name)
        if mro is None:
            mro = []
            if name != 'builtins.object':
                mro.append(self.oi)
        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
Example #26
0
    def _basic_new_typeinfo(self, ctx: AnalyzeTypeContext, name: str,
                            basetype_or_fallback: Instance) -> TypeInfo:
        """
        Build a basic :class:`.TypeInfo`.

        This was basically lifted from ``mypy.semanal``.
        """
        class_def = ClassDef(name, Block([]))
        class_def.fullname = name

        info = TypeInfo(SymbolTable(), class_def, '')
        class_def.info = info
        mro = basetype_or_fallback.type.mro
        if not mro:
            mro = [basetype_or_fallback.type,
                   named_builtin_type(ctx, 'object').type]
        info.mro = [info] + mro
        info.bases = [basetype_or_fallback]
        return info
Example #27
0
    def make_type_info(self, name: str,
                       module_name: Optional[str] = None,
                       is_abstract: bool = False,
                       mro: Optional[List[TypeInfo]] = None,
                       bases: Optional[List[Instance]] = None,
                       typevars: Optional[List[str]] = None,
                       variances: Optional[List[int]] = None) -> TypeInfo:
        """Make a TypeInfo suitable for use in unit tests."""

        class_def = ClassDef(name, Block([]), None, [])
        class_def.fullname = name

        if module_name is None:
            if '.' in name:
                module_name = name.rsplit('.', 1)[0]
            else:
                module_name = '__main__'

        if typevars:
            v = []  # type: List[TypeVarDef]
            for id, n in enumerate(typevars, 1):
                if variances:
                    variance = variances[id - 1]
                else:
                    variance = COVARIANT
                v.append(TypeVarDef(n, n, id, [], self.o, variance=variance))
            class_def.type_vars = v

        info = TypeInfo(SymbolTable(), class_def, module_name)
        if mro is None:
            mro = []
            if name != 'builtins.object':
                mro.append(self.oi)
        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
Example #28
0
    def strip_type_info(self, info: TypeInfo) -> List[SymbolNode]:
        info.type_vars = []
        info.bases = []
        info.is_abstract = False
        info.abstract_attributes = []
        info.mro = []
        info.add_type_vars()
        info.tuple_type = None
        info.typeddict_type = None
        info.tuple_type = None
        TypeState.reset_subtype_caches_for(info)
        info.declared_metaclass = None
        info.metaclass_type = None

        # We need to delete any entries that were generated by plugins,
        # since they will get regenerated.
        to_delete = [(k, v) for k, v in info.names.items() if v.plugin_generated]
        for k, _ in to_delete:
            del info.names[k]
        return [v.node for k, v in to_delete if v.node]
Example #29
0
def decl_info_hook(ctx):
    """Support dynamically defining declarative bases.

    For example:
        from sqlalchemy.ext.declarative import declarative_base

        Base = declarative_base()
    """
    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))
    set_declarative(info)

    # TODO: check what else is added.
    add_metadata_var(ctx, info)
Example #30
0
    def strip_type_info(self, info: TypeInfo) -> List[SymbolNode]:
        info.type_vars = []
        info.bases = []
        info.is_abstract = False
        info.abstract_attributes = []
        info.mro = []
        info.add_type_vars()
        info.tuple_type = None
        info.typeddict_type = None
        info.tuple_type = None
        TypeState.reset_subtype_caches_for(info)
        info.declared_metaclass = None
        info.metaclass_type = None

        # We need to delete any entries that were generated by plugins,
        # since they will get regenerated.
        to_delete = [(k, v) for k, v in info.names.items()
                     if v.plugin_generated]
        for k, _ in to_delete:
            del info.names[k]
        return [v.node for k, v in to_delete if v.node]
Example #31
0
    def dyn_class_hook(self, ctx: DynamicClassDefContext) -> TypedDictType:
        """Generate annotations from a JSON Schema."""
        schema_path, = ctx.call.args
        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)

        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)
        info.typeddict_type = td_type

        dict_type = named_builtin_type(ctx, 'dict')
        mro = dict_type.type.mro
        if not mro:
            mro = [dict_type.type, named_builtin_type(ctx, 'object').type]

        class_def.info = info
        info.mro = mro
        info.bases = [dict_type]
        ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
Example #32
0
    def make_type_info(self,
                       name: str,
                       is_abstract: bool = False,
                       mro: List[TypeInfo] = None,
                       bases: List[Instance] = None,
                       typevars: List[str] = None,
                       variances: List[int] = None) -> TypeInfo:
        """Make a TypeInfo suitable for use in unit tests."""

        class_def = ClassDef(name, Block([]), None, [])
        class_def.fullname = name

        if typevars:
            v = []  # type: List[TypeVarDef]
            for id, n in enumerate(typevars, 1):
                if variances:
                    variance = variances[id - 1]
                else:
                    variance = COVARIANT
                v.append(TypeVarDef(n, id, None, self.o, variance=variance))
            class_def.type_vars = v

        info = TypeInfo(SymbolTable(), class_def)
        if mro is None:
            mro = []
            if name != 'builtins.object':
                mro.append(self.oi)
        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