public string ResolveExpression(TextEditorData ed, Document doc, int offset, out int startOffset)
        {
            startOffset = offset;
            var editorData = DResolverWrapper.CreateEditorData(doc);

            if (editorData == null)
            {
                return(null);
            }
            editorData.CaretOffset = offset;
            var edLoc = ed.OffsetToLocation(offset);

            editorData.CaretLocation = new CodeLocation(edLoc.Column, edLoc.Line);

            var o = DResolver.GetScopedCodeObject(editorData);

            if (o != null)
            {
                startOffset = ed.LocationToOffset(o.Location.Line, o.Location.Column);
                if (o is INode)
                {
                    return((o as INode).Name);
                }
                return(o.ToString());
            }

            return(null);
        }
        public override Task <Container <SelectionRange> > Handle(SelectionRangeParam request,
                                                                  CancellationToken cancellationToken)
        {
            var workDone = ProgressManager.WorkDone(request,
                                                    new WorkDoneProgressBegin {
                Message = "Begin getting selection ranges", Percentage = 0.0
            });
            var progress   = ProgressManager.For(request, cancellationToken);
            var allResults = new List <SelectionRange>();

            int progressPosition = 0;

            foreach (var position in request.Positions)
            {
                var editorData = DResolverWrapper.CreateEditorData(new HoverParams
                {
                    Position     = position,
                    TextDocument = request.TextDocument
                }, cancellationToken);
                allResults.Add(FindIdealSelectionRange(editorData));
                progress?.OnNext(new Container <SelectionRange>(allResults));
                workDone.OnNext(new WorkDoneProgressReport
                {
                    Percentage = ((double)++progressPosition / request.Positions.Count()) * 100
                });
            }

            progress?.OnCompleted();
            workDone.OnCompleted();
            return(Task.FromResult(progress != null
                ? new Container <SelectionRange>()
                : new Container <SelectionRange>(allResults)));
        }
        public static DParameterDataProvider Create(Document doc, IAbstractSyntaxTree SyntaxTree, CodeCompletionContext ctx)
        {
            var caretLocation = new CodeLocation(ctx.TriggerLineOffset, ctx.TriggerLine);

            try {
                var edData = DResolverWrapper.GetEditorData(doc);

                edData.CaretLocation = caretLocation;
                edData.CaretOffset   = ctx.TriggerOffset;

                var argsResult = ParameterInsightResolution.ResolveArgumentContext(edData);

                if (argsResult == null || argsResult.ResolvedTypesOrMethods == null || argsResult.ResolvedTypesOrMethods.Length < 1)
                {
                    return(null);
                }

                return(new DParameterDataProvider(doc, argsResult)
                {
                    startoffset = ctx.TriggerOffset
                });
            } catch {
                return(null);
            }
        }
