Пример #1
0
        private static bool ParameterIsResult(ParameterDeclaration parameter, DeclarationFinder finder)
        {
            var enclosingMember = parameter.ParentDeclaration;

            if (!(enclosingMember is ModuleBodyElementDeclaration member))
            {
                return(false);
            }

            return(!member.IsInterfaceImplementation &&
                   member.DeclarationType != DeclarationType.LibraryFunction &&
                   member.DeclarationType != DeclarationType.LibraryProcedure &&
                   !finder.FindEventHandlers().Contains(member));
        }
Пример #2
0
        private static void RemoveByRefIdentifierFromHandlers(
            EventDeclaration eventDeclaration,
            int parameterIndex,
            DeclarationFinder finder,
            IRewriteSession rewriteSession)
        {
            var handlers = finder.FindEventHandlers(eventDeclaration)
                           .Select(implementation => implementation.Parameters[parameterIndex]);

            foreach (var parameter in handlers)
            {
                RemoveByRefIdentifier(rewriteSession, parameter);
            }
        }
Пример #3
0
        private static void RemoveByRefIdentifierFromImplementations(
            ModuleBodyElementDeclaration interfaceMember,
            int parameterIndex,
            DeclarationFinder finder,
            IRewriteSession rewriteSession)
        {
            var implementationParameters = finder.FindInterfaceImplementationMembers(interfaceMember)
                                           .Select(implementation => implementation.Parameters[parameterIndex]);

            foreach (var parameter in implementationParameters)
            {
                RemoveByRefIdentifier(rewriteSession, parameter);
            }
        }
Пример #4
0
        private async Task <ImmutableArray <SymbolResult> > GetMatchingNamespacesAsync(
            Project project,
            SemanticModel semanticModel,
            SyntaxNode simpleName,
            CancellationToken cancellationToken)
        {
            var syntaxFacts = project.LanguageServices.GetService <ISyntaxFactsService>();

            if (syntaxFacts.IsAttributeName(simpleName))
            {
                return(ImmutableArray <SymbolResult> .Empty);
            }

            syntaxFacts.GetNameAndArityOfSimpleName(simpleName, out var name, out var arityUnused);
            if (cancellationToken.IsCancellationRequested)
            {
                return(ImmutableArray <SymbolResult> .Empty);
            }

            var symbolAndProjectIds = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
                project, SearchQuery.Create(name, IgnoreCase),
                SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);

            var symbols = symbolAndProjectIds.SelectAsArray(t => t.Symbol);

            // There might be multiple namespaces that this name will resolve successfully in.
            // Some of them may be 'better' results than others.  For example, say you have
            //  Y.Z   and Y exists in both X1 and X2
            // We'll want to order them such that we prefer the namespace that will correctly
            // bind Z off of Y as well.

            string rightName       = null;
            var    isAttributeName = false;

            if (syntaxFacts.IsLeftSideOfDot(simpleName))
            {
                var rightSide = syntaxFacts.GetRightSideOfDot(simpleName.Parent);
                syntaxFacts.GetNameAndArityOfSimpleName(rightSide, out rightName, out arityUnused);
                isAttributeName = syntaxFacts.IsAttributeName(rightSide);
            }

            var namespaces = symbols
                             .OfType <INamespaceSymbol>()
                             .Where(n => !n.IsGlobalNamespace && HasAccessibleTypes(n, semanticModel, cancellationToken))
                             .Select(n => new SymbolResult(n,
                                                           BindsWithoutErrors(n, rightName, isAttributeName) ? NamespaceWithNoErrorsWeight : NamespaceWithErrorsWeight));

            return(namespaces.ToImmutableArray());
        }
        public Task <IList <SerializableSymbolAndProjectId> > FindSolutionSourceDeclarationsWithNormalQueryAsync(
            string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async token =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(token).ConfigureAwait(false);
                    var result = await DeclarationFinder.FindSourceDeclarationsWithNormalQueryInCurrentProcessAsync(
                        solution, name, ignoreCase, criteria, token).ConfigureAwait(false);

                    return (IList <SerializableSymbolAndProjectId>)result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate);
                }
            }, cancellationToken));
        }
