Ejemplo n.º 1
0
        public void UpdateModule(string filename, string srcText, bool verbose)
        {
            filename = normalizePath(filename);
            DModule ast;

            try
            {
                ast = DParser.ParseString(srcText, false, true, _taskTokens);
            }
            catch (Exception ex)
            {
                ast = new DModule {
                    ParseErrors = new System.Collections.ObjectModel.ReadOnlyCollection <ParserError>(
                        new List <ParserError> {
                        new ParserError(false, ex.Message + "\n\n" + ex.StackTrace, DTokens.Invariant, CodeLocation.Empty)
                    })
                };                            //WTF
            }
            if (string.IsNullOrEmpty(ast.ModuleName))
            {
                ast.ModuleName = Path.GetFileNameWithoutExtension(filename);
            }
            ast.FileName = filename;

            _modules [filename] = ast;
            GlobalParseCache.AddOrUpdateModule(ast);

            _editorData.ParseCache = null;

            _sources[filename] = srcText;
            //MessageBox.Show("UpdateModule(" + filename + ")");
            //throw new NotImplementedException();
            _activityCounter++;
        }
Ejemplo n.º 2
0
        public virtual bool CanHandle(FilePath fileName, string mimeType, Project ownerProject)
        {
            if (excludeThis)
            {
                return(false);
            }

            var dprj = ownerProject as AbstractDProject;

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

            var mod = GlobalParseCache.GetModule(fileName.ToString());

            if (GetGtkDMainClass(mod) == null)
            {
                return(false);
            }

            excludeThis = true;
            var db = DisplayBindingService.GetDefaultViewBinding(fileName, mimeType, ownerProject);

            excludeThis = false;
            return(db != null);
        }
Ejemplo n.º 3
0
        void parsingFinished(ParsingFinishedEventArgs ea)
        {
            // Update UFCS cache
            var pcw = GenParseCacheView();

            foreach (var path in IncludePaths)
            {
                var r = GlobalParseCache.GetRootPackage(path);

                //HACK: Ensure that the includes list won't get changed during parsing
                if (r == null)
                {
                    throw new ArgumentNullException("Root package must not be null - either a parse error occurred or the list was changed in between");
                }

                //TODO: Supply global condition flags? -- At least the vendor id
                r.UfcsCache.BeginUpdate(pcw);
            }

            HadInitialParse = true;

            if (FinishedParsing != null)
            {
                FinishedParsing(ea);
            }
        }
Ejemplo n.º 4
0
        public void UpdateModule(string filename, string srcText, bool verbose)
        {
            DModule ast;

            try
            {
                ast = DParser.ParseString(srcText, false);
            }
            catch (Exception ex)
            {
                ast = new DModule {
                    ParseErrors = new System.Collections.ObjectModel.ReadOnlyCollection <ParserError>(
                        new List <ParserError> {
                        new ParserError(false, ex.Message + "\n\n" + ex.StackTrace, DTokens.Invariant, CodeLocation.Empty)
                    })
                };                            //WTF
            }
            if (string.IsNullOrEmpty(ast.ModuleName))
            {
                ast.ModuleName = Path.GetFileNameWithoutExtension(filename);
            }
            ast.FileName = filename;

            //GlobalParseCache.RemoveModule(filename);
            GlobalParseCache.AddOrUpdateModule(ast);
            ConditionalCompilationFlags cflags = new ConditionalCompilationFlags(_editorData);

            //GlobalParseCache.UfcsCache.CacheModuleMethods(ast, ResolutionContext.Create(_parseCacheList, cflags, null, null));

            _modules[filename] = ast;
            _sources[filename] = srcText;
            //MessageBox.Show("UpdateModule(" + filename + ")");
            //throw new NotImplementedException();
        }
Ejemplo n.º 5
0
        static DModule ParseFile(Uri uri, string code)
        {
            var module = DParser.ParseString(code);

            module.FileName = uri.AbsolutePath;
            GlobalParseCache.AddOrUpdateModule(module);
            return(module);
        }
