Exemplo n.º 1
0
 def base_class_definitions_incompatible(self, name: str, base1: TypeInfo,
                                         base2: TypeInfo,
                                         context: Context) -> None:
     self.fail(
         'Definition of "{}" in base class "{}" is incompatible '
         'with definition in base class "{}"'.format(
             name, base1.name(), base2.name()), context)
Exemplo n.º 2
0
 def base_class_definitions_incompatible(
     self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context
 ) -> None:
     self.fail(
         'Definition of "{}" in base class "{}" is incompatible '
         'with definition in base class "{}"'.format(name, base1.name(), base2.name()),
         context,
     )
Exemplo n.º 3
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
                           valids: List[Type], arg_number: int, context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value) for value in valids)):
             if len(actuals) > 1 or not isinstance(actual, Instance):
                 self.fail('Invalid type argument value for "{}"'.format(
                     type.name()), context)
             else:
                 self.fail('Type argument {} of "{}" has incompatible value "{}"'.format(
                     arg_number, type.name(), actual.type.name()), context)
Exemplo n.º 4
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
                           valids: List[Type], arg_number: int, context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value) for value in valids)):
             if len(actuals) > 1 or not isinstance(actual, Instance):
                 self.fail('Invalid type argument value for "{}"'.format(
                     type.name()), context)
             else:
                 self.fail('Type argument {} of "{}" has incompatible value "{}"'.format(
                     arg_number, type.name(), actual.type.name()), context)
Exemplo n.º 5
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: str,
                           valids: List[Type], arg_number: int, context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value)
                         for value in valids)):
             if len(actuals) > 1 or not isinstance(actual, Instance):
                 self.fail('Invalid type argument value for "{}"'.format(
                     type.name()), context)
             else:
                 class_name = '"{}"'.format(type.name())
                 actual_type_name = '"{}"'.format(actual.type.name())
                 self.fail(messages.INCOMPATIBLE_TYPEVAR_VALUE.format(
                     arg_name, class_name, actual_type_name), context)
Exemplo n.º 6
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: str,
                           valids: List[Type], arg_number: int, context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value)
                         for value in valids)):
             if len(actuals) > 1 or not isinstance(actual, Instance):
                 self.fail('Invalid type argument value for "{}"'.format(
                     type.name()), context)
             else:
                 class_name = '"{}"'.format(type.name())
                 actual_type_name = '"{}"'.format(actual.type.name())
                 self.fail(messages.INCOMPATIBLE_TYPEVAR_VALUE.format(
                     arg_name, class_name, actual_type_name), context)
Exemplo n.º 7
0
def check_model_values(ctx: Union[MethodContext, FunctionContext],
                       model: TypeInfo, arg_name: str) -> None:
    arg_index = ctx.callee_arg_names.index('values')
    expected_types = get_expected_model_types(model)

    for actual_name, actual_type in zip(ctx.arg_names[arg_index],
                                        ctx.arg_types[arg_index]):
        if actual_name is None:
            continue

        if actual_name not in expected_types:
            ctx.api.fail(
                f'Unexpected argument "{actual_name}"'.format(
                    actual_name, model.name()),
                ctx.context,
            )
            continue

        # Using private API to simplify life.
        ctx.api.check_subtype(  # type: ignore
            actual_type,
            expected_types[actual_name],
            ctx.context,
            f'Incompatible type for argument "{actual_name}"',
            'got',
            'expected',
        )
Exemplo n.º 8
0
def nearest_builtin_ancestor(type: TypeInfo) -> TypeInfo:
    for base in type.mro:
        if base.defn.is_builtinclass:
            return base
    else:
        return None
        assert False, 'No built-in ancestor found for {}'.format(type.name())
Exemplo n.º 9
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
                           valids: List[Type], context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value) for value in valids)):
             self.fail('Invalid type argument value for "{}"'.format(
                 type.name()), context)
Exemplo n.º 10
0
def nearest_builtin_ancestor(type: TypeInfo) -> TypeInfo:
    for base in type.mro:
        if base.defn.is_builtinclass:
            return base
    else:
        return None
        assert False, 'No built-in ancestor found for {}'.format(type.name())