Пример #6
0
        public async Task <ImmutableArray <SerializableSymbolAndProjectId> > FindProjectSourceDeclarationsWithPatternAsync(
            ProjectId projectId, string pattern, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            using (UserOperationBooster.Boost())
            {
                var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false);

                var project = solution.GetProject(projectId);

                var result = await DeclarationFinder.FindSourceDeclarationsWithPatternInCurrentProcessAsync(
                    project, pattern, criteria, cancellationToken).ConfigureAwait(false);

                return(result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate));
            }
        }
        protected override bool IsResultDeclaration(Declaration declaration, DeclarationFinder finder)
        {
            if (!(declaration is ParameterDeclaration parameter) ||
                !parameter.IsImplicitByRef ||
                parameter.IsParamArray
                //Exclude parameters of Declare statements
                || !(parameter.ParentDeclaration is ModuleBodyElementDeclaration enclosingMethod))
            {
                return(false);
            }

            return(!IsPropertyMutatorRHSParameter(enclosingMethod, parameter) &&
                   !enclosingMethod.IsInterfaceImplementation &&
                   !finder.FindEventHandlers().Contains(enclosingMethod));
        }
        public async Task <IList <SerializableSymbolAndProjectId> > FindProjectSourceDeclarationsWithNormalQueryAsync(
            ProjectId projectId, string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            using (UserOperationBooster.Boost())
            {
                var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false);

                var project = solution.GetProject(projectId);

                var result = await DeclarationFinder.FindSourceDeclarationsWithNormalQueryInCurrentProcessAsync(
                    project, name, ignoreCase, criteria, cancellationToken).ConfigureAwait(false);

                return(result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate));
            }
        }
        public async Task <SerializableSymbolAndProjectId[]> FindAllDeclarationsWithNormalQueryAsync(
            ProjectId projectId, string name, SearchKind searchKind, SymbolFilter criteria)
        {
            var solution = await GetSolutionAsync().ConfigureAwait(false);

            var project = solution.GetProject(projectId);

            using (var query = SearchQuery.Create(name, searchKind))
            {
                var result = await DeclarationFinder.FindAllDeclarationsWithNormalQueryInCurrentProcessAsync(
                    project, query, criteria, this.CancellationToken).ConfigureAwait(false);

                return(result.Select(SerializableSymbolAndProjectId.Dehydrate).ToArray());
            }
        }
Пример #10
0
        private async Task <ImmutableArray <SymbolResult> > GetMatchingTypesAsync(
            Document document, SemanticModel semanticModel, SyntaxNode node, bool hideAdvancedMembers, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var project     = document.Project;
            var syntaxFacts = project.LanguageServices.GetRequiredService <ISyntaxFactsService>();

            syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out var arity);
            var looksGeneric = syntaxFacts.LooksGeneric(node);

            var symbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
                project, SearchQuery.Create(name, IgnoreCase),
                SymbolFilter.Type, cancellationToken).ConfigureAwait(false);

            // also lookup type symbols with the "Attribute" suffix.
            var inAttributeContext = syntaxFacts.IsAttributeName(node);

            if (inAttributeContext)
            {
                var attributeSymbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
                    project, SearchQuery.Create(name + "Attribute", IgnoreCase),
                    SymbolFilter.Type, cancellationToken).ConfigureAwait(false);

                symbols = symbols.Concat(attributeSymbols);
            }

            var editorBrowserInfo = new EditorBrowsableInfo(semanticModel.Compilation);

            var validSymbols = symbols
                               .OfType <INamedTypeSymbol>()
                               .Where(s => IsValidNamedTypeSearchResult(semanticModel, arity, inAttributeContext, looksGeneric, s) &&
                                      s.IsEditorBrowsable(hideAdvancedMembers, semanticModel.Compilation, editorBrowserInfo))
                               .ToImmutableArray();

            // Check what the current node binds to.  If it binds to any symbols, but with
            // the wrong arity, then we don't want to suggest fully qualifying to the same
            // type that we're already binding to.  That won't address the WrongArity problem.
            var currentSymbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken);

            if (currentSymbolInfo.CandidateReason == CandidateReason.WrongArity)
            {
                validSymbols = validSymbols.WhereAsArray(
                    s => !currentSymbolInfo.CandidateSymbols.Contains(s));
            }

            return(validSymbols.SelectAsArray(s => new SymbolResult(s, weight: TypeWeight)));
        }
