Represents a VBComponent or a VBProject.
 /// <summary>
 /// Creates an inspection result.
 /// </summary>
 protected InspectionResultBase(IInspection inspection, QualifiedModuleName qualifiedName, ParserRuleContext context, CommentNode comment = null)
 {
     _inspection = inspection;
     _qualifiedName = qualifiedName;
     _context = context;
     _comment = comment;
 }
        public static TestMethod NewTestMethod(VBE vbe)
        {
            if (vbe.ActiveCodePane == null)
            {
                return null;
            }

            try
            {
                if (vbe.ActiveCodePane.CodeModule.HasAttribute<TestModuleAttribute>())
                {
                    var module = vbe.ActiveCodePane.CodeModule;
                    var name = GetNextTestMethodName(module.Parent);
                    var body = TestMethodTemplate.Replace(NamePlaceholder, name);
                    module.InsertLines(module.CountOfLines, body);

                    var qualifiedModuleName = new QualifiedModuleName(module.Parent);
                    return new TestMethod(new QualifiedMemberName(qualifiedModuleName, name), vbe);
                }
            }
            catch (COMException)
            {
            }

            return null;
        }
 public OptionExplicitInspectionResult(IInspection inspection, QualifiedModuleName qualifiedName) 
     : base(inspection, new CommentNode(string.Empty, Tokens.CommentMarker, new QualifiedSelection(qualifiedName, Selection.Home)))
 {
     _quickFixes = new[]
     {
         new OptionExplicitQuickFix(Context, QualifiedSelection), 
     };
 }
 public void TestInitialization()
 {
     _vbe = new Mock<VBE>();
     _vbProject = new Mock<VBProject>();
     _declarations = new Declarations();
     _module = new QualifiedModuleName();
     _view = new Mock<IRenameView>();
 }
Beispiel #5
0
 private void RunMethodCleanup(QualifiedModuleName qualifiedModuleName)
 {
     var handler = MethodCleanup;
     if (handler != null)
     {
         handler(this, new TestModuleEventArgs(qualifiedModuleName));
     }
 }