Ejemplo n.º 6
0
        public static void UpdateParseCacheAsync(IEnumerable <string> Cache, bool skipfunctionbodies = false, ParseFinishedHandler onfinished = null)
        {
            if (Cache == null)
            {
                throw new ArgumentNullException("Cache");
            }

            GlobalParseCache.BeginAddOrUpdatePaths(Cache, skipfunctionbodies, onfinished);
        }
Ejemplo n.º 7
0
        public static void UpdateParseCacheAsync(IEnumerable <string> Cache, string fallBack, string solutionPath, bool skipfunctionbodies = false, ParseFinishedHandler onfinished = null)
        {
            if (Cache == null)
            {
                throw new ArgumentNullException("Cache");
            }

            GlobalParseCache.BeginAddOrUpdatePaths(Parser.DParserWrapper.EnsureAbsolutePaths(Cache, fallBack, solutionPath), skipfunctionbodies, finishedHandler: onfinished);
        }
Ejemplo n.º 8
0
        public void GetReferences(string filename, string tok, uint line, uint idx, string expr)
        {
            filename = normalizePath(filename);
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _request = Request.References;
            _result  = "__pending__";

            Action dg = () =>
            {
                _setupEditorData();
                CodeLocation loc = new CodeLocation((int)idx + 1, (int)line);
                _editorData.CaretLocation = loc;
                _editorData.SyntaxTree    = ast as DModule;
                _editorData.ModuleCode    = _sources[filename];
                _editorData.CaretOffset   = getCodeOffset(_editorData.ModuleCode, loc);

                ISyntaxRegion sr = DResolver.GetScopedCodeObject(_editorData);
                LooseResolution.NodeResolutionAttempt attempt;
                var rr = sr != null?LooseResolution.ResolveTypeLoosely(_editorData, sr, out attempt, true) : null;

                StringBuilder refs = new StringBuilder();
                if (rr != null)
                {
                    var n = DResolver.GetResultMember(rr, true);

                    if (n != null)
                    {
                        var ctxt = ResolutionContext.Create(_editorData, true);
                        if (n.ContainsAttribute(DTokens.Private) || ((n is DVariable) && (n as DVariable).IsLocal))
                        {
                            GetReferencesInModule(ast, refs, n, ctxt);
                        }
                        else
                        {
                            foreach (var basePath in _imports.Split(nlSeparator, StringSplitOptions.RemoveEmptyEntries))
                            {
                                foreach (var mod in GlobalParseCache.EnumModulesRecursively(basePath))
                                {
                                    GetReferencesInModule(mod, refs, n, ctxt);
                                }
                            }
                        }
                    }
                    //var res = TypeReferenceFinder.Scan(_editorData, System.Threading.CancellationToken.None, null);
                }
                if (!_editorData.CancelToken.IsCancellationRequested && _request == Request.References)
                {
                    _result = refs.ToString();
                }
            };
        }
        public static DModule GetFileSyntaxTree(string file, out AbstractDProject OwnerProject)
        {
            var doc = IdeApp.Workbench.ActiveDocument;

            OwnerProject = doc.Project as AbstractDProject;
            var dparsedDoc = doc.ParsedDocument as MonoDevelop.D.Parser.ParsedDModule;

            return(dparsedDoc != null ? dparsedDoc.DDom : GlobalParseCache.GetModule(file));
        }
Ejemplo n.º 10
0
        public virtual void Dispose()
        {
            var root = GlobalParseCache.GetRootPackage(FileName);

            if (root != null)
            {
                root.UfcsCache.RemoveModuleMethods(this);
            }
        }
Ejemplo n.º 11
0
        private void button_ReparseProjSources_Click(object sender, RoutedEventArgs e)
        {
            if (ManagedProject == null)
            {
                return;
            }

            button_ReparsePrjDirectory.IsEnabled = false;
            GlobalParseCache.BeginAddOrUpdatePaths(new[] { ManagedProject.BaseDirectory }, false, (ParsingFinishedEventArgs ea) => button_ReparsePrjDirectory.IsEnabled = true);
        }
Ejemplo n.º 12
0
        public DModule GetModule(string fileName)
        {
            DModule mod;

            if (!_modules.TryGetValue(fileName, out mod))
            {
                GlobalParseCache.GetModule(fileName);
            }
            return(mod);
        }
