Exemplo n.º 1
0
def _create(inference_state, access_handle, parent_context, *args):
    compiled_object = create_cached_compiled_object(
        inference_state,
        access_handle,
        # TODO It looks like we have to use the compiled object as a parent context.
        #      Why is that?
        parent_context=None if parent_context is None else
        parent_context.compiled_object.as_context()  # noqa
    )

    # TODO accessing this is bad, but it probably doesn't matter that much,
    # because we're working with interpreteters only here.
    python_object = access_handle.access._obj
    result = _find_syntax_node_name(inference_state, python_object)
    if result is None:
        # TODO Care about generics from stuff like `[1]` and don't return like this.
        if type(python_object) in (dict, list, tuple):
            return ValueSet({compiled_object})

        tree_values = to_stub(compiled_object)
        if not tree_values:
            return ValueSet({compiled_object})
    else:
        module_node, tree_node, file_io, code_lines = result

        if parent_context is None:
            # TODO this __name__ is probably wrong.
            name = compiled_object.get_root_context().py__name__()
            string_names = tuple(name.split('.'))
            module_context = ModuleValue(
                inference_state,
                module_node,
                file_io=file_io,
                string_names=string_names,
                code_lines=code_lines,
                is_package=compiled_object.is_package(),
            ).as_context()
            if name is not None:
                inference_state.module_cache.add(string_names,
                                                 ValueSet([module_context]))
        else:
            if parent_context.tree_node.get_root_node() != module_node:
                # This happens e.g. when __module__ is wrong, or when using
                # TypeVar('foo'), where Jedi uses 'foo' as the name and
                # Python's TypeVar('foo').__module__ will be typing.
                return ValueSet({compiled_object})
            module_context = parent_context.get_root_context()

        tree_values = ValueSet({module_context.create_value(tree_node)})
        if tree_node.type == 'classdef':
            if not access_handle.is_class():
                # Is an instance, not a class.
                tree_values = tree_values.execute_with_values()

    return ValueSet(
        MixedObject(compiled_object, tree_value=tree_value)
        for tree_value in tree_values)
Exemplo n.º 2
0
 def _complete_code_lines(self, code_lines):
     module_node = self._inference_state.grammar.parse(''.join(code_lines))
     module_value = ModuleValue(
         self._inference_state,
         module_node,
         code_lines=code_lines,
     )
     module_value.parent_context = self._module_context
     return Completion(self._inference_state,
                       module_value.as_context(),
                       code_lines=code_lines,
                       position=module_node.end_pos,
                       signatures_callback=lambda *args, **kwargs: [],
                       fuzzy=self._fuzzy).complete()
Exemplo n.º 3
0
def _load_python_module(inference_state,
                        file_io,
                        sys_path=None,
                        import_names=None,
                        is_package=False):
    try:
        return inference_state.module_cache.get_from_path(file_io.path)
    except KeyError:
        pass

    module_node = inference_state.parse(file_io=file_io,
                                        cache=True,
                                        diff_cache=settings.fast_parser,
                                        cache_path=settings.cache_directory)

    from jedi.inference.value import ModuleValue
    return ModuleValue(
        inference_state,
        module_node,
        file_io=file_io,
        string_names=import_names,
        code_lines=get_cached_code_lines(inference_state.grammar,
                                         file_io.path),
        is_package=is_package,
    )
def collections_namedtuple(value, arguments, callback):
    """
    Implementation of the namedtuple function.

    This has to be done by processing the namedtuple class template and
    inferring the result.

    """
    inference_state = value.inference_state

    # Process arguments
    name = u'jedi_unknown_namedtuple'
    for c in _follow_param(inference_state, arguments, 0):
        x = get_str_or_none(c)
        if x is not None:
            name = force_unicode(x)
            break

    # TODO here we only use one of the types, we should use all.
    param_values = _follow_param(inference_state, arguments, 1)
    if not param_values:
        return NO_VALUES
    _fields = list(param_values)[0]
    string = get_str_or_none(_fields)
    if string is not None:
        fields = force_unicode(string).replace(',', ' ').split()
    elif isinstance(_fields, iterable.Sequence):
        fields = [
            force_unicode(get_str_or_none(v))
            for lazy_value in _fields.py__iter__() for v in lazy_value.infer()
        ]
        fields = [f for f in fields if f is not None]
    else:
        return NO_VALUES

    # Build source code
    code = _NAMEDTUPLE_CLASS_TEMPLATE.format(
        typename=name,
        field_names=tuple(fields),
        num_fields=len(fields),
        arg_list=repr(tuple(fields)).replace("u'", "").replace("'", "")[1:-1],
        repr_fmt='',
        field_defs='\n'.join(
            _NAMEDTUPLE_FIELD_TEMPLATE.format(index=index, name=name)
            for index, name in enumerate(fields)))

    # Parse source code
    module = inference_state.grammar.parse(code)
    generated_class = next(module.iter_classdefs())
    parent_context = ModuleValue(
        inference_state,
        module,
        file_io=None,
        string_names=None,
        code_lines=parso.split_lines(code, keepends=True),
    ).as_context()

    return ValueSet(
        [ClassValue(inference_state, parent_context, generated_class)])