Beispiel #6
0
 private void RunModuleInitialize(QualifiedModuleName qualifiedModuleName)
 {
     var handler = ModuleInitialize;
     if (handler != null)
     {
         handler(this, new TestModuleEventArgs(qualifiedModuleName));
     }
 }
 public ComponentParseTask(VBComponent vbComponent, VBAPreprocessor preprocessor, IAttributeParser attributeParser, TokenStreamRewriter rewriter = null)
 {
     _attributeParser = attributeParser;
     _preprocessor = preprocessor;
     _component = vbComponent;
     _rewriter = rewriter;
     _qualifiedName = new QualifiedModuleName(vbComponent); 
 }
 /// <summary>
 /// Creates an inspection result.
 /// </summary>
 protected CodeInspectionResultBase(string inspection, CodeInspectionSeverity type, QualifiedModuleName qualifiedName, ParserRuleContext context, CommentNode comment = null)
 {
     _name = inspection;
     _type = type;
     _qualifiedName = qualifiedName;
     _context = context;
     _comment = comment;
 }
 public ImplicitActiveSheetReferenceInspectionResult(IInspection inspection, string result, ParserRuleContext context, QualifiedModuleName qualifiedName)
     : base(inspection, qualifiedName, context)
 {
     _result = result;
     _quickFixes = new CodeInspectionQuickFix[]
     {
         new IgnoreOnceQuickFix(context, QualifiedSelection, Inspection.AnnotationName), 
     };
 }
 public UntypedFunctionUsageInspectionResult(IInspection inspection, string result, QualifiedModuleName qualifiedName, ParserRuleContext context) 
     : base(inspection, qualifiedName, context)
 {
     _result = result;
     _quickFixes = new CodeInspectionQuickFix[]
     {
         new UntypedFunctionUsageQuickFix(Context, QualifiedSelection), 
         new IgnoreOnceQuickFix(Context, QualifiedSelection, Inspection.AnnotationName), 
     };
 }
        public IEnumerable<IAnnotation> ModuleAnnotations(QualifiedModuleName module)
        {
            IAnnotation[] result;
            if (_annotations.TryGetValue(module, out result))
            {
                return result;
            }

            return new List<IAnnotation>();
        }
 public IdentifierReference(QualifiedModuleName qualifiedName, string identifierName, Selection selection, ParserRuleContext context, Declaration declaration, bool isAssignmentTarget = false, bool hasExplicitLetStatement = false)
 {
     _qualifiedName = qualifiedName;
     _identifierName = identifierName;
     _selection = selection;
     _context = context;
     _declaration = declaration;
     _hasExplicitLetStatement = hasExplicitLetStatement;
     _isAssignmentTarget = isAssignmentTarget;
 }
        public IEnumerable<CommentNode> ModuleComments(QualifiedModuleName module)
        {
            CommentNode[] result;
            if (_comments.TryGetValue(module, out result))
            {
                return result;
            }

            return new List<CommentNode>();
        }
 public IdentifierNotAssignedInspectionResult(IInspection inspection, Declaration target,
     ParserRuleContext context, QualifiedModuleName qualifiedName)
     : base(inspection, target, context, qualifiedName)
 {
     _target = target;
     _quickFixes = new CodeInspectionQuickFix[]
     {
         new RemoveUnassignedIdentifierQuickFix(Context, QualifiedSelection), 
         new IgnoreOnceQuickFix(context, QualifiedSelection, Inspection.AnnotationName), 
     };
 }
 private Declaration CreateProjectDeclaration(QualifiedModuleName projectQualifiedName, VBProject project)
 {
     var qualifiedName = projectQualifiedName.QualifyMemberName(project.Name);
     var projectId = qualifiedName.QualifiedModuleName.ProjectId;
     var projectDeclaration = new ProjectDeclaration(qualifiedName, project.Name);
     var references = _projectReferences.Where(projectContainingReference => projectContainingReference.ContainsKey(projectId));
     foreach (var reference in references)
     {
         int priority = reference[projectId];
         projectDeclaration.AddProjectReference(reference.ReferencedProjectId, priority);
     }
     return projectDeclaration;
 }
        public VBComponentParseResult(VBComponent component, IParseTree parseTree, IEnumerable<CommentNode> comments, ITokenStream tokenStream)
        {
            _component = component;
            _qualifiedName = new QualifiedModuleName(component);
            _parseTree = parseTree;
            _comments = comments;
            _tokenStream = tokenStream;

            var listener = new DeclarationSymbolsListener(_qualifiedName, Accessibility.Implicit, _component.Type);
            var walker = new ParseTreeWalker();
            walker.Walk(listener, _parseTree);

            _declarations.AddRange(listener.Declarations.Items);
        }
        public DeclarationSymbolsListener(
            QualifiedModuleName qualifiedName,
            Accessibility componentAccessibility,
            vbext_ComponentType type,
            IEnumerable<CommentNode> comments,
            IEnumerable<IAnnotation> annotations,
            IDictionary<Tuple<string, DeclarationType>, Attributes> attributes,
            HashSet<ReferencePriorityMap> projectReferences)
        {
            _qualifiedName = qualifiedName;
            _comments = comments;
            _annotations = annotations;
            _attributes = attributes;

            var declarationType = type == vbext_ComponentType.vbext_ct_StdModule
                ? DeclarationType.Module
                : DeclarationType.Class;

            var project = _qualifiedName.Component.Collection.Parent;
            var projectQualifiedName = new QualifiedModuleName(project);
            _projectReferences = projectReferences;

            _projectDeclaration = CreateProjectDeclaration(projectQualifiedName, project);

            var key = Tuple.Create(_qualifiedName.ComponentName, declarationType);
            var moduleAttributes = attributes.ContainsKey(key)
                ? attributes[key]
                : new Attributes();

            _moduleDeclaration = new Declaration(
                _qualifiedName.QualifyMemberName(_qualifiedName.Component.Name),
                _projectDeclaration,
                _projectDeclaration,
                _qualifiedName.Component.Name,
                false,
                false,
                componentAccessibility,
                declarationType,
                null, Selection.Home, false,
                FindAnnotations(), moduleAttributes);

            SetCurrentScope();
        }
        public DeclarationSymbolsListener(QualifiedModuleName qualifiedName, Accessibility componentAccessibility, vbext_ComponentType type)
        {
            _qualifiedName = qualifiedName;

            var declarationType = type == vbext_ComponentType.vbext_ct_StdModule
                ? DeclarationType.Module
                //: result.Component.Type == vbext_ComponentType.vbext_ct_MSForm 
                //    ? DeclarationType.UserForm
                //    : result.Component.Type == vbext_ComponentType.vbext_ct_Document
                //        ? DeclarationType.Document
                : DeclarationType.Class;

            SetCurrentScope();
            _declarations.Add(new Declaration(_qualifiedName.QualifyMemberName(_qualifiedName.Component.Name), _qualifiedName.Project.Name, _qualifiedName.Component.Name, false, false, componentAccessibility, declarationType, null, Selection.Home));

            if (type == vbext_ComponentType.vbext_ct_MSForm)
            {
                DeclareControlsAsMembers(qualifiedName.Component);
            }
        }
 public IdentifierReference(
     QualifiedModuleName qualifiedName, 
     Declaration parentScopingDeclaration, 
     Declaration parentNonScopingDeclaration, 
     string identifierName,
     Selection selection, 
     ParserRuleContext context, 
     Declaration declaration, 
     bool isAssignmentTarget = false,
     bool hasExplicitLetStatement = false, 
     IEnumerable<IAnnotation> annotations = null)
 {
     _parentScopingDeclaration = parentScopingDeclaration;
     _parentNonScopingDeclaration = parentNonScopingDeclaration;
     _qualifiedName = qualifiedName;
     _identifierName = identifierName;
     _selection = selection;
     _context = context;
     _declaration = declaration;
     _hasExplicitLetStatement = hasExplicitLetStatement;
     _isAssignmentTarget = isAssignmentTarget;
     _annotations = annotations ?? new List<IAnnotation>();
 }
