Beispiel #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))
Beispiel #2
0
 def testReplaceTypes(self):
   src = textwrap.dedent("""
       class A(object):
           def a(self, a: A or B) -> A or B raises A, B
   """)
   expected = textwrap.dedent("""
       class A(object):
           def a(self: A2, a: A2 or B) -> A2 or B raises A2, B
   """)
   tree = self.Parse(src)
   new_tree = tree.Visit(visitors.ReplaceTypes({"A": pytd.NamedType("A2")}))
   self.AssertSourceEquals(new_tree, expected)
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
0
    def p_funcdef(self, p):
        """funcdef : DEF NAME LPAREN params RPAREN return raises signature maybe_body"""
        _, _, name, _, params, _, return_type, raises, _, body = p
        # TODO(kramm): Output a warning if we already encountered a signature
        #              with these types (but potentially different argument names)
        if name == '__init__' and isinstance(return_type, pytd.AnythingType):
            ret = pytd.NamedType('NoneType')
        else:
            ret = return_type
        signature = pytd.Signature(params=tuple(params.required),
                                   return_type=ret,
                                   exceptions=tuple(raises),
                                   template=(),
                                   has_optional=params.has_optional)

        typeparams = {
            name: pytd.TypeParameter(name)
            for name in self.context.typevars
        }
        used_typeparams = set()
        signature = signature.Visit(
            visitors.ReplaceTypes(typeparams, used_typeparams))
        if used_typeparams:
            signature = signature.Replace(template=tuple(
                pytd.TemplateItem(typeparams[name])
                for name in used_typeparams))

        for mutator in body:
            try:
                signature = signature.Visit(mutator)
            except NotImplementedError as e:
                make_syntax_error(self, e.message, p)
            if not mutator.successful:
                make_syntax_error(self, 'No parameter named %s' % mutator.name,
                                  p)
        p[0] = NameAndSig(name=name, signature=signature, external_code=False)
Beispiel #6
0
 def VisitSignature(self, node):
     return node.Visit(
         visitors.ReplaceTypes(
             {p.name: p.type_param
              for p in node.template}))
Beispiel #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 abstract.FailedFunctionCall
    will be raised. Other cases may raise abstract.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: an abstract.FunctionArgs 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.ConversionError occurs or if field names are invalid, this
      function returns Unsolvable (in a Variable) instead of a PyTDClass.

    Raises:
      abstract.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.ConversionError:
      return node, self.vm.convert.unsolvable.to_variable(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.get_atomic_python_constant(name_var)
    except abstract.ConversionError:
      return node, self.vm.convert.unsolvable.to_variable(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, e.message)
      return node, self.vm.convert.unsolvable.to_variable(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)