Exemplo n.º 11
0
 def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
                           valids: List[Type], context: Context) -> None:
     for actual in actuals:
         if (not isinstance(actual, AnyType) and
                 not any(is_same_type(actual, value) for value in valids)):
             self.fail('Invalid type argument value for "{}"'.format(
                 type.name()), context)
Exemplo n.º 12
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance,
                   special_sig: Optional[str],
                   is_new: bool) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    variables.extend(info.defn.type_vars)
    variables.extend(init_type.variables)

    from mypy.subtypes import is_subtype

    init_ret_type = get_proper_type(init_type.ret_type)
    default_ret_type = fill_typevars(info)
    if (
        is_new
        and isinstance(init_ret_type, (Instance, TupleType))
        # Only use the return type from __new__ if it is actually returning
        # a subtype of what we would return otherwise.
        and is_subtype(init_ret_type, default_ret_type, ignore_type_params=True)
    ):
        ret_type = init_ret_type  # type: Type
    else:
        ret_type = default_ret_type

    callable_type = init_type.copy_modified(
        ret_type=ret_type, fallback=type_type, name=None, variables=variables,
        special_sig=special_sig)
    c = callable_type.with_name(info.name())
    return c
Exemplo n.º 13
0
    def type_suffix(self, fdef: FuncDef, info: TypeInfo = None) -> str:
        """Return the suffix for a mangled name.

        This includes an optional type suffix for a function or method.
        """
        if not info:
            info = fdef.info
        # If info is None, we have a global function => no suffix. Also if the
        # method is not an override, we need no suffix.
        if not info or (not info.bases or not info.bases[0].type.has_method(fdef.name())):
            return ""
        elif is_simple_override(fdef, info):
            return self.type_suffix(fdef, info.bases[0].type)
        elif self.is_pretty:
            return "`" + info.name()
        else:
            return "__" + info.name()
Exemplo n.º 14
0
 def enter_class_scope(self, info: TypeInfo) -> str:
     """Enter a class target scope."""
     # Duplicate the previous top non-class target (it can't be a class but since the
     # depths of all stacks must agree we need something).
     self.target_stack.append(self.target_stack[-1])
     full_target = '%s.%s' % (self.full_target_stack[-1], info.name())
     self.full_target_stack.append(full_target)
     self.scope_stack.append(info)
     return full_target
Exemplo n.º 15
0
 def enter_class_scope(self, info: TypeInfo) -> str:
     """Enter a class target scope."""
     # Duplicate the previous top non-class target (it can't be a class but since the
     # depths of all stacks must agree we need something).
     self.target_stack.append(self.target_stack[-1])
     full_target = '%s.%s' % (self.full_target_stack[-1], info.name())
     self.full_target_stack.append(full_target)
     self.scope_stack.append(info)
     return full_target
Exemplo n.º 16
0
    def type_suffix(self, fdef: FuncDef, info: TypeInfo = None) -> str:
        """Return the suffix for a mangled name.

        This includes an optional type suffix for a function or method.
        """
        if not info:
            info = fdef.info
        # If info is None, we have a global function => no suffix. Also if the
        # method is not an override, we need no suffix.
        if not info or (not info.bases
                        or not info.bases[0].type.has_method(fdef.name())):
            return ''
        elif is_simple_override(fdef, info):
            return self.type_suffix(fdef, info.bases[0].type)
        elif self.is_pretty:
            return '`' + info.name()
        else:
            return '__' + info.name()
Exemplo n.º 17
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance,
                   special_sig: Optional[str]) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    variables.extend(info.defn.type_vars)
    variables.extend(init_type.variables)

    callable_type = init_type.copy_modified(
        ret_type=fill_typevars(info), fallback=type_type, name=None, variables=variables,
        special_sig=special_sig)
    c = callable_type.with_name(info.name())
    return c
Exemplo n.º 18
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance,
                   special_sig: Optional[str]) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    variables.extend(info.defn.type_vars)
    variables.extend(init_type.variables)

    callable_type = init_type.copy_modified(
        ret_type=fill_typevars(info), fallback=type_type, name=None, variables=variables,
        special_sig=special_sig)
    c = callable_type.with_name(info.name())
    return c