Beispiel #20
0
 public TestModuleEventArgs(QualifiedModuleName qualifiedModuleName)
 {
     _qualifiedModuleName = qualifiedModuleName;
 }
        private IEnumerable<CommentNode> ParseComments(QualifiedModuleName qualifiedName)
        {
            var code = qualifiedName.Component.CodeModule.Code();
            var commentBuilder = new StringBuilder();
            var continuing = false;

            var startLine = 0;
            var startColumn = 0;

            for (var i = 0; i < code.Length; i++)
            {
                var line = code[i];                
                var index = 0;

                if (continuing || line.HasComment(out index))
                {
                    startLine = continuing ? startLine : i;
                    startColumn = continuing ? startColumn : index;

                    var commentLength = line.Length - index;

                    continuing = line.EndsWith("_");
                    if (!continuing)
                    {
                        commentBuilder.Append(line.Substring(index, commentLength).TrimStart());
                        var selection = new Selection(startLine + 1, startColumn + 1, i + 1, line.Length + 1);

                        var result = new CommentNode(commentBuilder.ToString(), new QualifiedSelection(qualifiedName, selection));
                        commentBuilder.Clear();
                        
                        yield return result;
                    }
                    else
                    {
                        // ignore line continuations in comment text:
                        commentBuilder.Append(line.Substring(index, commentLength).TrimStart()); 
                    }
                }
            }
        }
        private VBComponentParseResult Parse(VBComponent component, out bool cached)
        {
            try
            {
                VBComponentParseResult cachedValue;
                var name = new QualifiedModuleName(component); // already a performance hit
                if (ParseResultCache.TryGetValue(name, out cachedValue))
                {
                    cached = true;
                    return cachedValue;
                }

                var codeModule = component.CodeModule;
                var lines = codeModule.Lines();

                ITokenStream stream;
                var parseTree = Parse(lines, out stream);
                var comments = ParseComments(name);
                var result = new VBComponentParseResult(component, parseTree, comments, stream);

                var existing = ParseResultCache.Keys.SingleOrDefault(k => k.Project == name.Project && k.ComponentName == name.ComponentName);
                VBComponentParseResult removed;
                ParseResultCache.TryRemove(existing, out removed);
                ParseResultCache.AddOrUpdate(name, module => result, (qName, module) => result);

                cached = false;
                return result;
            }
            catch (SyntaxErrorException exception)
            {
                OnParserError(exception, component);
                cached = false;
                return null;
            }
            catch (COMException)
            {
                cached = false;
                return null;
            }
        }
 public QualifiedMemberName(QualifiedModuleName qualifiedModuleName, string memberName)
 {
     _qualifiedModuleName = qualifiedModuleName;
     _memberName          = memberName;
 }
        public void AcquireTarget_MethodRenamingMoreComponents_CorrectTargetChosen()
        {
            // arange
            // initial selection
            var symbolSelection = new Selection(4, 5, 4, 8);
            var selectedComponent = new QualifiedModuleName("TestProject", "Module1");
            var qualifiedSelection = new QualifiedSelection(selectedComponent, symbolSelection);

            // just for passing null reference exception            
            var context = new Mock<ParserRuleContext>();
            context.SetupGet(c => c.Start.Line).Returns(-1);
            context.SetupGet(c => c.Stop.Line).Returns(-1);
            context.SetupGet(c => c.Stop.Text).Returns("Fake");

            // simulate all the components and symbols   
            IdentifierReference reference;
            var differentComponent = new QualifiedModuleName("TestProject", "Module2");
            var differentMember = new QualifiedMemberName(differentComponent, "Module2");
            AddDeclarationItem(context, new Selection(4, 9, 4, 16), differentMember, DeclarationType.Variable, "FooTest");

            // add references to the Foo declaration item to simulate prod usage
            AddDeclarationItem(context, new Selection(3, 5, 3, 8), differentMember, DeclarationType.Procedure, "Foo");
            var declarationItem = _listDeclarations[_listDeclarations.Count - 1];
            reference = new IdentifierReference(selectedComponent, "Foo", new Selection(7, 5, 7, 11), context.Object, declarationItem);
            AddReference(declarationItem, reference);
            reference = new IdentifierReference(selectedComponent, "Foo", symbolSelection, context.Object, declarationItem);
            AddReference(declarationItem, reference);

            AddDeclarationItem(context, new Selection(1, 1, 1, 1), differentMember, DeclarationType.Module, "Module2");
            var member = new QualifiedMemberName(selectedComponent, "fakeModule");
            AddDeclarationItem(context, new Selection(7, 5, 7, 11), member, DeclarationType.Procedure, "RunFoo");
            AddDeclarationItem(context, new Selection(3, 5, 3, 9), member, DeclarationType.Procedure, "Main");
            AddDeclarationItem(context, new Selection(1, 1, 1, 1), member, DeclarationType.Module, "Module1");

            _view.Setup(view => view.ShowDialog()).Returns(DialogResult.Cancel);
            _view.SetupProperty(view => view.Target);

            //act
            //var presenter = new RenamePresenter(_vbe.Object, _view.Object, _declarations, qualifiedSelection);
            //presenter.Show();

            Assert.Inconclusive("This test is broken");

            //assert
            var retVal = _view.Object.Target;
            Assert.AreEqual("Foo", retVal.IdentifierName, "Selected the correct symbol name");
            Assert.AreEqual(declarationItem.References.Count(), retVal.References.Count());
        }
        private void ResolveReferences(DeclarationFinder finder, VBComponent component, IParseTree tree)
        {
            var state = _state.GetModuleState(component);
            if (_state.Status == ParserState.ResolverError || (state != ParserState.Parsed))
            {
                return;
            }

            Debug.WriteLine("Resolving '{0}'... (thread {1})", component.Name, Thread.CurrentThread.ManagedThreadId);            
            var qualifiedName = new QualifiedModuleName(component);
            var resolver = new IdentifierReferenceResolver(qualifiedName, finder);
            var listener = new IdentifierReferenceListener(resolver);
            if (!string.IsNullOrWhiteSpace(tree.GetText().Trim()))
            {
                var walker = new ParseTreeWalker();
                try
                {
                    walker.Walk(listener, tree);
                    state = ParserState.Ready;
                }
                catch (Exception exception)
                {
                    Debug.Print("Exception thrown resolving '{0}' (thread {2}): {1}", component.Name, exception, Thread.CurrentThread.ManagedThreadId);
                    state = ParserState.ResolverError;
                }
            }

            _state.SetModuleState(component, state);
            Debug.Print("'{0}' is {1}. Resolver took {2}ms to complete (thread {3})", component.Name, _state.GetModuleState(component), /*_resolverTimer[component].ElapsedMilliseconds*/0, Thread.CurrentThread.ManagedThreadId);
        }
        private void ResolveDeclarations(VBComponent component, IParseTree tree)
        {
            var qualifiedModuleName = new QualifiedModuleName(component);

            var obsoleteCallStatementListener = new ObsoleteCallStatementListener();
            var obsoleteLetStatementListener = new ObsoleteLetStatementListener();
            var emptyStringLiteralListener = new EmptyStringLiteralListener();
            var argListWithOneByRefParamListener = new ArgListWithOneByRefParamListener();
            
            try
            {
                ParseTreeWalker.Default.Walk(new CombinedParseTreeListener(new IParseTreeListener[]{
                    obsoleteCallStatementListener,
                    obsoleteLetStatementListener,
                    emptyStringLiteralListener,
                    argListWithOneByRefParamListener,
                }), tree);
                // TODO: these are actually (almost) isnpection results.. we should handle them as such
                _state.ArgListsWithOneByRefParam = argListWithOneByRefParamListener.Contexts.Select(context => new QualifiedContext(qualifiedModuleName, context));
                _state.EmptyStringLiterals = emptyStringLiteralListener.Contexts.Select(context => new QualifiedContext(qualifiedModuleName, context));
                _state.ObsoleteLetContexts = obsoleteLetStatementListener.Contexts.Select(context => new QualifiedContext(qualifiedModuleName, context));
                _state.ObsoleteCallContexts = obsoleteCallStatementListener.Contexts.Select(context => new QualifiedContext(qualifiedModuleName, context));

                // cannot locate declarations in one pass *the way it's currently implemented*,
                // because the context in EnterSubStmt() doesn't *yet* have child nodes when the context enters.
                // so we need to EnterAmbiguousIdentifier() and evaluate the parent instead - this *might* work.
                var declarationsListener = new DeclarationSymbolsListener(qualifiedModuleName, Accessibility.Implicit, component.Type, _state.GetModuleComments(component), _state.GetModuleAnnotations(component),_state.GetModuleAttributes(component), _references);
                // TODO: should we unify the API? consider working like the other listeners instead of event-based
                declarationsListener.NewDeclaration += (sender, e) => _state.AddDeclaration(e.Declaration);
                declarationsListener.CreateModuleDeclarations();
                // rewalk parse tree for second declaration level
                ParseTreeWalker.Default.Walk(declarationsListener, tree);
            } catch (Exception exception)
            {
                Debug.Print("Exception thrown resolving '{0}' (thread {2}): {1}", component.Name, exception, Thread.CurrentThread.ManagedThreadId);
                _state.SetModuleState(component, ParserState.ResolverError);
            }

        }
 public NavigateCodeEventArgs(QualifiedModuleName qualifiedModuleName, Selection selection)
 {
     _qualifiedName = qualifiedModuleName;
     _selection = selection;
 }
 public NavigateCodeEventArgs(QualifiedModuleName qualifiedName, ParserRuleContext context)
 {
     _qualifiedName = qualifiedName;
     _selection = context.GetSelection();
 }
