Ejemplo n.º 1
0
def insert_solution(result, mapping, global_lookup):
    """Replace ~unknown types in a pytd with the actual (solved) types."""
    subst = {
        unknown: convert_string_type_list(types_as_strings, unknown, mapping,
                                          global_lookup)
        for unknown, types_as_strings in mapping.items()
    }
    result = result.Visit(optimize.RenameUnknowns(subst))
    # We remove duplicates here (even though Optimize does so again) because
    # it's much faster before the string types are replaced.
    result = result.Visit(optimize.RemoveDuplicates())
    return result.Visit(visitors.ReplaceTypes(subst))
Ejemplo n.º 2
0
 def testRemoveInheritedMethodsWithLateType(self):
     src = textwrap.dedent("""
     class Foo(other.Bar):
       def bar() -> float
 """)
     expected = textwrap.dedent("""
     class Foo(other.Bar):
       def bar() -> float
 """)
     ast = self.Parse(src)
     ast = ast.Visit(
         visitors.ReplaceTypes({"other.Bar": pytd.LateType("other.Bar")}))
     ast = ast.Visit(optimize.RemoveInheritedMethods())
     ast = ast.Visit(visitors.LateTypeToClassType())
     self.AssertSourceEquals(ast, expected)
Ejemplo n.º 3
0
 def testFindCommonSuperClasses(self):
   src = textwrap.dedent("""
       x = ...  # type: int or other.Bar
   """)
   expected = textwrap.dedent("""
       x = ...  # type: int or other.Bar
   """)
   ast = self.Parse(src)
   ast = ast.Visit(visitors.ReplaceTypes(
       {"other.Bar": pytd.LateType("other.Bar")}))
   hierarchy = ast.Visit(visitors.ExtractSuperClassesByName())
   ast = ast.Visit(optimize.FindCommonSuperClasses(
       optimize.SuperClassHierarchy(hierarchy)))
   ast = ast.Visit(visitors.LateTypeToClassType())
   self.AssertSourceEquals(ast, expected)
Ejemplo n.º 4
0
 def testReplaceTypes(self):
   src = textwrap.dedent("""
       class A(object):
           def a(self, a: A or B) -> A or B:
               raise A()
               raise B()
   """)
   expected = textwrap.dedent("""
       class A(object):
           def a(self: A2, a: A2 or B) -> A2 or B:
               raise A2()
               raise B()
   """)
   tree = self.Parse(src)
   new_tree = tree.Visit(visitors.ReplaceTypes({"A": pytd.NamedType("A2")}))
   self.AssertSourceEquals(new_tree, expected)
Ejemplo n.º 5
0
 def test_find_common_superclasses(self):
     src = pytd_src("""
     x = ...  # type: Union[int, other.Bar]
 """)
     expected = pytd_src("""
     x = ...  # type: Union[int, other.Bar]
 """)
     ast = self.Parse(src)
     ast = ast.Visit(
         visitors.ReplaceTypes({"other.Bar": pytd.LateType("other.Bar")}))
     hierarchy = ast.Visit(visitors.ExtractSuperClassesByName())
     ast = ast.Visit(
         optimize.FindCommonSuperClasses(
             optimize.SuperClassHierarchy(hierarchy)))
     ast = ast.Visit(visitors.LateTypeToClassType())
     self.AssertSourceEquals(ast, expected)
Ejemplo n.º 6
0
 def test_replace_types(self):
   src = textwrap.dedent("""
       from typing import Union
       class A:
           def a(self, a: Union[A, B]) -> Union[A, B]:
               raise A()
               raise B()
   """)
   expected = textwrap.dedent("""
       from typing import Union
       class A:
           def a(self: A2, a: Union[A2, B]) -> Union[A2, B]:
               raise A2()
               raise B()
   """)
   tree = self.Parse(src)
   new_tree = tree.Visit(visitors.ReplaceTypes({"A": pytd.NamedType("A2")}))
   self.AssertSourceEquals(new_tree, expected)
Ejemplo n.º 7
0
    def call(self, node, _, args):
        """Creates a namedtuple class definition.

    Performs the same argument checking as collections.namedtuple, e.g. making
    sure field names don't start with _ or digits, making sure no keywords are
    used for the typename or field names, and so on. Because the methods of the
    class have to be changed to match the number and names of the fields, we
    construct pytd.Function and pytd.Constant instances for each member of the
    class. Finally, the pytd.Class is wrapped in an abstract.PyTDClass.

    If incorrect arguments are passed, a subclass of function.FailedFunctionCall
    will be raised. Other cases may raise abstract_utils.ConversionError
    exceptions, such as when the arguments are in unicode or any of the
    arguments have multiple bindings, but these are caught and return Any. This
    also occurs if an argument to namedtuple is invalid, e.g. a keyword is used
    as a field name and rename is False.

    Arguments:
      node: the current CFG node
      _: the func binding, ignored.
      args: a function.Args instance

    Returns:
      a tuple of the given CFG node and an abstract.PyTDClass instance (wrapped
      in a Variable) representing the constructed namedtuple class.
      If a abstract_utils.ConversionError occurs or if field names are invalid,
      this function returns Unsolvable (in a Variable) instead of a PyTDClass.

    Raises:
      function.FailedFunctionCall: Raised by _getargs if any of the arguments
        do not match the function signature.
    """
        # If we can't extract the arguments, we take the easy way out and return Any
        try:
            name_var, field_names, rename = self._getargs(node, args)
        except abstract_utils.ConversionError:
            return node, self.vm.new_unsolvable(node)

        # We need the bare name for a few things, so pull that out now.
        # The same unicode issue can strike here, so again return Any.
        try:
            name = abstract_utils.get_atomic_python_constant(name_var)
        except abstract_utils.ConversionError:
            return node, self.vm.new_unsolvable(node)

        # namedtuple does some checking and optionally renaming of field names,
        # so we do too.
        try:
            field_names = self._validate_and_rename_args(
                name, field_names, rename)
        except ValueError as e:
            self.vm.errorlog.invalid_namedtuple_arg(self.vm.frames,
                                                    utils.message(e))
            return node, self.vm.new_unsolvable(node)

        name = namedtuple_name(name, field_names)
        ast = namedtuple_ast(name,
                             field_names,
                             python_version=self.vm.python_version)
        mapping = self._get_known_types_mapping()

        # A truly well-formed pyi for the namedtuple will have references to the new
        # namedtuple class itself for all `self` params and as the return type for
        # methods like __new__, _replace and _make. In order to do that, we need a
        # ClassType.
        cls_type = pytd.ClassType(name)
        mapping[name] = cls_type

        cls = ast.Lookup(name).Visit(visitors.ReplaceTypes(mapping))
        cls_type.cls = cls

        # Make sure all NamedType nodes have been replaced by ClassType nodes with
        # filled cls pointers.
        cls.Visit(visitors.VerifyLookup())

        # We can't build the PyTDClass directly, and instead must run it through
        # convert.constant_to_value first, for caching.
        instance = self.vm.convert.constant_to_value(cls, {},
                                                     self.vm.root_cfg_node)
        self.vm.trace_namedtuple(instance)
        return node, instance.to_variable(node)