Exemple #4
0
        bool UpdateMarkers()
        {
            try
            {
                var dom = SyntaxTree;

                if (dom == null)
                {
                    return(false);
                }

                ResolutionContext ctxt;
                var rr = DResolverWrapper.ResolveHoveredCode(out ctxt, Document);

                if (rr == null || rr.Length < 1)
                {
                    return(false);
                }

                var parseCache = Document.HasProject ?
                                 (Document.Project as AbstractDProject).ParseCache :
                                 DCompilerService.Instance.GetDefaultCompiler().GenParseCacheView();

                var mr = rr[0] as DSymbol;

                if (mr == null)
                {
                    return(false);
                }

                var referencedNode = mr.Definition;

                // Slightly hacky: To keep highlighting the id of e.g. a NewExpression, take the ctor's parent node (i.e. the class node)
                if (referencedNode is DMethod && ((DMethod)referencedNode).SpecialType == DMethod.MethodType.Constructor)
                {
                    mr             = mr.Base as DSymbol;
                    referencedNode = mr.Definition;
                }
                try
                {
                    var references = D_Parser.Refactoring.ReferencesFinder.Scan(dom, referencedNode, ctxt).ToList();

                    if (references.Count > 0)
                    {
                        ShowReferences(references);
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.LogWarning("Error during usage highlighting analysis", ex);
                }
            }
            catch (Exception ex)
            {
                LoggingService.LogDebug("Error while highlighting symbol usages", ex);
            }
            return(false);
        }
Exemple #5
0
        /// <summary>
        /// Inserts import statement into correct place
        /// </summary>
        static void ApplySolution(string import, Document doc)
        {
            var eData = DResolverWrapper.CreateEditorData(doc);
            var loc   = new CodeLocation(0, DParser.FindLastImportStatementEndLocation(eData.SyntaxTree, eData.ModuleCode).Line + 1);

            doc.Editor.Insert(doc.Editor.GetLine(loc.Line).Offset, import.Trim() + doc.Editor.EolMarker);

            //IOInterface.InsertIntoCode(loc, "import " + mod.ModuleName + ";\n");
        }
        /// <summary>
        /// Reads the current caret context, and opens the adequate reference site in the default browser
        /// </summary>
        public static string GetReferenceUrl()
        {
            var caret = Ide.IdeApp.Workbench.ActiveDocument.Editor.Caret.Location;

            ResolutionContext ctxt = null;
            var rr = DResolverWrapper.ResolveHoveredCode(out ctxt, Ide.IdeApp.Workbench.ActiveDocument);

            return(GetReferenceUrl(rr != null ? rr [0] : null, ctxt, new CodeLocation(caret.Column, caret.Line)));
        }
        public static void BuildCompletionData(Document EditorDocument,
                                               DModule SyntaxTree,
                                               CodeCompletionContext ctx,
                                               CompletionDataList l,
                                               char triggerChar)
        {
            var ed = DResolverWrapper.CreateEditorData(EditorDocument, SyntaxTree, ctx, triggerChar);

            CodeCompletion.GenerateCompletionData(ed, new CompletionDataGenerator(l, null), triggerChar);
        }
Exemple #8
0
        public void Parse()
        {
            Clear();

            var editor  = MonoDevelop.Ide.IdeApp.Workbench.ActiveDocument;
            var project = ((editor != null && editor.HasProject) ? editor.Project : MonoDevelop.Ide.IdeApp.ProjectOperations.CurrentSelectedProject) as AbstractDProject;
            var file    = FindTraceLogFileName(project);

            if (file == null)
            {
                profilerPadWidget.AddTracedFunction(0, 0, 0, 0, new DVariable {
                    Name = trace_log + " not found.."
                });
                return;
            }

            var ctxt = ResolutionContext.Create(DResolverWrapper.CreateParseCacheView(editor), null, null);

            StreamReader reader = File.OpenText(file);
            string       line;

            while ((line = reader.ReadLine()) != null)
            {
                var m = traceFuncRegex.Match(line);

                if (m.Success)
                {
                    var symName = m.Groups["name"].Value;

                    if (symName.StartsWith("="))
                    {
                        continue;
                    }

                    bool mightBeLegalUnresolvableSymbol;
                    var  dn = ExamTraceSymbol(symName, ctxt, out mightBeLegalUnresolvableSymbol);

                    long v;
                    if (dn != null || mightBeLegalUnresolvableSymbol)
                    {
                        profilerPadWidget.AddTracedFunction(
                            long.TryParse(m.Groups["numcalls"].Value, out v) ? v : 0,
                            long.TryParse(m.Groups["treetime"].Value, out v) ? v : 0,
                            long.TryParse(m.Groups["functime"].Value, out v) ? v : 0,
                            long.TryParse(m.Groups["percall"].Value, out v) ? v : 0,
                            dn ?? new DVariable {
                            Name = symName
                        });
                    }
                }
            }
        }
Exemple #9
0
 public static void BuildCompletionData(Document EditorDocument,
                                        DModule SyntaxTree,
                                        CodeCompletionContext ctx,
                                        CompletionDataList l,
                                        char triggerChar)
 {
     AbstractCompletionProvider.BuildCompletionData(
         new CompletionDataGenerator {
         CompletionDataList = l
     },
         DResolverWrapper.CreateEditorData(EditorDocument, SyntaxTree as DModule, ctx, triggerChar),
         triggerChar == '\0'?null:triggerChar.ToString());
 }
        public static void CreateImportStatementForCurrentCodeContext()
        {
            var doc    = IdeApp.Workbench.ActiveDocument;
            var edData = DResolverWrapper.CreateEditorData(doc);

            try
            {
                ImportGen_CustImplementation.CreateImportDirectiveForHighlightedSymbol(edData, new ImportGen_CustImplementation(doc));
            }
            catch (Exception ex)
            {
                MessageService.ShowError(IdeApp.Workbench.RootWindow, "Error during import directive creation", ex.Message);
            }
        }
        public static ResolutionContext CreateContext(Document doc, bool pushFirstScope = true)
        {
            if (doc != null)
            {
                var ed = DResolverWrapper.CreateEditorData(doc);
                if (pushFirstScope)
                {
                    return(new ResolutionContext(ed.ParseCache, new ConditionalCompilationFlags(ed), ed.SyntaxTree, ed.CaretLocation));
                }
                return(new ResolutionContext(ed.ParseCache, new ConditionalCompilationFlags(ed)));
            }

            return(new ResolutionContext(DResolverWrapper.CreateParseCacheView(),
                                         new ConditionalCompilationFlags(VersionIdEvaluation.GetOSAndCPUVersions(), 1, true)));
        }
        protected override bool TryResolve(out Tuple <ResolutionContext, DSymbol> resolveResult)
        {
            ResolutionContext lastCtxt;
            IEditorData       ed;
            var rr = DResolverWrapper.ResolveHoveredCode(out lastCtxt, out ed, Document);

            if (rr == null || rr.Length < 1 || !(rr[0] is DSymbol))
            {
                resolveResult = null;
                return(false);
            }

            resolveResult = new Tuple <ResolutionContext, DSymbol>(lastCtxt, rr[0] as DSymbol);

            return(true);
        }
Exemple #13
0
        public override TooltipItem GetItem(TextEditor editor, int offset)
        {
            // Note: Normally, the document already should be open
            var doc = IdeApp.Workbench.GetDocument(editor.Document.FileName);

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

            var ast = doc.GetDAst();

            // Due the first note, the AST already should exist
            if (ast == null)
            {
                return(null);
            }

            // Get code cache
            var codeCache = DResolverWrapper.CreateParseCacheView(doc);

            // Create editor context
            var line = editor.GetLineByOffset(offset);

            var ed = new EditorData {
                CaretOffset   = offset,
                CaretLocation = new CodeLocation(offset - line.Offset, editor.OffsetToLineNumber(offset)),
                ModuleCode    = editor.Text,
                ParseCache    = codeCache,
                SyntaxTree    = ast
            };

            // Let the engine build all contents
            LooseResolution.NodeResolutionAttempt att;
            ISyntaxRegion sr;
            var           rr = LooseResolution.ResolveTypeLoosely(ed, out att, out sr, true);

            // Create tool tip item
            if (rr != null)
            {
                return(new TooltipItem(new TTI {
                    t = rr, sr = sr
                }, offset, 1));
            }

            return(null);
        }
Exemple #14
0
        public override Task <Hover> Handle(HoverParams request, CancellationToken cancellationToken)
        {
            var editorData           = DResolverWrapper.CreateEditorData(request, cancellationToken);
            var resolvedHoveredTypes = LooseResolution.ResolveTypeLoosely(editorData, out LooseResolution.NodeResolutionAttempt resolutionAttempt, out ISyntaxRegion syntaxRegion, true);

            var markup = string.Join(Environment.NewLine + Environment.NewLine, AmbiguousType.TryDissolve(resolvedHoveredTypes)
                                     .Where(t => t != null)
                                     .Select(t => TooltipMarkupGen.CreateSignatureMarkdown(t)));

            return(Task.FromResult(new Hover
            {
                Contents = new MarkedStringsOrMarkupContent(new MarkupContent
                {
                    Kind = MarkupKind.Markdown,
                    Value = markup
                }),
                Range = syntaxRegion.ToRange()
            }));
        }
Exemple #15
0
        /// <summary>
        /// Returns possible imports for current context
        /// </summary>
        IEnumerable <string> GetSolutions(Document doc)
        {
            //i had to copy-paste some code from other files
            ResolutionContext ctxt;
            var rr = Resolver.DResolverWrapper.ResolveHoveredCode(out ctxt);

            if (rr != null && rr.Length > 0)
            {
                var res = rr[rr.Length - 1];
                var n   = DResolver.GetResultMember(res);
                if (n != null)
                {
                    //seems like this can filter function calls
                    yield break;
                }
            }

            INode[] nodes;
            bool    req;
            var     edData = DResolverWrapper.CreateEditorData(doc);

            try
            {
                nodes = ImportDirectiveCreator.TryFindingSelectedIdImportIndependently(edData, out req);
            }
            catch
            {
                yield break;
            }
            if (!req || nodes == null)
            {
                yield break;
            }
            foreach (var node in nodes)
            {
                var mod = node.NodeRoot as DModule;
                if (mod != null && mod != edData.SyntaxTree)
                {
                    yield return(mod.ModuleName);
                }
            }
            yield break;
        }
Exemple #16
0
        public static ResolutionContext CreateCurrentContext()
        {
            Document doc = null;

            DispatchService.GuiSyncDispatch(() => doc = Ide.IdeApp.Workbench.ActiveDocument);
            if (doc != null)
            {
                var ddoc = doc.ParsedDocument as ParsedDModule;
                if (ddoc != null)
                {
                    var ast = ddoc.DDom;
                    if (ast != null)
                    {
                        IStatement stmt;
                        var        caret = new D_Parser.Dom.CodeLocation(doc.Editor.Caret.Column, doc.Editor.Caret.Line);
                        var        bn    = DResolver.SearchBlockAt(ast, caret, out stmt);
                        var        dbn   = bn as DBlockNode;
                        if (stmt == null && dbn != null)
                        {
                            //TODO: If inside an expression statement, search the nearest function call or template instance expression - and try to evaluate that one.

                            if (dbn.StaticStatements.Count != 0)
                            {
                                foreach (var ss in dbn.StaticStatements)
                                {
                                    if (caret >= ss.Location && caret <= ss.EndLocation)
                                    {
                                        stmt = ss;
                                        break;
                                    }
                                }
                            }
                        }

                        var ed = DResolverWrapper.CreateEditorData(doc);
                        return(new ResolutionContext(ed.ParseCache, new ConditionalCompilationFlags(ed), bn, stmt));
                    }
                }
            }
            return(new ResolutionContext(DResolverWrapper.CreateCacheList(),
                                         new ConditionalCompilationFlags(VersionIdEvaluation.GetOSAndCPUVersions(), 1, true), null));
        }
Exemple #17
0
        public override TooltipItem GetItem(TextEditor editor, int offset)
        {
            // Note: Normally, the document already should be open
            var doc = IdeApp.Workbench.GetDocument(editor.Document.FileName);

            if (doc == null || !(doc.ParsedDocument is ParsedDModule))
            {
                return(null);
            }

            // Due the first note, the AST already should exist
            var ast = (doc.ParsedDocument as ParsedDModule).DDom;

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

            // Get code cache
            var codeCache = DResolverWrapper.CreateCacheList(doc);

            // Create editor context
            var line = editor.GetLineByOffset(offset);

            var EditorContext = new EditorData {
                CaretOffset   = offset,
                CaretLocation = new CodeLocation(offset - line.Offset, editor.OffsetToLineNumber(offset)),
                ModuleCode    = editor.Text,
                ParseCache    = codeCache,
                SyntaxTree    = ast as DModule
            };

            // Let the engine build all contents
            var ttContents = AbstractTooltipProvider.BuildToolTip(EditorContext);

            // Create tool tip item
            if (ttContents != null)
            {
                return(new TooltipItem(ttContents, offset, 1));
            }
            return(null);
        }
Exemple #18
0
        private static EditorData CreateCompletionEditorData(CompletionParams completionParams,
                                                             CancellationToken cancellationToken, out char triggerChar)
        {
            var triggerString = completionParams.Context.TriggerCharacter ?? string.Empty;

            triggerChar = triggerString.Length > 0 ? triggerString[0] : '\0';

            var editorData = DResolverWrapper.CreateEditorData(completionParams, cancellationToken);

            bool removeChar = char.IsLetter(triggerChar) || triggerChar == '_';

            if (removeChar)
            {
                editorData.CaretOffset  -= 1;
                editorData.CaretLocation = new CodeLocation(editorData.CaretLocation.Column - 1,
                                                            editorData.CaretLocation.Line);
            }

            return(editorData);
        }
Exemple #19
0
        void FindReferences_Upd(CommandInfo ci)
        {
            lastResults = DResolverWrapper.ResolveHoveredCode(out lastContext);

            if (lastResults == null || lastResults.Length == 0)
            {
                ci.Bypass = true;
                return;
            }

            ci.Bypass = true;

            foreach (var r in lastResults)
            {
                if ((firstResultNode = DResolver.GetResultMember(r)) != null)
                {
                    ci.Bypass = false;
                    return;
                }
            }
        }
Exemple #20
0
        public override Task <LocationOrLocationLinks> Handle(DefinitionParams request, CancellationToken cancellationToken)
        {
            var progress = ProgressManager.For(request, cancellationToken);
            var work     = ProgressManager.WorkDone(request, new WorkDoneProgressBegin
            {
                Title   = "Resolve symbol definition location",
                Message = "Begin resolving definition under caret"
            });

            var editorData = DResolverWrapper.CreateEditorData(request, cancellationToken);
            var results    = DResolverWrapper.ResolveHoveredCodeLoosely(editorData, out LooseResolution.NodeResolutionAttempt resolutionAttempt, out ISyntaxRegion syntaxRegion);

            var result = new LocationOrLocationLinks(
                results.Select(ExpressionTypeEvaluation.GetResultMember)
                .Select(node => ToLocationOrLocationLink(node, Capability.LinkSupport, syntaxRegion)));

            progress?.OnNext(new Container <LocationOrLocationLink>(result));
            work.OnCompleted();

            return(Task.FromResult(progress != null ? new LocationOrLocationLinks() : result));
        }
Exemple #21
0
        public static void HandleLdOutput(AbstractDProject prj, BuildResult br, string linkerOutput)
        {
            var ctxt = ResolutionContext.Create(DResolverWrapper.CreateParseCacheView(prj), null, null);

            ctxt.ContextIndependentOptions =
                ResolutionOptions.IgnoreAllProtectionAttributes |
                ResolutionOptions.DontResolveBaseTypes |
                ResolutionOptions.DontResolveBaseClasses |
                ResolutionOptions.DontResolveAliases;

            foreach (Match m in ldErrorRegex.Matches(linkerOutput))
            {
                var error = new BuildError();

                var firstSymbolOccurring = ldMangleRegex.Match(m.Groups["err"].Value);

                if (firstSymbolOccurring.Success)
                {
                    var mangledString    = "_D" + firstSymbolOccurring.Groups["mangle"].Value;
                    var associatedSymbol = DResolver.GetResultMember(Demangler.DemangleAndResolve(mangledString, ctxt));
                    if (associatedSymbol != null)
                    {
                        error.FileName = (associatedSymbol.NodeRoot as DModule).FileName;
                        error.Line     = associatedSymbol.Location.Line;
                        error.Column   = associatedSymbol.Location.Column;
                    }
                }

                error.ErrorText = m.Groups["msg"].Value;
                if (string.IsNullOrWhiteSpace(error.ErrorText))
                {
                    error.ErrorText = m.Groups["err"].Value;
                }

                error.ErrorText = DemangleLdOutput(error.ErrorText);

                br.Append(error);
            }
        }
 public static ResolutionContext CreateContext(Document doc, bool pushFirstScope = true)
 {
     if (doc != null)
     {
         var ddoc = doc.ParsedDocument as ParsedDModule;
         if (ddoc != null)
         {
             var ast = ddoc.DDom;
             if (ast != null)
             {
                 var ed = DResolverWrapper.CreateEditorData(doc);
                 if (pushFirstScope)
                 {
                     return(new ResolutionContext(ed.ParseCache, new ConditionalCompilationFlags(ed), ast, ed.CaretLocation));
                 }
                 return(new ResolutionContext(ed.ParseCache, new ConditionalCompilationFlags(ed)));
             }
         }
     }
     return(new ResolutionContext(DResolverWrapper.CreateCacheList(),
                                  new ConditionalCompilationFlags(VersionIdEvaluation.GetOSAndCPUVersions(), 1, true)));
 }
        public bool Update(Document doc = null)
        {
            lastResults = DResolverWrapper.ResolveHoveredCodeLoosely(out ctxt, out ed, out resultResolutionAttempt, doc);

            return(lastResults != null && lastResults.Length > 0);
        }
        public override Task <DocumentHighlightContainer> Handle(DocumentHighlightParams request,
                                                                 CancellationToken cancellationToken)
        {
            var workDone = ProgressManager.WorkDone(request, new WorkDoneProgressBegin
            {
                Title      = "Begin finding highlights",
                Percentage = 0
            });

            var editorData       = DResolverWrapper.CreateEditorData(request, cancellationToken);
            var nodeSymbolToFind = DResolverWrapper
                                   .ResolveHoveredCodeLoosely(editorData, out LooseResolution.NodeResolutionAttempt _,
                                                              out ISyntaxRegion _)
                                   .Select(GetResultMember)
                                   .FirstOrDefault();

            if (nodeSymbolToFind == null)
            {
                workDone.OnNext(new WorkDoneProgressReport()
                {
                    Message    = "No symbol found",
                    Percentage = 100
                });
                workDone.OnCompleted();
                return(Task.FromResult(new DocumentHighlightContainer()));
            }

            var progress = ProgressManager.For(request, cancellationToken);
            List <DocumentHighlight> allFoundReferences;
            var ctxt = ResolutionContext.Create(editorData, true);

            try
            {
                allFoundReferences = cancellationToken.IsCancellationRequested
                    ? new List <DocumentHighlight>()
                    : ReferencesFinder
                                     .SearchModuleForASTNodeReferences(editorData.SyntaxTree, nodeSymbolToFind, ctxt)
                                     .Where(region => region != null)
                                     .OrderBy(region => region.Location)
                                     .Select(ToDocumentHighlight)
                                     .ToList();
            }
            catch (Exception ex)
            {
                workDone.OnError(ex);
                if (progress != null)
                {
                    progress.OnError(ex);
                    return(Task.FromResult(new DocumentHighlightContainer()));
                }

                return(Task.FromException <DocumentHighlightContainer>(ex));
            }

            if (allFoundReferences.Count > 0)
            {
                progress?.OnNext(new DocumentHighlightContainer(allFoundReferences));
            }

            workDone.OnCompleted();
            progress?.OnCompleted();

            return(Task.FromResult(progress != null
                ? new DocumentHighlightContainer()
                : new DocumentHighlightContainer(allFoundReferences)));
        }
        public override List <Change> PerformChanges(RefactoringOptions options, object prop)
        {
            #region Init
            var renameProperties = prop as RenameProperties;
            if (renameProperties == null)
            {
                return(null);
            }

            var changes = new List <Change>();

            var doc = options.Document;
            if (doc == null)
            {
                return(null);
            }

            var ddoc = doc.ParsedDocument as ParsedDModule;
            if (ddoc == null)
            {
                return(null);
            }

            var n = options.SelectedItem as INode;
            if (n == null)
            {
                return(null);
            }

            var project = doc.HasProject ? doc.Project as DProject : null;

            var parseCache = DResolverWrapper.CreateCacheList(project);

            var modules = new List <DModule>();
            if (project == null)
            {
                modules.Add((Ide.IdeApp.Workbench.ActiveDocument.ParsedDocument as ParsedDModule).DDom);
            }
            else
            {
                foreach (var p in project.GetSourcePaths())
                {
                    modules.AddRange(GlobalParseCache.EnumModules(p));
                }
            }

            var ctxt = ResolutionContext.Create(parseCache, null, null);
            #endregion

            // Enumerate references
            foreach (var mod in modules)
            {
                if (mod == null)
                {
                    continue;
                }

                var references = D_Parser.Refactoring.ReferencesFinder.Scan(mod, n, ctxt).ToList();

                if (((DModule)n.NodeRoot).FileName == mod.FileName)
                {
                    references.Insert(0, new IdentifierDeclaration(n.NameHash)
                    {
                        Location = n.NameLocation
                    });
                }

                if (references.Count < 1)
                {
                    continue;
                }

                var txt             = TextFileProvider.Instance.GetEditableTextFile(new FilePath(mod.FileName));
                var prevReplacement = CodeLocation.Empty;
                foreach (ISyntaxRegion reference in references)
                {
                    if (prevReplacement == reference.Location)
                    {
                        continue;
                    }

                    prevReplacement = reference.Location;
                    changes.Add(new TextReplaceChange {
                        FileName     = mod.FileName,
                        InsertedText = renameProperties.NewName,
                        RemovedChars = n.Name.Length,
                        Description  = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), n.Name, renameProperties.NewName),
                        Offset       = txt.GetPositionFromLineColumn(reference.Location.Line, reference.Location.Column)
                    });
                }
            }

            return(changes);
        }
        public override TooltipItem GetItem(Mono.TextEditor.TextEditor editor, int offset)
        {
            if (offset >= editor.Document.TextLength)
            {
                return(null);
            }

            if (!DebuggingService.IsDebugging || DebuggingService.IsRunning)
            {
                return(null);
            }

            var frame = DebuggingService.CurrentFrame;

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

            var ed = (ExtensibleTextEditor)editor;

            string expression = null;
            int    startOffset = 0, length = 0;

            if (ed.IsSomethingSelected && offset >= ed.SelectionRange.Offset && offset <= ed.SelectionRange.EndOffset)
            {
                // This should be handled by the MD-internal Debug value tooltip provider already
                expression  = ed.SelectedText;
                startOffset = ed.SelectionRange.Offset;
                length      = ed.SelectionRange.Length;
            }
            else
            {
                var doc = Ide.IdeApp.Workbench.GetDocument(ed.FileName);
                if (doc == null)
                {
                    return(null);
                }

                var editorData = DResolverWrapper.CreateEditorData(doc);
                editorData.CaretOffset = offset;
                var edLoc = ed.OffsetToLocation(offset);
                editorData.CaretLocation = new D_Parser.Dom.CodeLocation(edLoc.Column, edLoc.Line);
                var ctxt = ResolutionContext.Create(editorData);

                var o = DResolver.GetScopedCodeObject(editorData, ctxt,
                                                      DResolver.AstReparseOptions.AlsoParseBeyondCaret |
                                                      DResolver.AstReparseOptions.OnlyAssumeIdentifierList);

                if (o != null)
                {
                    expression = o.ToString();
                }
            }

            if (string.IsNullOrEmpty(expression))
            {
                return(null);
            }

            ObjectValue val;

            if (!cachedValues.TryGetValue(expression, out val))
            {
                val = frame.GetExpressionValue(expression, true);
                cachedValues [expression] = val;
            }

            if (val == null || val.IsUnknown || val.IsNotSupported)
            {
                return(null);
            }

            val.Name = expression;

            return(new TooltipItem(val, startOffset, length));
        }
        bool UpdateMarkers()
        {
            try
            {
                var dom = SyntaxTree;

                if (dom == null)
                {
                    return(false);
                }

                ResolverContextStack ctxt;
                var rr = DResolverWrapper.ResolveHoveredCode(out ctxt, Document);

                if (rr == null || rr.Length < 1)
                {
                    return(false);
                }

                var parseCache = Document.HasProject ?
                                 (Document.Project as DProject).ParseCache :
                                 ParseCacheList.Create(DCompilerService.Instance.GetDefaultCompiler().ParseCache);

                var mr = rr[0] as DSymbol;

                if (mr == null)
                {
                    return(false);
                }

                var referencedNode = mr.Definition;

                // Slightly hacky: To keep highlighting the id of e.g. a NewExpression, take the ctor's parent node (i.e. the class node)
                if (referencedNode is DMethod && ((DMethod)referencedNode).SpecialType == DMethod.MethodType.Constructor)
                {
                    mr             = mr.Base as DSymbol;
                    referencedNode = mr.Definition;
                }
                try
                {
                    var references = D_Parser.Refactoring.ReferencesFinder.Scan(dom, referencedNode, ctxt).ToList();

                    // Highlight the node's definition location - only if the node is located in the current document
                    if (referencedNode.NodeRoot is IAbstractSyntaxTree &&
                        (referencedNode.NodeRoot as IAbstractSyntaxTree).FileName == dom.FileName)
                    {
                        references.Add(new IdentifierDeclaration(referencedNode.Name)
                        {
                            Location    = referencedNode.NameLocation,
                            EndLocation = new CodeLocation(referencedNode.NameLocation.Column + referencedNode.Name.Length, referencedNode.NameLocation.Line)
                        });
                    }

                    if (references.Count > 0)
                    {
                        ShowReferences(references);
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.LogWarning("Error during usage highlighting analysis", ex);
                }
            }
            catch (Exception ex)
            {
                LoggingService.LogDebug("Error while highlighting symbol usages", ex);
            }
            return(false);
        }
Exemple #28
0
        public override Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            var workDone = ProgressManager.WorkDone(request, new WorkDoneProgressBegin
            {
                Title      = "Begin resolving references",
                Percentage = 0
            });

            var editorData       = DResolverWrapper.CreateEditorData(request, cancellationToken);
            var nodeSymbolToFind = DResolverWrapper
                                   .ResolveHoveredCodeLoosely(editorData, out LooseResolution.NodeResolutionAttempt _, out ISyntaxRegion _)
                                   .Select(ExpressionTypeEvaluation.GetResultMember)
                                   .FirstOrDefault();

            if (nodeSymbolToFind == null)
            {
                workDone.OnNext(new WorkDoneProgressReport()
                {
                    Message    = "No symbol found",
                    Percentage = 100
                });
                workDone.OnCompleted();
                return(Task.FromResult(new LocationContainer()));
            }

            var modules = editorData.ParseCache.EnumRootPackagesSurroundingModule(editorData.SyntaxTree)
                          .SelectMany(package => (IEnumerable <DModule>)package)
                          .Where(module => module != null)
                          .OrderBy(module => module.FileName)
                          .ToList();

            var progress           = ProgressManager.For(request, cancellationToken);
            var allFoundReferences = new List <Location>();
            var ctxt          = ResolutionContext.Create(editorData, true);
            int progressIndex = 0;

            foreach (var module in modules)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    var references = ReferencesFinder.SearchModuleForASTNodeReferences(module, nodeSymbolToFind, ctxt, request.Context.IncludeDeclaration)
                                     .Where(region => region != null)
                                     .OrderBy(region => region.Location)
                                     .Select(region => ToLocation(region, module))
                                     .Where(location => location != default)
                                     .ToList();
                    progressIndex++;
                    if (references.Count > 0)
                    {
                        workDone.OnNext(new WorkDoneProgressReport
                        {
                            Message    = "Scanned " + module.FileName,
                            Percentage = ((double)progressIndex / modules.Count) * 100.0
                        });
                        allFoundReferences.AddRange(references);
                        progress?.OnNext(new Container <Location>(allFoundReferences));
                    }
                }
                catch (Exception ex)
                {
                    workDone.OnError(ex);
                    if (progress != null)
                    {
                        progress.OnError(ex);
                        return(Task.FromResult(new LocationContainer()));
                    }
                    return(Task.FromException <LocationContainer>(ex));
                }
            }

            workDone.OnCompleted();
            progress?.OnCompleted();

            // if $progress sent, result must be empty
            return(Task.FromResult(progress != null ? new LocationContainer()
                : new LocationContainer(allFoundReferences)));
        }
        public bool Update(Document doc = null)
        {
            lastResults = DResolverWrapper.ResolveHoveredCodeLoosely(out ed, out resultResolutionAttempt, out lastSyntaxObject, lastDoc = (doc ?? IdeApp.Workbench.ActiveDocument));

            return(lastResults != null && lastResults.Length > 0);
        }