Beispiel #29
0
 public QualifiedSelection(QualifiedModuleName qualifiedName, Selection selection)
 {
     QualifiedName = qualifiedName;
     Selection     = selection;
 }
 public QualifiedMemberName(QualifiedModuleName qualifiedModuleName, string memberName)
 {
     _qualifiedModuleName = qualifiedModuleName;
     _memberName = memberName;
 }
Beispiel #31
0
 private static IEnumerable<QualifiedMemberName> FindModuleInitializeMethods(QualifiedModuleName module)
 {
     return module.Component.GetMembers(vbext_ProcKind.vbext_pk_Proc)
         .Where(m => m.HasAttribute<ModuleInitializeAttribute>())
         .Select(m => m.QualifiedMemberName);
 }
        public void AcquireTarget_MethodRenamingAtSameComponent_CorrectTargetChosen()
        {
            // arange
            var symbolSelection = new Selection(8, 1, 8, 16);
            var selectedComponent = new QualifiedModuleName("TestProject", "TestModule");
            var qualifiedSelection = new QualifiedSelection(selectedComponent, symbolSelection);

            // just for passing null reference exception            
            var context = new Mock<ParserRuleContext>();
            context.SetupGet(c => c.Start.Line).Returns(1);
            context.SetupGet(c => c.Stop.Line).Returns(2);
            context.SetupGet(c => c.Stop.Text).Returns("Four");

            // simulate all the components and symbols   
            var member = new QualifiedMemberName(selectedComponent, "fakeModule");
            const string identifierName = "Foo";
            AddDeclarationItem(context, symbolSelection, member, DeclarationType.Procedure, identifierName);
            AddDeclarationItem(context, new Selection(1, 1, 1, 16), member, DeclarationType.Procedure);
            AddDeclarationItem(context, new Selection(1, 1, 1, 1), member, DeclarationType.Module);

            // allow Moq to set the Target property
            _view.Setup(view => view.ShowDialog()).Returns(DialogResult.Cancel);
            _view.SetupProperty(view => view.Target);

            //act
            Assert.Inconclusive("This test is broken");
            //var presenter = new RenamePresenter(_vbe.Object, _view.Object, _declarations, qualifiedSelection);
            //presenter.Show();

            //assert
            var retVal = _view.Object.Target;
            Assert.AreEqual(symbolSelection, retVal.Selection, "Returns only the declaration on the desired selection");
            Assert.AreEqual(identifierName, retVal.IdentifierName);
        }