Beispiel #1
0
 private static IEnumerable <AnalysisValue> GetTestCaseClasses(IModuleAnalysis analysis)
 {
     return(analysis.GetAllMembers(SourceLocation.MinValue, GetMemberOptions.ExcludeBuiltins)
            .SelectMany(m => analysis.GetValues(m.Name, SourceLocation.MinValue))
            .Where(v => v.MemberType == PythonMemberType.Class)
            .Where(v => v.Mro.SelectMany(v2 => v2).Any(IsTestCaseClass)));
 }
        private async Task <Hover> GetSelfHoverAsync(Expression expr, IModuleAnalysis analysis, PythonAst tree, Position position, CancellationToken cancellationToken)
        {
            if (!(expr is NameExpression name) || name.Name != "self")
            {
                return(null);
            }
            var classDef = analysis.GetVariables(expr, position).FirstOrDefault(v => v.Type == VariableType.Definition);

            if (classDef == null)
            {
                return(null);
            }

            var instanceInfo = classDef.Variable.Types.OfType <IInstanceInfo>().FirstOrDefault();

            if (instanceInfo == null)
            {
                return(null);
            }

            var cd          = instanceInfo.ClassInfo.ClassDefinition;
            var classParams = new TextDocumentPositionParams {
                position     = cd.NameExpression.GetStart(tree),
                textDocument = new TextDocumentIdentifier {
                    uri = classDef.Location.DocumentUri
                }
            };

            return(await Hover(classParams, cancellationToken));
        }
Beispiel #3
0
 public Task HandleCompletionAsync(Uri documentUri, IModuleAnalysis analysis, PythonAst tree, SourceLocation location, CompletionList completions, CancellationToken token)
 {
     Assert.IsNotNull(tree);
     Assert.IsNotNull(analysis);
     for (int i = 0; i < completions.items.Length; ++i)
     {
         completions.items[i].insertText = "*" + completions.items[i].insertText;
     }
     return(Task.CompletedTask);
 }
Beispiel #4
0
        public CompletionAnalysis(
            IModuleAnalysis analysis,
            PythonAst tree,
            SourceLocation position,
            GetMemberOptions opts,
            ServerSettings.PythonCompletionOptions completionSettings,
            DocumentationBuilder textBuilder,
            ILogger log,
            Func <TextReader> openDocument
            )
        {
            Analysis      = analysis ?? throw new ArgumentNullException(nameof(analysis));
            Tree          = tree ?? throw new ArgumentNullException(nameof(tree));
            Position      = position;
            Index         = Tree.LocationToIndex(Position);
            Options       = opts;
            _pathResolver = analysis.ProjectState.CurrentPathResolver;
            _textBuilder  = textBuilder;
            _log          = log;
            _openDocument = openDocument;
            _addBrackets  = completionSettings.addBrackets;

            var finder = new ExpressionFinder(Tree, new GetExpressionOptions {
                Names              = true,
                Members            = true,
                NamedArgumentNames = true,
                ImportNames        = true,
                ImportAsNames      = true,
                Literals           = true,
                Errors             = true
            });

            finder.Get(Index, Index, out var node, out _statement, out _scope);

            var index = Index;
            var col   = Position.Column;

            while (CanBackUp(Tree, node, _statement, _scope, col))
            {
                col   -= 1;
                index -= 1;
                finder.Get(index, index, out node, out _statement, out _scope);
            }

            Node = node ?? (_statement as ExpressionStatement)?.Expression;
        }
        public static IEnumerable <BuiltinTypeId> GetTypeIdsByIndex(this IModuleAnalysis analysis, string exprText, int index)
        {
            return(analysis.GetValuesByIndex(exprText, index).Select(m => {
                if (m.PythonType.TypeId != BuiltinTypeId.Unknown)
                {
                    return m.PythonType.TypeId;
                }

                var state = analysis.ProjectState;
                if (m == state._noneInst)
                {
                    return BuiltinTypeId.NoneType;
                }

                var bci = m as BuiltinClassInfo;
                if (bci == null)
                {
                    var bii = m as BuiltinInstanceInfo;
                    if (bii != null)
                    {
                        bci = bii.ClassInfo;
                    }
                }
                if (bci != null)
                {
                    int count = (int)BuiltinTypeIdExtensions.LastTypeId;
                    for (int i = 1; i <= count; ++i)
                    {
                        var bti = (BuiltinTypeId)i;
                        if (!bti.IsVirtualId() && analysis.ProjectState.ClassInfos[bti] == bci)
                        {
                            return bti;
                        }
                    }
                }

                return BuiltinTypeId.Unknown;
            }));
        }