Пример #11
0
        private void ResolveInternal(CancellationToken token)
        {
            var components = _state.Projects
                             .Where(project => project.Protection == vbext_ProjectProtection.vbext_pp_none)
                             .SelectMany(p => p.VBComponents.Cast <VBComponent>()).ToList();

            if (!_state.HasAllParseTrees(components))
            {
                return;
            }
            _projectDeclarations.Clear();
            foreach (var kvp in _state.ParseTrees)
            {
                var qualifiedName = kvp.Key;
                if (true /*_state.IsModified(qualifiedName)*/)
                {
                    Debug.WriteLine("Module '{0}' {1}", qualifiedName.ComponentName, _state.IsNewOrModified(qualifiedName) ? "was modified" : "was NOT modified");
                    // modified module; walk parse tree and re-acquire all declarations
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    ResolveDeclarations(qualifiedName.Component, kvp.Value);
                }
                else
                {
                    Debug.WriteLine(string.Format("Module '{0}' was not modified since last parse. Clearing identifier references...", kvp.Key.ComponentName));
                    // clear identifier references for non-modified modules
                    var declarations = _state.AllUserDeclarations.Where(item => item.QualifiedName.QualifiedModuleName.Equals(qualifiedName));
                    foreach (var declaration in declarations)
                    {
                        declaration.ClearReferences();
                    }
                }
            }

            // walk all parse trees (modified or not) for identifier references
            var finder = new DeclarationFinder(_state.AllDeclarations, _state.AllComments, _state.AllAnnotations);

            foreach (var kvp in _state.ParseTrees)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                ResolveReferences(finder, kvp.Key.Component, kvp.Value);
            }
        }
Пример #12
0
        public Task <ImmutableArray <SerializableSymbolAndProjectId> > FindSolutionSourceDeclarationsWithPatternAsync(
            PinnedSolutionInfo solutionInfo, string pattern, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async() =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);

                    var result = await DeclarationFinder.FindSourceDeclarationsWithPatternInCurrentProcessAsync(
                        solution, pattern, criteria, cancellationToken).ConfigureAwait(false);

                    return Convert(result, solution, cancellationToken);
                }
            }, cancellationToken));
        }
Пример #13
0
        protected override bool IsResultDeclaration(Declaration declaration, DeclarationFinder finder)
        {
            if (!(declaration is ModuleBodyElementDeclaration member) ||
                member.IsInterfaceImplementation ||
                member.IsInterfaceMember ||
                finder.FindEventHandlers().Contains(member) ||
                member.Parameters.Count(param => param.IsByRef && !param.IsParamArray) != 1)
            {
                return(false);
            }

            var parameter           = member.Parameters.First(param => param.IsByRef && !param.IsParamArray);
            var parameterReferences = parameter.References.ToList();

            return(parameterReferences.Any(reference => IsAssignment(reference, finder)));
        }
Пример #14
0
            protected override async Task <ImmutableArray <ISymbol> > FindDeclarationsAsync(
                SymbolFilter filter,
                SearchQuery searchQuery
                )
            {
                var declarations = await DeclarationFinder
                                   .FindAllDeclarationsWithNormalQueryAsync(
                    _project,
                    searchQuery,
                    filter,
                    CancellationToken
                    )
                                   .ConfigureAwait(false);

                return(declarations);
            }
Пример #15
0
        public Task <IList <SerializableSymbolAndProjectId> > FindSolutionSourceDeclarationsWithPatternAsync(
            string pattern, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async() =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false);

                    var result = await DeclarationFinder.FindSourceDeclarationsWithPatternInCurrentProcessAsync(
                        solution, pattern, criteria, cancellationToken).ConfigureAwait(false);

                    return (IList <SerializableSymbolAndProjectId>)result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate);
                }
            }, cancellationToken));
        }
Пример #16
0
 public IdentifierReferenceInspectionResult(
     IInspection inspection,
     string description,
     DeclarationFinder finder,
     IdentifierReference reference,
     ICollection <string> disabledQuickFixes = null)
     : base(inspection,
            description,
            reference.QualifiedModuleName,
            reference.Context,
            reference.Declaration,
            new QualifiedSelection(reference.QualifiedModuleName, reference.Context.GetSelection()),
            GetQualifiedMemberName(finder, reference),
            disabledQuickFixes)
 {
     Reference = reference;
 }
 public SimpleNameDefaultBinding(
     DeclarationFinder declarationFinder,
     Declaration project,
     Declaration module,
     Declaration parent,
     ParserRuleContext context,
     string name,
     StatementResolutionContext statementContext)
 {
     _declarationFinder = declarationFinder;
     _project           = project;
     _module            = module;
     _parent            = parent;
     _context           = context;
     _name = name;
     _propertySearchType = StatementContext.GetSearchDeclarationType(statementContext);
 }