Ejemplo n.º 13
0
 public void Dispose()
 {
     GlobalParseCache.ParseTaskFinished -= ParseTaskFinished;
     Console.WriteLine("Deleting folder " + _subFolder);
     Directory.Delete(_subFolder, true);
     if (_parseFinishedSemaphore.WaitOne(0))
     {
         Assert.That(GlobalParseCache.RemoveRoot(_subFolder));
     }
 }
Ejemplo n.º 14
0
 public void TearDown()
 {
     GlobalParseCache.RemoveRoot(Lsp4DUtil.DefaultWorkspaceRoot);
     if (Client != null)
     {
         Client.Dispose();
         Assert.IsTrue(Client.Shutdown().Wait(5000));
     }
     Client = null;
     //Lsp4DUtil.CleanDefaultWorkspace();
 }
Ejemplo n.º 15
0
        public static ParseCacheView ParsePhobos(bool ufcs = true)
        {
            var dir = "/usr/include/d";

            GlobalParseCache.ParseTaskFinished += pc_FinishedParsing;
            GlobalParseCache.BeginAddOrUpdatePaths(new[] { dir }, false);

            GlobalParseCache.WaitForFinish();

            return(new ParseCacheView(new[] { dir }));
        }
Ejemplo n.º 16
0
        public DModule GetModule(string fileName)
        {
            DModule mod;

            mod = GlobalParseCache.GetModule(fileName);
            if (mod == null)
            {
                _modules.TryGetValue(fileName, out mod);
            }
            return(mod);
        }
Ejemplo n.º 17
0
        public void ConfigureSemanticProject(string filename, string imp, string stringImp, string versionids, string debugids, string cmdline, uint flags)
        {
            _editorDataProvider.ConfigureEnvironment(imp, versionids, debugids, flags);

            if (_imports != imp)
            {
                string[] uniqueDirs = EditorDataProvider.uniqueDirectories(imp);
                GlobalParseCache.BeginAddOrUpdatePaths(uniqueDirs, taskTokens: _taskTokens);
                _activityCounter++;
            }
            _imports = imp;
        }
Ejemplo n.º 18
0
        static void Add(ISet <RootPackage> results, IEnumerable <string> paths)
        {
            RootPackage pack;

            foreach (var p in paths)
            {
                if ((pack = GlobalParseCache.GetRootPackage(p)) != null)
                {
                    results.Add(pack);
                }
            }
        }
Ejemplo n.º 19
0
        public void Add(IEnumerable <string> roots)
        {
            RootPackage rp;

            foreach (var r in roots)
            {
                if ((rp = GlobalParseCache.GetRootPackage(r)) != null && !packs.Contains(rp))
                {
                    packs.Add(rp);
                }
            }
        }
Ejemplo n.º 20
0
        public void GetReferences(string filename, string tok, uint line, uint idx, string expr)
        {
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _setupEditorData();
            CodeLocation loc = new CodeLocation((int)idx + 1, (int)line);

            _editorData.CaretLocation = loc;
            _editorData.SyntaxTree    = ast as DModule;
            _editorData.ModuleCode    = _sources[filename];
            _editorData.CaretOffset   = getCodeOffset(_editorData.ModuleCode, loc);

            _references = null;

            ISyntaxRegion sr;

            DResolver.NodeResolutionAttempt attempt;
            var rr = DResolver.ResolveTypeLoosely(_editorData, out attempt, out sr);

            StringBuilder refs = new StringBuilder();

            if (rr != null)
            {
                var n = DResolver.GetResultMember(rr, true);

                if (n != null)
                {
                    var ctxt = ResolutionContext.Create(_editorData, true);
                    if (n.ContainsAttribute(DTokens.Private) || ((n is DVariable) && (n as DVariable).IsLocal))
                    {
                        GetReferencesInModule(ast, refs, n, ctxt);
                    }
                    else
                    {
                        foreach (var basePath in _imports.Split('\n'))
                        {
                            foreach (var mod in GlobalParseCache.EnumModulesRecursively(basePath))
                            {
                                GetReferencesInModule(mod, refs, n, ctxt);
                            }
                        }
                    }
                }
                //var res = TypeReferenceFinder.Scan(_editorData, System.Threading.CancellationToken.None, null);
            }
            _references = refs;
        }