Exemple #30
0
        static IEnumerable <SearchResult> FindReferences(
            AbstractDProject project,
            INode member,
            ISearchProgressMonitor monitor = null)
        {
            var searchResults = new List <SearchResult>();

            var modules = new List <DModule>();

            if (project != null)
            {
                foreach (var p in project.GetSourcePaths(IdeApp.Workspace.ActiveConfiguration))
                {
                    modules.AddRange(GlobalParseCache.EnumModulesRecursively(p, null));
                }
            }
            else
            {
                modules.Add(IdeApp.Workbench.ActiveDocument.GetDAst());
            }

            if (monitor != null)
            {
                monitor.BeginStepTask("Scan for references", modules.Count, 1);
            }

            List <ISyntaxRegion> references = null;
            var ctxt = ResolutionContext.Create(DResolverWrapper.CreateParseCacheView(project), null);

            foreach (var mod in modules)
            {
                if (mod == null)
                {
                    continue;
                }
                try
                {
                    references = ReferencesFinder.SearchModuleForASTNodeReferences(mod, member, ctxt).ToList();

                    if (references.Count < 1)
                    {
                        if (monitor != null)
                        {
                            monitor.Step(1);
                        }
                        continue;
                    }

                    // Sort the references by code location
                    references.Sort(new IdLocationComparer());

                    // Get actual document code
                    var targetDoc = TextFileProvider.Instance.GetTextEditorData(new FilePath(mod.FileName));

                    foreach (var reference in references)
                    {
                        CodeLocation loc;

                        if (reference is AbstractTypeDeclaration)
                        {
                            loc = ((AbstractTypeDeclaration)reference).NonInnerTypeDependendLocation;
                        }
                        else if (reference is IExpression)
                        {
                            loc = reference.Location;
                        }
                        else if (reference is TemplateParameter)
                        {
                            loc = (reference as TemplateParameter).NameLocation;
                        }
                        else if (reference is INode)
                        {
                            loc = (reference as INode).NameLocation;
                        }
                        else
                        {
                            continue;
                        }

                        searchResults.Add(new SearchResult(new FileProvider(mod.FileName, project),
                                                           targetDoc.LocationToOffset(loc.Line,
                                                                                      loc.Column),
                                                           member.Name.Length));
                    }
                }
                catch (Exception ex) { LoggingService.LogWarning("Error during reference search", ex); }

                if (monitor != null)
                {
                    monitor.Step(1);
                }
            }

            if (monitor != null)
            {
                monitor.EndTask();
            }

            return(searchResults);
        }