Пример #18
0
        public static bool IsIgnoringInspectionResult(this IInspectionResult result, DeclarationFinder declarationFinder)
        {
            switch (result)
            {
            case DeclarationInspectionResult declarationResult:
                return(declarationResult.Target.IsIgnoringInspectionResultFor(declarationResult.Inspection.AnnotationName));

            case IdentifierReferenceInspectionResult identifierReferenceResult:
                return(identifierReferenceResult.Reference.IsIgnoringInspectionResultFor(identifierReferenceResult.Inspection.AnnotationName));

            case QualifiedContextInspectionResult qualifiedContextResult:
                return(qualifiedContextResult.QualifiedName.IsIgnoringInspectionResultFor(qualifiedContextResult.Context.Start.Line, declarationFinder, qualifiedContextResult.Inspection.AnnotationName));

            default:
                return(false);
            }
        }
Пример #19
0
 public MemberAccessProcedurePointerBinding(
     DeclarationFinder declarationFinder,
     Declaration project,
     Declaration module,
     Declaration parent,
     VBAParser.MemberAccessExprContext expression,
     ParserRuleContext unrestrictedNameContext,
     IExpressionBinding lExpressionBinding)
 {
     _declarationFinder       = declarationFinder;
     _project                 = project;
     _module                  = module;
     _parent                  = parent;
     _expression              = expression;
     _lExpressionBinding      = lExpressionBinding;
     _unrestrictedNameContext = unrestrictedNameContext;
 }
Пример #20
0
 public IndexDefaultBinding(
     DeclarationFinder declarationFinder,
     Declaration project,
     Declaration module,
     Declaration parent,
     ParserRuleContext expression,
     IBoundExpression lExpression,
     ArgumentList argumentList)
 {
     _declarationFinder = declarationFinder;
     _project           = project;
     _module            = module;
     _parent            = parent;
     _expression        = expression;
     _lExpression       = lExpression;
     _argumentList      = argumentList;
 }
Пример #21
0
        private static ClassModuleDeclaration GetHostWorkbookDeclaration(DeclarationFinder finder)
        {
            var documentModuleQMNs        = finder.AllModules.Where(m => m.ComponentType == ComponentType.Document);
            ClassModuleDeclaration result = null;

            foreach (var qmn in documentModuleQMNs)
            {
                var declaration = finder.ModuleDeclaration(qmn) as ClassModuleDeclaration;
                if (declaration.Supertypes.Any(t => t.IdentifierName.Equals("Workbook") && t.ProjectName == "Excel" && !t.IsUserDefined))
                {
                    result = declaration;
                    break;
                }
            }

            return(result ?? throw new System.InvalidOperationException("Failed to find the host Workbook declaration."));
        }
Пример #22
0
        protected override IEnumerable <Declaration> ObjectionableDeclarations(DeclarationFinder finder)
        {
            if (!finder.TryFindProjectDeclaration("Excel", out var excel))
            {
                return(Enumerable.Empty <Declaration>());
            }

            var relevantClasses = InterestingClasses
                                  .Select(className => finder.FindClassModule(className, excel, true))
                                  .OfType <ModuleDeclaration>();

            var relevantProperties = relevantClasses
                                     .SelectMany(classDeclaration => classDeclaration.Members)
                                     .OfType <PropertyDeclaration>()
                                     .Where(member => InterestingMembers.Contains(member.IdentifierName));

            return(relevantProperties);
        }
        private void UpdateAliasFunctionModulesFromReferencedProjects(DeclarationFinder finder)
        {
            var vba = finder.FindProject("VBA");

            if (vba == null)
            {
                // If the VBA project is null, we haven't loaded any COM references;
                // we're in a unit test and the mock project didn't setup any references.
                return;
            }

            _conversionModule  = finder.FindStdModule("Conversion", vba, true);
            _fileSystemModule  = finder.FindStdModule("FileSystem", vba, true);
            _interactionModule = finder.FindStdModule("Interaction", vba, true);
            _stringsModule     = finder.FindStdModule("Strings", vba, true);
            _dateTimeModule    = finder.FindStdModule("DateTime", vba, true);
            _hiddenModule      = finder.FindStdModule("_HiddenModule", vba, true);
        }
        protected override bool IsResultDeclaration(Declaration declaration, DeclarationFinder finder, bool globalInfo)
        {
            if (!VisibleAsUdf.Contains(declaration.Accessibility))
            {
                return(false);
            }

            var cellIdMatch = ValidCellIdRegex.Match(declaration.IdentifierName);

            if (!cellIdMatch.Success)
            {
                return(false);
            }

            var row = Convert.ToUInt32(cellIdMatch.Groups["Row"].Value);

            return(row > 0 && row <= MaximumExcelRows);
        }