Beispiel #6
0
        /// <summary>
        /// Get Test Case Members for a class.  If the class has 'test*' tests
        /// return those.  If there aren't any 'test*' tests return (if one at
        /// all) the runTest overridden method
        /// </summary>
        private static IEnumerable <KeyValuePair <string, ILocationInfo> > GetTestCaseMembers(
            PythonAst ast,
            string sourceFile,
            Uri documentUri,
            IModuleAnalysis analysis,
            AnalysisValue classValue
            )
        {
            IEnumerable <KeyValuePair <string, ILocationInfo> > tests = null, runTest = null;

            if (ast != null && !string.IsNullOrEmpty(sourceFile))
            {
                var walker = new TestMethodWalker(ast, sourceFile, documentUri, classValue.Locations);
                ast.Walk(walker);
                tests   = walker.Methods.Where(v => v.Key.StartsWithOrdinal("test"));
                runTest = walker.Methods.Where(v => v.Key.Equals("runTest"));
            }

            var methodFunctions = classValue.GetAllMembers(analysis.InterpreterContext)
                                  .Where(v => v.Value.Any(m => m.MemberType == PythonMemberType.Function || m.MemberType == PythonMemberType.Method))
                                  .Select(v => new KeyValuePair <string, ILocationInfo>(v.Key, v.Value.SelectMany(av => av.Locations).FirstOrDefault(l => l != null)));

            var analysisTests = methodFunctions.Where(v => v.Key.StartsWithOrdinal("test"));
            var analysisRunTest = methodFunctions.Where(v => v.Key.Equals("runTest"));

            tests   = tests?.Concat(analysisTests) ?? analysisTests;
            runTest = runTest?.Concat(analysisRunTest) ?? analysisRunTest;

            if (tests.Any())
            {
                return(tests);
            }
            else
            {
                return(runTest);
            }
        }
 public static IEnumerable <IMemberResult> GetMemberByIndex(this IModuleAnalysis entry, string variable, string memberName, int index)
 {
     return(entry.GetMembersByIndex(variable, index).Where(m => m.Name == memberName));
 }
 public static IEnumerable <string> GetCompletionDocumentationByIndex(this IModuleAnalysis entry, string variable, string memberName, int index)
 {
     return(entry.GetMemberByIndex(variable, memberName, index).Select(m => m.Documentation));
 }
 public static IEnumerable <string> GetShortDescriptionsByIndex(this IModuleAnalysis entry, string variable, int index)
 {
     return(entry.GetValuesByIndex(variable, index).Select(m => m.ShortDescription));
 }
 public static IEnumerable <IPythonType> GetTypesByIndex(this IModuleAnalysis analysis, string exprText, int index)
 {
     return(analysis.GetValuesByIndex(exprText, index).Select(m => m.PythonType));
 }
        private IEnumerable <AnalysisValue> GetImportHover(IPythonProjectEntry entry, IModuleAnalysis analysis, PythonAst tree, Position position, out Hover hover)
        {
            hover = null;

            var index = tree.LocationToIndex(position);
            var w     = new ImportedModuleNameWalker(entry, index, tree);

            tree.Walk(w);

            if (w.ImportedType != null)
            {
                return(analysis.GetValues(w.ImportedType.Name, position));
            }

            var sb   = new StringBuilder();
            var span = SourceSpan.Invalid;

            foreach (var n in w.ImportedModules)
            {
                if (Analyzer.Modules.TryGetImportedModule(n.Name, out var modRef) && modRef.AnalysisModule != null)
                {
                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                        sb.AppendLine();
                    }
                    sb.Append(_displayTextBuilder.GetModuleDocumentation(modRef));
                    span = span.IsValid ? span.Union(n.SourceSpan) : n.SourceSpan;
                }
            }
            if (sb.Length > 0)
            {
                hover = new Hover {
                    contents = sb.ToString(),
                    range    = span
                };
            }
            return(Enumerable.Empty <AnalysisValue>());
        }
Beispiel #12
0
 public static ModuleAnalysisAssertions Should(this IModuleAnalysis moduleAnalysis)
 => new ModuleAnalysisAssertions(moduleAnalysis);
        private static IEnumerable <IMemberResult> GetModuleVariables(ProjectEntry entry, GetMemberOptions opts, string prefix, IModuleAnalysis analysis)
        {
            var all = analysis.GetAllMembers(SourceLocation.None, opts);

            return(all
                   .Where(m => {
                if (m.Values.Any(v => v.DeclaringModule == entry || v.Locations.Any(l => l.DocumentUri == entry.DocumentUri)))
                {
                    if (string.IsNullOrEmpty(prefix) || m.Name.StartsWithOrdinal(prefix, ignoreCase: true))
                    {
                        return true;
                    }
                }
                return false;
            })
                   .Concat(GetChildScopesVariables(analysis, analysis.Scope, opts, 0)));
        }
 private static IEnumerable <IMemberResult> GetScopeVariables(IModuleAnalysis analysis, IScope scope, GetMemberOptions opts, int currentDepth)
 => analysis.GetAllAvailableMembersFromScope(scope, opts).Concat(GetChildScopesVariables(analysis, scope, opts, currentDepth + 1));
 private static IEnumerable <IMemberResult> GetChildScopesVariables(IModuleAnalysis analysis, IScope scope, GetMemberOptions opts, int currentDepth)
 => currentDepth < _symbolHierarchyDepthLimit
         ? scope.Children.SelectMany(c => GetScopeVariables(analysis, c, opts, currentDepth))
         : Enumerable.Empty <IMemberResult>();
        private static IEnumerable <IMemberResult> GetModuleVariables(ProjectEntry entry, GetMemberOptions opts, string prefix, IModuleAnalysis analysis)
        {
            var breadthFirst = analysis.Scope.TraverseBreadthFirst(s => s.Children);
            var all          = breadthFirst.SelectMany(c => analysis.GetAllAvailableMembersFromScope(c, opts));
            var result       = all
                               .Where(m => {
                if (m.Values.Any(v => v.DeclaringModule == entry ||
                                 v.Locations
                                 .MaybeEnumerate()
                                 .ExcludeDefault()
                                 .Any(l => l.DocumentUri == entry.DocumentUri)))
                {
                    return(string.IsNullOrEmpty(prefix) || m.Name.StartsWithOrdinal(prefix, ignoreCase: true));
                }
                return(false);
            })
                               .Take(_symbolHierarchyMaxSymbols);

            return(result);
        }
 public static IEnumerable <string> GetMemberNamesByIndex(this IModuleAnalysis analysis, string exprText, int index, GetMemberOptions options = GetMemberOptions.IntersectMultipleResults)
 {
     return(analysis.GetMembersByIndex(exprText, index, options).Select(m => m.Name));
 }