Exemplo n.º 19
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    for i, tvar in enumerate(info.defn.type_vars):
        variables.append(TypeVarDef(tvar.name, i + 1, tvar.values, tvar.upper_bound, tvar.variance))

    initvars = init_type.variables
    variables.extend(initvars)

    c = CallableType(
        init_type.arg_types, init_type.arg_kinds, init_type.arg_names, self_type(info), type_type, None, variables
    ).with_name('"{}"'.format(info.name()))
    return convert_class_tvars_to_func_tvars(c, len(initvars))
Exemplo n.º 20
0
def class_callable(init_type: Callable, info: TypeInfo) -> Callable:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    for i, tvar in enumerate(info.defn.type_vars):
        variables.append(TypeVarDef(tvar.name, i + 1, tvar.values))

    initvars = init_type.variables
    variables.extend(initvars)

    c = Callable(init_type.arg_types, init_type.arg_kinds, init_type.arg_names,
                 self_type(info), True, None,
                 variables).with_name('"{}"'.format(info.name()))
    return convert_class_tvars_to_func_tvars(c, len(initvars))
Exemplo n.º 21
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    for i, tvar in enumerate(info.defn.type_vars):
        variables.append(TypeVarDef(tvar.name, i + 1, tvar.values, tvar.upper_bound,
                                    tvar.variance))

    initvars = init_type.variables
    variables.extend(initvars)

    callable_type = init_type.copy_modified(
        ret_type=self_type(info), fallback=type_type, name=None, variables=variables)
    c = callable_type.with_name('"{}"'.format(info.name()))
    return convert_class_tvars_to_func_tvars(c, len(initvars))
Exemplo n.º 22
0
 def __init__(self, type: TypeInfo, base: 'ClassRepresentation') -> None:
     self.cname = 'MR_%s' % type.name()
     self.fullname = type.fullname()
     self.slotmap = {}
     self.vtable_index = {}
     self.defining_class = {}
     self.vtable_methods = []
     if base:
         self.inherit_from_base(base)
     for m in sorted(type.names):
         if isinstance(type.names[m].node, FuncBase):
             self.add_method(m, type)
         else:
             self.slotmap[m] = len(self.slotmap)
             self.add_method('_' + m, type)    # Getter TODO refactor
             self.add_method('set_' + m, type) # Setter # TODO refactor
Exemplo n.º 23
0
Arquivo: cgen.py Projeto: silky/mypy
 def __init__(self, type: TypeInfo, base: 'ClassRepresentation') -> None:
     self.cname = 'MR_%s' % type.name()
     self.fullname = type.fullname()
     self.slotmap = {}
     self.vtable_index = {}
     self.defining_class = {}
     self.vtable_methods = []
     if base:
         self.inherit_from_base(base)
     for m in sorted(type.names):
         if isinstance(type.names[m].node, FuncBase):
             self.add_method(m, type)
         else:
             self.slotmap[m] = len(self.slotmap)
             self.add_method('_' + m, type)  # Getter TODO refactor
             self.add_method('set_' + m, type)  # Setter # TODO refactor
Exemplo n.º 24
0
def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    for i, tvar in enumerate(info.defn.type_vars):
        variables.append(TypeVarDef(tvar.name, i + 1, tvar.values, tvar.upper_bound,
                                    tvar.variance))

    initvars = init_type.variables
    variables.extend(initvars)

    callable_type = init_type.copy_modified(
        ret_type=self_type(info), fallback=type_type, name=None, variables=variables)
    c = callable_type.with_name('"{}"'.format(info.name()))
    cc = convert_class_tvars_to_func_tvars(c, len(initvars))
    cc.is_classmethod_class = True
    return cc
Exemplo n.º 25
0
def class_callable(init_type: Callable, info: TypeInfo) -> Callable:
    """Create a type object type based on the signature of __init__."""
    variables = [] # type: List[TypeVarDef]
    for i in range(len(info.type_vars)): # TODO bounds
        variables.append(TypeVarDef(info.type_vars[i], i + 1, None))

    initvars = init_type.variables
    variables.extend(initvars)

    c = Callable(init_type.arg_types,
                 init_type.arg_kinds,
                 init_type.arg_names,
                 self_type(info),
                 True,
                 None,
                 variables).with_name('"{}"'.format(info.name()))
    return convert_class_tvars_to_func_tvars(c, len(initvars))