Пример #25
0
 public SimpleNameDefaultBinding(
     DeclarationFinder declarationFinder,
     Declaration project,
     Declaration module,
     Declaration parent,
     ParserRuleContext context,
     string name,
     StatementResolutionContext statementContext)
 {
     _declarationFinder = declarationFinder;
     _project           = project;
     _module            = module;
     _parent            = parent;
     _context           = context;
     // hack; SimpleNameContext.Identifier() excludes the square brackets
     _name = context.Start.Text == "[" && context.Stop.Text == "]" ? "[" + name + "]" : name;
     _propertySearchType = StatementContext.GetSearchDeclarationType(statementContext);
 }
Пример #26
0
 public IndexDefaultBinding(
     DeclarationFinder declarationFinder,
     Declaration project,
     Declaration module,
     Declaration parent,
     ParserRuleContext expression,
     IExpressionBinding lExpressionBinding,
     ArgumentList argumentList)
     : this(
         declarationFinder,
         project,
         module,
         parent,
         expression,
         (IBoundExpression)null,
         argumentList)
 {
     _lExpressionBinding = lExpressionBinding;
 }
Пример #27
0
 protected override void AddModuleToModuleReferences(DeclarationFinder finder, CancellationToken token)
 {
     try
     {
         foreach (var module in finder.AllModules)
         {
             AddModuleToModuleReferences(finder, module);
         }
     }
     catch (OperationCanceledException)
     {
         throw;
     }
     catch (Exception)
     {
         _parserStateManager.SetStatusAndFireStateChanged(this, ParserState.ResolverError, token);
         throw;
     }
 }
        protected override IEnumerable <Declaration> ObjectionableDeclarations(DeclarationFinder finder)
        {
            var excel = finder.Projects.SingleOrDefault(item => !item.IsUserDefined && item.IdentifierName == "Excel");

            if (excel == null)
            {
                return(Enumerable.Empty <Declaration>());
            }

            var globalModules = GlobalObjectClassNames
                                .Select(className => finder.FindClassModule(className, excel, true))
                                .OfType <ModuleDeclaration>();

            return(globalModules
                   .SelectMany(moduleClass => moduleClass.Members)
                   .Where(declaration => TargetMemberNames.Contains(declaration.IdentifierName) &&
                          declaration.DeclarationType.HasFlag(DeclarationType.Member) &&
                          declaration.AsTypeName == "Range"));
        }
Пример #29
0
        public Task <IList <SerializableSymbolAndProjectId> > FindAllDeclarationsWithNormalQueryAsync(
            ProjectId projectId, string name, SearchKind searchKind, SymbolFilter criteria, CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async() =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false);
                    var project = solution.GetProject(projectId);

                    using var query = SearchQuery.Create(name, searchKind);

                    var result = await DeclarationFinder.FindAllDeclarationsWithNormalQueryInCurrentProcessAsync(
                        project, query, criteria, cancellationToken).ConfigureAwait(false);

                    return (IList <SerializableSymbolAndProjectId>)result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate);
                }
            }, cancellationToken));
        }
Пример #30
0
        protected override bool IsResultDeclaration(Declaration declaration, DeclarationFinder finder)
        {
            if (declaration.AsTypeName != Tokens.Integer)
            {
                return(false);
            }

            switch (declaration)
            {
            case ParameterDeclaration parameter:
                return(ParameterIsResult(parameter, finder));

            case ModuleBodyElementDeclaration member:
                return(MethodIsResult(member));

            default:
                return(declaration.DeclarationType != DeclarationType.LibraryFunction);
            }
        }
 public static Dictionary<string, List<SyntaxToken>> GetAllDeclarations(SyntaxNode syntax)
 {
     var finder = new DeclarationFinder();
     finder.Visit(syntax);
     return finder.map;
 }