def check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None, **kwargs): """Verify the Python code.""" tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric("memory", metrics.Snapshot) snapshotter.take_snapshot("analyze:check_types:tracer") if deep: if maximum_depth is None: maximum_depth = (QUICK_CHECK_MAXIMUM_DEPTH if options.quick else MAXIMUM_DEPTH) tracer.analyze(loc, defs, maximum_depth=maximum_depth) snapshotter.take_snapshot("analyze:check_types:post") _maybe_output_debug(options, tracer.program)
def check_types(src, filename, errorlog, options, loader, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, **kwargs): """Verify a PyTD against the Python code.""" tracer = CallTracer( errorlog=errorlog, options=options, module_name=(options.module_name or get_module_name(filename, options.pythonpath)), analyze_annotated=True, generate_unknowns=False, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) snapshotter = metrics.get_metric("memory", metrics.Snapshot) snapshotter.take_snapshot("analyze:check_types:tracer") if deep: tracer.analyze(loc, defs, maximum_depth=(2 if options.quick else None)) snapshotter.take_snapshot("analyze:check_types:post") _maybe_output_debug(options, tracer.program)
def check_types(py_src, py_filename, errorlog, options, loader, run_builtins=True, deep=True, cache_unknowns=False, init_maximum_depth=INIT_MAXIMUM_DEPTH): """Verify a PyTD against the Python code.""" tracer = CallTracer(errorlog=errorlog, options=options, module_name=get_module_name(py_filename, options), cache_unknowns=cache_unknowns, analyze_annotated=True, generate_unknowns=False, loader=loader) loc, defs = tracer.run_program(py_src, py_filename, init_maximum_depth, run_builtins) snapshotter = metrics.get_metric("memory", metrics.Snapshot) snapshotter.take_snapshot("infer:check_types:tracer") if deep: tracer.analyze(loc, defs, maximum_depth=(2 if options.quick else None)) snapshotter.take_snapshot("infer:check_types:post") _maybe_output_debug(options, tracer.program)
def _Visit(node, visitor, *args, **kwargs): name = type(visitor).__name__ recursive = name in _visiting _visiting.add(name) start = time.clock() try: return _VisitNode(node, visitor, *args, **kwargs) finally: if not recursive: _visiting.remove(name) elapsed = time.clock() - start metrics.get_metric("visit_" + name, metrics.Distribution).add(elapsed) if _visiting: metrics.get_metric("visit_nested_" + name, metrics.Distribution).add(elapsed)
def infer_types(src, errorlog, options, loader, filename=None, deep=True, init_maximum_depth=INIT_MAXIMUM_DEPTH, show_library_calls=False, maximum_depth=None, tracer_vm=None, **kwargs): """Given Python source return its types. Args: src: A string containing Python source code. errorlog: Where error messages go. Instance of errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader instance to load PYI information. filename: Filename of the program we're parsing. deep: If True, analyze all functions, even the ones not called by the main execution flow. init_maximum_depth: Depth of analysis during module loading. show_library_calls: If True, call traces are kept in the output. maximum_depth: Depth of the analysis. Default: unlimited. tracer_vm: An instance of CallTracer, in case the caller wants to instantiate and retain the vm used for type inference. **kwargs: Additional parameters to pass to vm.VirtualMachine Returns: A tuple of (ast: TypeDeclUnit, builtins: TypeDeclUnit) Raises: AssertionError: In case of a bad parameter combination. """ # If the caller has passed in a vm, use that. if tracer_vm: assert isinstance(tracer_vm, CallTracer) tracer = tracer_vm else: tracer = CallTracer(errorlog=errorlog, options=options, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader, **kwargs) loc, defs = tracer.run_program(src, filename, init_maximum_depth) log.info("===Done running definitions and module-level code===") snapshotter = metrics.get_metric("memory", metrics.Snapshot) snapshotter.take_snapshot("analyze:infer_types:tracer") if deep: if maximum_depth is None: if not options.quick: maximum_depth = MAXIMUM_DEPTH elif options.analyze_annotated: # Since there's no point in analyzing annotated functions for inference, # the presence of this option means that the user wants checking, too. maximum_depth = QUICK_CHECK_MAXIMUM_DEPTH else: maximum_depth = QUICK_INFER_MAXIMUM_DEPTH tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot("analyze:infer_types:post") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or any( a in defs for a in abstract_utils.DYNAMIC_ATTRIBUTE_MARKERS): try: ast.Lookup("__getattr__") except KeyError: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with other if statement, triggers a ValueError: Unresolved class # when attempts to load from the protocols file if options.protocols: protocols_pytd = tracer.loader.import_name("protocols") else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all() # Insert type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info("=========== PyTD to solve =============\n%s", pytd_utils.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info("Solving is turned off. Discarding call traces.") # Rename remaining "~unknown" to "?" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove "~list" etc.: ast = convert_structural.extract_local(ast) _maybe_output_debug(options, tracer.program) return ast, builtins_pytd
def test_get_metric(self): c1 = metrics.get_metric("foo", metrics.Counter) self.assertIsInstance(c1, metrics.Counter) c2 = metrics.get_metric("foo", metrics.Counter) self.assertIs(c1, c2)
def infer_types(src, errorlog, options, loader, filename=None, run_builtins=True, deep=True, cache_unknowns=False, show_library_calls=False, analyze_annotated=False, init_maximum_depth=INIT_MAXIMUM_DEPTH, maximum_depth=None): """Given Python source return its types. Args: src: A string containing Python source code. errorlog: Where error messages go. Instance of errors.ErrorLog. options: config.Options object loader: A load_pytd.Loader instance to load PYI information. filename: Filename of the program we're parsing. run_builtins: Whether to preload the native Python builtins when running the program. deep: If True, analyze all functions, even the ones not called by the main execution flow. cache_unknowns: If True, do a faster approximation of unknown types. show_library_calls: If True, call traces are kept in the output. analyze_annotated: If True, analyze methods with type annotations, too. init_maximum_depth: Depth of analysis during module loading. maximum_depth: Depth of the analysis. Default: unlimited. Returns: A TypeDeclUnit Raises: AssertionError: In case of a bad parameter combination. """ tracer = CallTracer(errorlog=errorlog, options=options, module_name=get_module_name(filename, options), cache_unknowns=cache_unknowns, analyze_annotated=analyze_annotated, generate_unknowns=options.protocols, store_all_calls=not deep, loader=loader) loc, defs = tracer.run_program(src, filename, init_maximum_depth, run_builtins) log.info("===Done running definitions and module-level code===") snapshotter = metrics.get_metric("memory", metrics.Snapshot) snapshotter.take_snapshot("infer:infer_types:tracer") if deep: tracer.exitpoint = tracer.analyze(loc, defs, maximum_depth) else: tracer.exitpoint = loc snapshotter.take_snapshot("infer:infer_types:post") ast = tracer.compute_types(defs) ast = tracer.loader.resolve_ast(ast) if tracer.has_unknown_wildcard_imports or ("HAS_DYNAMIC_ATTRIBUTES" in defs or "has_dynamic_attributes" in defs): try: ast.Lookup("__getattr__") except KeyError: ast = pytd_utils.Concat( ast, builtins.GetDefaultAst(options.python_version)) # If merged with other if statement, triggers a ValueError: Unresolved class # when attempts to load from the protocols file if options.protocols: protocols_pytd = tracer.loader.import_name("protocols") else: protocols_pytd = None builtins_pytd = tracer.loader.concat_all() # Insert type parameters, where appropriate ast = ast.Visit(visitors.CreateTypeParametersForSignatures()) if options.protocols: log.info("=========== PyTD to solve =============\n%s", pytd.Print(ast)) ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd) elif not show_library_calls: log.info("Solving is turned off. Discarding call traces.") # Rename remaining "~unknown" to "?" ast = ast.Visit(visitors.RemoveUnknownClasses()) # Remove "~list" etc.: ast = convert_structural.extract_local(ast) if options.output_cfg or options.output_typegraph: if options.output_cfg and options.output_typegraph: raise AssertionError("Can output CFG or typegraph, but not both") dot = debug.program_to_dot(tracer.program, set([]), bool(options.output_cfg)) proc = subprocess.Popen([ "/usr/bin/dot", "-T", "svg", "-o", options.output_cfg or options.output_typegraph ], stdin=subprocess.PIPE) proc.stdin.write(dot) proc.stdin.close() _maybe_output_debug(options, tracer.program) return ast, builtins_pytd