Ejemplo n.º 21
0
            private void ParseTaskFinished(ParsingFinishedEventArgs ea)
            {
                Console.WriteLine("Parse task finished: " + ea.Directory);
                if (!ea.Directory.StartsWith(_subFolder))
                {
                    Assert.Warn("Received ParseTaskFinished-Event for wrong directory (" + ea.Directory + ")");
                    return;
                }

                var moduleFiles = GlobalParseCache.EnumModulesRecursively(_subFolder).ConvertAll(module => module.FileName);

                CollectionAssert.AreEquivalent(moduleFiles, ModuleFileNames);
                _parseFinishedSemaphore.Set();
            }
Ejemplo n.º 22
0
        public DModule GetModule(string fileName)
        {
            if (!_sources.ContainsKey(fileName))
            {
                return(null);
            }
            DModule mod = GlobalParseCache.GetModule(fileName);

            if (mod == null)
            {
                _modules.TryGetValue(fileName, out mod);
            }
            return(mod);
        }
Ejemplo n.º 23
0
 public void ConfigureSemanticProject(string filename, string imp, string stringImp, string versionids, string debugids, uint flags)
 {
     if (_imports != imp)
     {
         string[] uniqueDirs = uniqueDirectories(imp);
         GlobalParseCache.BeginAddOrUpdatePaths(uniqueDirs);
     }
     _imports       = imp;
     _stringImports = stringImp;
     _versionIds    = versionids;
     _debugIds      = debugids;
     _flags         = flags;
     _setupEditorData();
     //MessageBox.Show("ConfigureSemanticProject()");
     //throw new NotImplementedException();
 }
Ejemplo n.º 24
0
        public static async Task SetWorkspaceRoots(IEnumerable <string> workspaceFolders,
                                                   ProgressManager progressManager, IWorkDoneProgressParams workDoneProgressParams)
        {
            WorkspaceFolders.OnNext(workspaceFolders.ToImmutableList());

            var completionSource     = new TaskCompletionSource <bool>();
            var initialParseProgress = progressManager.WorkDone(workDoneProgressParams, new WorkDoneProgressBegin()
            {
                Title      = "Begin parsing workspace",
                Percentage = 0
            });

            var partProgresses = GlobalParseCache.BeginAddOrUpdatePaths(WorkspaceFolders.Value, finishedHandler:
                                                                        ea =>
            {
                initialParseProgress.OnNext(new WorkDoneProgressReport()
                {
                    Message    = "Done parsing workspace",
                    Percentage = 100
                });
                initialParseProgress.OnCompleted();
                completionSource.SetResult(true);
            });

            int partIndex = 1;

            foreach (var statisticsHandle in partProgresses)
            {
                initialParseProgress.OnNext(new WorkDoneProgressReport()
                {
                    Percentage = partIndex / partProgresses.Count,
                    Message    = "Parse " + statisticsHandle.basePath
                });
                statisticsHandle.WaitForCompletion();
                partIndex++;

                initialParseProgress.OnNext(new WorkDoneProgressReport()
                {
                    Percentage = partIndex / partProgresses.Count,
                    Message    = "Finished parsing " + statisticsHandle.basePath
                });
            }

            await completionSource.Task;
        }