Exemplo n.º 5
0
def _create(inference_state, compiled_value, module_context):
    # TODO accessing this is bad, but it probably doesn't matter that much,
    # because we're working with interpreteters only here.
    python_object = compiled_value.access_handle.access._obj
    result = _find_syntax_node_name(inference_state, python_object)
    if result is None:
        # TODO Care about generics from stuff like `[1]` and don't return like this.
        if type(python_object) in (dict, list, tuple):
            return ValueSet({compiled_value})

        tree_values = to_stub(compiled_value)
        if not tree_values:
            return ValueSet({compiled_value})
    else:
        module_node, tree_node, file_io, code_lines = result

        if module_context is None or module_context.tree_node != module_node:
            root_compiled_value = compiled_value.get_root_context().get_value()
            # TODO this __name__ might be wrong.
            name = root_compiled_value.py__name__()
            string_names = tuple(name.split('.'))
            module_value = ModuleValue(
                inference_state,
                module_node,
                file_io=file_io,
                string_names=string_names,
                code_lines=code_lines,
                is_package=root_compiled_value.is_package(),
            )
            if name is not None:
                inference_state.module_cache.add(string_names,
                                                 ValueSet([module_value]))
            module_context = module_value.as_context()

        tree_values = ValueSet({module_context.create_value(tree_node)})
        if tree_node.type == 'classdef':
            if not compiled_value.is_class():
                # Is an instance, not a class.
                tree_values = tree_values.execute_with_values()

    return ValueSet(
        MixedObject(compiled_value, tree_value=tree_value)
        for tree_value in tree_values)
Exemplo n.º 6
0
 def _get_module_context(self):
     tree_module_value = ModuleValue(
         self._inference_state, self._module_node,
         file_io=KnownContentFileIO(self.path, self._code),
         string_names=('__main__',),
         code_lines=self._code_lines,
     )
     return interpreter.MixedModuleContext(
         tree_module_value,
         self.namespaces,
     )
Exemplo n.º 7
0
    def _get_module(self):
        names = None
        is_package = False
        if self.path is not None:
            import_names, is_p = transform_path_to_dotted(
                self._inference_state.get_sys_path(add_parent_paths=False),
                self.path
            )
            if import_names is not None:
                names = import_names
                is_package = is_p

        if self.path is None:
            file_io = None
        else:
            file_io = KnownContentFileIO(self.path, self._code)
        if self.path is not None and self.path.suffix == '.pyi':
            # We are in a stub file. Try to load the stub properly.
            stub_module = load_proper_stub_module(
                self._inference_state,
                self._inference_state.latest_grammar,
                file_io,
                names,
                self._module_node
            )
            if stub_module is not None:
                return stub_module

        if names is None:
            names = ('__main__',)

        module = ModuleValue(
            self._inference_state, self._module_node,
            file_io=file_io,
            string_names=names,
            code_lines=self._code_lines,
            is_package=is_package,
        )
        if names[0] not in ('builtins', 'typing'):
            # These modules are essential for Jedi, so don't overwrite them.
            self._inference_state.module_cache.add(names, ValueSet([module]))
        return module
Exemplo n.º 8
0
def _get_paths_from_buildout_script(inference_state, buildout_script_path):
    file_io = FileIO(str(buildout_script_path))
    try:
        module_node = inference_state.parse(
            file_io=file_io, cache=True, cache_path=settings.cache_directory)
    except IOError:
        debug.warning('Error trying to read buildout_script: %s',
                      buildout_script_path)
        return

    from jedi.inference.value import ModuleValue
    module_context = ModuleValue(
        inference_state,
        module_node,
        file_io=file_io,
        string_names=None,
        code_lines=get_cached_code_lines(inference_state.grammar,
                                         str(buildout_script_path)),
    ).as_context()
    yield from check_sys_path_modifications(module_context)