Exemplo n.º 26
0
def class_callable(init_type: CallableType, info: TypeInfo,
                   type_type: Instance, special_sig: Optional[str],
                   is_new: bool) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    variables.extend(info.defn.type_vars)
    variables.extend(init_type.variables)

    init_ret_type = get_proper_type(init_type.ret_type)
    if is_new and isinstance(init_ret_type, (Instance, TupleType)):
        ret_type = init_type.ret_type  # type: Type
    else:
        ret_type = fill_typevars(info)

    callable_type = init_type.copy_modified(ret_type=ret_type,
                                            fallback=type_type,
                                            name=None,
                                            variables=variables,
                                            special_sig=special_sig)
    c = callable_type.with_name(info.name())
    return c
Exemplo n.º 27
0
Arquivo: cgen.py Projeto: silky/mypy
    def generate_class(self, cls: TypeInfo) -> 'ClassRepresentation':
        if cls.bases:
            baserep = self.get_class_representation(cls.bases[0].type)
        else:
            baserep = None
        rep = ClassRepresentation(cls, baserep)
        self.classes[cls] = rep

        # Emit vtable.
        vtable = 'MVT_%s' % cls.name()
        self.emit_types('MFunction %s[] = {' % vtable)
        for m in rep.vtable_methods:
            defining_class = rep.defining_class[m]
            self.emit_types('    M%s_%s,' % (defining_class, m))
        self.emit_types('}; /* %s */' % vtable)

        # Emit type runtime info.
        self.emit_types('MTypeRepr %s = {' % rep.cname)
        self.emit_types('    %s,' % vtable)
        self.emit_types('    0,')
        self.emit_types('    "%s"' % cls.fullname())
        self.emit_types('};\n')

        return rep
Exemplo n.º 28
0
    def generate_class(self, cls: TypeInfo) -> 'ClassRepresentation':
        if cls.bases:
            baserep = self.get_class_representation(cls.bases[0].type)
        else:
            baserep = None
        rep = ClassRepresentation(cls, baserep)
        self.classes[cls] = rep

        # Emit vtable.
        vtable = 'MVT_%s' % cls.name()
        self.emit_types('MFunction %s[] = {' % vtable)
        for m in rep.vtable_methods:
            defining_class = rep.defining_class[m]
            self.emit_types('    M%s_%s,' % (defining_class, m))
        self.emit_types('}; /* %s */' % vtable)

        # Emit type runtime info.
        self.emit_types('MTypeRepr %s = {' % rep.cname)
        self.emit_types('    %s,' % vtable)
        self.emit_types('    0,')
        self.emit_types('    "%s"' % cls.fullname())
        self.emit_types('};\n')
        
        return rep
Exemplo n.º 29
0
 def read_only_property(self, name: str, type: TypeInfo,
                        context: Context) -> None:
     self.fail(
         'Property "{}" defined in "{}" is read-only'.format(
             name, type.name()), context)
Exemplo n.º 30
0
 def read_only_property(self, name: str, type: TypeInfo,
                        context: Context) -> None:
     self.fail('Property "{}" defined in "{}" is read-only'.format(
         name, type.name()), context)
Exemplo n.º 31
0
 def add_method(self, method: str, defining_class: TypeInfo) -> None:
     self.defining_class[method] = defining_class.name()
     if method not in self.vtable_index:
         self.vtable_index[method] = len(self.vtable_methods)
         self.vtable_methods.append(method)
Exemplo n.º 32
0
Arquivo: cgen.py Projeto: silky/mypy
 def add_method(self, method: str, defining_class: TypeInfo) -> None:
     self.defining_class[method] = defining_class.name()
     if method not in self.vtable_index:
         self.vtable_index[method] = len(self.vtable_methods)
         self.vtable_methods.append(method)
Exemplo n.º 33
0
 def disjointness_violation(self, cls: TypeInfo, disjoint: TypeInfo,
                            context: Context) -> None:
     self.fail('disjointclass constraint of class {} disallows {} as a '
               'base class'.format(cls.name(), disjoint.name()), context)
Exemplo n.º 34
0
 def disjointness_violation(self, cls: TypeInfo, disjoint: TypeInfo,
                            context: Context) -> None:
     self.fail('disjointclass constraint of class {} disallows {} as a '
               'base class'.format(cls.name(), disjoint.name()), context)