Ejemplo n.º 25
0
        public override Task <ISearchDataSource> GetResults(SearchPopupSearchPattern s, int resultsCount, CancellationToken token)
        {
            return(Task.Factory.StartNew(delegate {
                var l = new List <INode>();

                foreach (var project in IdeApp.Workspace.GetAllProjects())
                {
                    var dprj = project as AbstractDProject;
                    if (dprj == null)
                    {
                        continue;
                    }

                    ModulePackage pack;
                    foreach (var p in dprj.GetSourcePaths())
                    {
                        if ((pack = GlobalParseCache.GetRootPackage(p)) != null)
                        {
                            foreach (DModule m in pack)
                            {
                                SearchResultsIn(m, s.Pattern, l, resultsCount);
                            }
                        }
                    }

                    foreach (var p in dprj.IncludePaths)
                    {
                        if ((pack = GlobalParseCache.GetRootPackage(p)) != null)
                        {
                            foreach (DModule m in pack)
                            {
                                SearchResultsIn(m, s.Pattern, l, resultsCount);
                            }
                        }
                    }
                }

                return (ISearchDataSource) new DSearchDataSource(l)
                {
                    SearchPattern = s.Pattern
                };
            }, token));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Searches in current solution and in the global cache for the given file and returns it.
        /// If not found, file will be parsed.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DModule GetFileSyntaxTree(string file, out DProject OwnerProject)
        {
            OwnerProject = null;
            var mod = GlobalParseCache.GetModule(file);

            if (CoreManager.CurrentSolution != null)
            {
                foreach (var prj in CoreManager.CurrentSolution)
                {
                    var dprj = prj as DProject;

                    if (dprj != null && dprj.ContainsFile(file))
                    {
                        OwnerProject = dprj;
                    }
                }
            }

            return(mod ?? DParser.ParseFile(file));
        }
Ejemplo n.º 27
0
        static IEnumerable <DModule> TryGetGenericImportingPackageForSymbol(DNode nodeToTestImportabilityFor)
        {
            if (nodeToTestImportabilityFor == null)
            {
                yield break;
            }

            var moduleContainingPackage = GlobalParseCache.GetPackage(nodeToTestImportabilityFor.NodeRoot as DModule);

            while (moduleContainingPackage != null)
            {
                // Search for package.d-Modules;
                var packageModule = (moduleContainingPackage.Parent ?? moduleContainingPackage).GetModule(moduleContainingPackage.NameHash);

                if (packageModule == null)
                {
                    moduleContainingPackage = moduleContainingPackage.Parent;
                    continue;
                }

                // Try to get from found package module to destination node
                var ctxt = new ResolutionContext(new LegacyParseCacheView(new[] { moduleContainingPackage.Root }), null, packageModule);
                ctxt.CurrentContext.ContextDependentOptions = ResolutionOptions.ReturnMethodReferencesOnly | ResolutionOptions.DontResolveBaseTypes;

                var td  = D_Parser.Parser.DParser.ParseBasicType(DNode.GetNodePath(nodeToTestImportabilityFor, true));
                var res = TypeDeclarationResolver.ResolveSingle(td, ctxt, false);

                foreach (var ov in AmbiguousType.TryDissolve(res))
                {
                    if (ov is DSymbol && (ov as DSymbol).Definition == nodeToTestImportabilityFor)
                    {
                        yield return(packageModule);

                        break;
                    }
                }

                moduleContainingPackage = moduleContainingPackage.Parent;
            }
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        public override ParsedDocument Parse(bool storeAst, string file, TextReader content, Project prj = null)
        {
            if (!storeAst)
            {
                return(null);
            }

            ProjectFile pf = null;

            if (prj == null)
            {
                var sln = Ide.IdeApp.ProjectOperations.CurrentSelectedSolution;
                if (sln != null)
                {
                    foreach (var proj in sln.GetAllProjects())
                    {
                        if (proj.IsFileInProject(file))
                        {
                            prj = proj;
                            pf  = proj.GetProjectFile(file);
                            break;
                        }
                    }
                }
            }
            else if (prj.IsFileInProject(file))
            {
                pf = prj.GetProjectFile(file);
            }

            // HACK(?) The folds are parsed before the document gets loaded
            // - so reuse the last parsed document to save time
            // -- What if multiple docs are opened?
            var d = LastParsedMod as ParsedDModule;

            if (d != null && d.FileName == file)
            {
                LastParsedMod = null;
                return(d);
            }
            else
            {
                LastParsedMod = null;
            }

            var dprj = prj as AbstractDProject;

            // Remove obsolete ast from cache
            if (file != null)
            {
                GlobalParseCache.RemoveModule(file);
            }

            DModule ast;
            var     doc = new ParsedDModule(file);

            var parser = DParser.Create(content);

            // Also put attention on non-ddoc comments; These will be used to generate foldable comment regions then
            parser.Lexer.OnlyEnlistDDocComments = false;

            // Parse the code
            try
            {
                ast = parser.Parse();
            }
            catch (TooManyErrorsException)
            {
                ast = parser.Document;
            }

            // Update project owner information / Build appropriate module name
            if (string.IsNullOrEmpty(ast.ModuleName))
            {
                if (pf == null)
                {
                    ast.ModuleName = file != null?Path.GetFileNameWithoutExtension(file) : string.Empty;
                }
                else
                {
                    ast.ModuleName = BuildModuleName(pf);
                }
            }
            ast.FileName = file;

            // Assign new ast to the ParsedDDocument object
            doc.DDom = ast;

            // Add parser errors to the parser output
            foreach (var parserError in parser.ParseErrors)
            {
                doc.ErrorList.Add(new Error(
                                      ErrorType.Error,
                                      parserError.Message,
                                      parserError.Location.Line,
                                      parserError.Location.Column));
            }

            #region Provide comment fold support by addin them to the IDE document object
            foreach (var cm in parser.Comments)
            {
                var c = new MonoDevelop.Ide.TypeSystem.Comment(cm.CommentText)
                {
                    CommentStartsLine = cm.CommentStartsLine,
                    CommentType       = (cm.CommentType & D_Parser.Parser.Comment.Type.Block) != 0 ? CommentType.Block : CommentType.SingleLine,
                    IsDocumentation   = cm.CommentType.HasFlag(D_Parser.Parser.Comment.Type.Documentation),
                };
                if (c.CommentType == CommentType.SingleLine)
                {
                    if (c.IsDocumentation)
                    {
                        c.OpenTag = "///";
                    }
                    else
                    {
                        c.OpenTag = "//";
                    }
                }
                else
                {
                    if (c.IsDocumentation)
                    {
                        c.OpenTag    = "/**";
                        c.ClosingTag = "*/";
                    }
                    else
                    {
                        c.OpenTag    = "/*";
                        c.ClosingTag = "*/";
                    }
                }

                c.Region = new DomRegion(cm.StartPosition.Line, cm.StartPosition.Column, cm.EndPosition.Line, cm.EndPosition.Column);

                doc.Comments.Add(c);

                // Enlist TODO/FIXME/HACK etc. stuff in the IDE's project task list
                for (int i = CommentTag.SpecialCommentTags.Count - 1; i >= 0; i--)
                {
                    if (c.Text.StartsWith(CommentTag.SpecialCommentTags[i].Tag))
                    {
                        doc.Add(new Tag(CommentTag.SpecialCommentTags[i].Tag, c.Text, c.Region));
                        break;
                    }
                }
            }
            #endregion

            #region Serialize to NRefactory Dom structure

            /*
             * var cu = new CompilationUnit(file);
             * doc.CompilationUnit = cu;
             *
             * var global = new DomType(cu, ClassType.Class,
             *      Modifiers.Public | Modifiers.Partial,
             *      "(global)",
             *      new DomLocation(),
             *      ast.ModuleName,
             *      new DomRegion());
             * cu.Add(global);
             *
             * foreach (var n in ast)
             * {
             *      var ch = ConvertDParserToDomNode(n, doc);
             *
             *      if (ch is DomField || ch is DomMethod)
             *              global.Add(ch as IMember);
             *      else
             *              cu.Add(ch as IType);
             * }
             */
            #endregion


            if (prj != null)
            {
                // Workaround for tags not being displayed
                var ctnt = TypeSystemService.GetProjectContentWrapper(prj);
                if (ctnt != null)
                {
                    var tags = ctnt.GetExtensionObject <ProjectCommentTags>();
                    if (tags != null)
                    {
                        tags.UpdateTags(prj, file, doc.TagComments);
                    }
                }
            }

            return(doc);
        }
Ejemplo n.º 30
0
        static IEnumerable <SearchResult> FindReferences(
            AbstractDProject project,
            INode member,
            ISearchProgressMonitor monitor = null)
        {
            var searchResults = new List <SearchResult>();

            var parseCache = project != null ?
                             project.ParseCache : DCompilerService.Instance.GetDefaultCompiler().GenParseCacheView();

            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.ParsedDocument as MonoDevelop.D.Parser.ParsedDModule).DDom);
            }

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

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

            foreach (var mod in modules)
            {
                if (mod == null)
                {
                    continue;
                }
                try
                {
                    references = ReferencesFinder.Scan(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
                        {
                            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);
        }