protected void AddCodeFile(string fileName, string code)
        {
            var oldFile = projectContent.GetFile(fileName);

            Assert.IsNull(oldFile, "Duplicate file name: " + fileName);
            var newFile = Parse(fileName, code);

            projectContent = projectContent.AddOrUpdateFiles(newFile);
            assemblyModel.Update(oldFile, newFile);
        }
        protected void AddCodeFile(string fileName, string code)
        {
            var oldFile = projectContent.GetFile(fileName);

            Assert.IsNull(oldFile);
            var newFile = Parse(fileName, code);

            projectContent = projectContent.AddOrUpdateFiles(newFile);
            testProject.NotifyParseInformationChanged(oldFile, newFile);
        }
Ejemplo n.º 3
0
        public void AddCodeFile(string fileName, string code)
        {
            IUnresolvedFile oldFile = projectContent.GetFile(fileName);
            IUnresolvedFile newFile = Parse(fileName, code);

            projectContent = projectContent.AddOrUpdateFiles(newFile);
        }
Ejemplo n.º 4
0
        static IEnumerable <Tag> GetSpecialComments(IProjectContent ctx, string name)
        {
            var doc = ctx.GetFile(name) as ParsedDocument;

            if (doc == null)
            {
                return(Enumerable.Empty <Tag> ());
            }
            return((IEnumerable <Tag>)doc.TagComments);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// This method can take some time to finish. It's not threaded
 /// </summary>
 /// <returns>
 /// A <see cref="ParsedDocument"/> that contains the current dom.
 /// </returns>
 public ParsedDocument UpdateParseDocument()
 {
     try {
         string currentParseFile = FileName;
         var    editor           = Editor;
         if (editor == null)
         {
             return(null);
         }
         TypeSystemService.AddSkippedFile(currentParseFile);
         string currentParseText = editor.Text;
         this.parsedDocument = TypeSystemService.ParseFile(Project, currentParseFile, editor.Document.MimeType, currentParseText);
         if (Project == null && this.parsedDocument != null)
         {
             singleFileContext = GetProjectContext().UpdateProjectContent(singleFileContext.GetFile(currentParseFile), parsedDocument.ParsedFile);
         }
     } finally {
         OnDocumentParsed(EventArgs.Empty);
     }
     return(this.parsedDocument);
 }
Ejemplo n.º 6
0
		public override IEnumerable<MemberReference> FindReferences (Project project, IProjectContent content, IEnumerable<FilePath> possibleFiles, IEnumerable<object> members)
		{
			if (project == null)
				throw new ArgumentNullException ("project", "Project not set.");
			if (content == null)
				throw new ArgumentNullException ("content", "Project content not set.");
			SetPossibleFiles (possibleFiles);
			SetSearchedMembers (members);
			
			var scopes = searchedMembers.Select (e => refFinder.GetSearchScopes (e as IEntity));
			var compilation = TypeSystemService.GetCompilation (project);
			List<MemberReference> refs = new List<MemberReference> ();
			foreach (var opendoc in openDocuments) {
				foreach (var newRef in FindInDocument (opendoc.Item2)) {
					if (newRef == null || refs.Any (r => r.FileName == newRef.FileName && r.Region == newRef.Region))
						continue;
					refs.Add (newRef);
				}
			}
			
			foreach (var file in files) {
				string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText (file);
				if (memberName != null && text.IndexOf (memberName, StringComparison.Ordinal) < 0 &&
					(keywordName == null || text.IndexOf (keywordName, StringComparison.Ordinal) < 0))
					continue;
				using (var editor = TextEditorData.CreateImmutable (text)) {
					editor.Document.FileName = file;
					var unit = new CSharpParser ().Parse (editor);
					if (unit == null)
						continue;
					
					var storedFile = content.GetFile (file);
					var parsedFile = storedFile as CSharpParsedFile;
					
					if (parsedFile == null && storedFile is ParsedDocumentDecorator) {
						parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpParsedFile;
					}
					
					if (parsedFile == null) {
						// for fallback purposes - should never happen.
						parsedFile = unit.ToTypeSystem ();
						content = content.UpdateProjectContent (content.GetFile (file), parsedFile);
						compilation = content.CreateCompilation ();
					}
					foreach (var scope in scopes) {
						refFinder.FindReferencesInFile (
							scope,
							parsedFile,
							unit,
							compilation,
							(astNode, result) => {
								var newRef = GetReference (result, astNode, file, editor);
								if (newRef == null || refs.Any (r => r.FileName == newRef.FileName && r.Region == newRef.Region))
									return;
								refs.Add (newRef);
							},
							CancellationToken.None
						);
					}
				}
			}
			return refs;
		}
Ejemplo n.º 7
0
        void RenameReferencesInFile(SymbolRenameArgs args, IFindReferenceSearchScope searchScope, FileName fileName, Action <PatchedFile> callback, Action <Error> errorCallback, bool isNameValid, CancellationToken cancellationToken)
        {
            ITextSource textSource = args.ParseableFileContentFinder.Create(fileName);

            if (textSource == null)
            {
                return;
            }
            if (searchScope.SearchTerm != null)
            {
                if (textSource.IndexOf(searchScope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) < 0)
                {
                    return;
                }
            }

            var parseInfo = SD.ParserService.Parse(fileName, textSource) as CSharpFullParseInformation;

            if (parseInfo == null)
            {
                return;
            }
            ReadOnlyDocument         document    = null;
            IHighlighter             highlighter = null;
            List <RenameResultMatch> results     = new List <RenameResultMatch>();

            // Grab the unresolved file matching the compilation version
            // (this may differ from the version created by re-parsing the project)
            CSharpUnresolvedFile unresolvedFile = null;
            IProjectContent      pc             = compilation.MainAssembly.UnresolvedAssembly as IProjectContent;

            if (pc != null)
            {
                unresolvedFile = pc.GetFile(fileName) as CSharpUnresolvedFile;
            }

            CSharpAstResolver resolver = new CSharpAstResolver(compilation, parseInfo.SyntaxTree, unresolvedFile);

            fr.RenameReferencesInFile(
                new[] { searchScope }, args.NewName, resolver,
                delegate(RenameCallbackArguments callbackArgs) {
                var node       = callbackArgs.NodeToReplace;
                string newCode = callbackArgs.NewNode.ToString();
                if (document == null)
                {
                    document = new ReadOnlyDocument(textSource, fileName);

                    if (args.ProvideHighlightedLine)
                    {
                        highlighter = SD.EditorControlService.CreateHighlighter(document);
                        highlighter.BeginHighlighting();
                    }
                }
                var startLocation = node.StartLocation;
                var endLocation   = node.EndLocation;
                int offset        = document.GetOffset(startLocation);
                int length        = document.GetOffset(endLocation) - offset;
                if (args.ProvideHighlightedLine)
                {
                    var builder          = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter);
                    var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null;
                    results.Add(new RenameResultMatch(fileName, startLocation, endLocation, offset, length, newCode, builder, defaultTextColor));
                }
                else
                {
                    results.Add(new RenameResultMatch(fileName, startLocation, endLocation, offset, length, newCode));
                }
            },
                errorCallback, cancellationToken);
            if (highlighter != null)
            {
                highlighter.Dispose();
            }
            if (results.Count > 0)
            {
                if (!isNameValid)
                {
                    errorCallback(new Error(ErrorType.Error, string.Format("The name '{0}' is not valid in the current context!", args.NewName),
                                            new DomRegion(fileName, results[0].StartLocation)));
                    return;
                }
                IDocument changedDocument = new TextDocument(document);
                var       oldVersion      = changedDocument.Version;
                foreach (var result in results.OrderByDescending(m => m.StartOffset))
                {
                    changedDocument.Replace(result.StartOffset, result.Length, result.NewCode);
                }
                callback(new PatchedFile(fileName, results, oldVersion, changedDocument.Version));
            }
        }
Ejemplo n.º 8
0
        void FindReferencesInFile(SymbolSearchArgs args, IFindReferenceSearchScope searchScope, FileName fileName, Action <SearchedFile> callback, CancellationToken cancellationToken)
        {
            ITextSource textSource = args.ParseableFileContentFinder.Create(fileName);

            if (textSource == null)
            {
                return;
            }
            if (searchScope.SearchTerm != null)
            {
                if (textSource.IndexOf(searchScope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) < 0)
                {
                    return;
                }
            }

            var parseInfo = SD.ParserService.Parse(fileName, textSource) as CSharpFullParseInformation;

            if (parseInfo == null)
            {
                return;
            }
            ReadOnlyDocument         document    = null;
            IHighlighter             highlighter = null;
            List <SearchResultMatch> results     = new List <SearchResultMatch>();

            // Grab the unresolved file matching the compilation version
            // (this may differ from the version created by re-parsing the project)
            CSharpUnresolvedFile unresolvedFile = null;
            IProjectContent      pc             = compilation.MainAssembly.UnresolvedAssembly as IProjectContent;

            if (pc != null)
            {
                unresolvedFile = pc.GetFile(fileName) as CSharpUnresolvedFile;
            }

            fr.FindReferencesInFile(
                searchScope, unresolvedFile, parseInfo.SyntaxTree, compilation,
                delegate(AstNode node, ResolveResult result) {
                if (document == null)
                {
                    document    = new ReadOnlyDocument(textSource, fileName);
                    highlighter = SD.EditorControlService.CreateHighlighter(document);
                    highlighter.BeginHighlighting();
                }
                Identifier identifier = node.GetChildByRole(Roles.Identifier);
                if (!identifier.IsNull)
                {
                    node = identifier;
                }
                var region           = new DomRegion(fileName, node.StartLocation, node.EndLocation);
                int offset           = document.GetOffset(node.StartLocation);
                int length           = document.GetOffset(node.EndLocation) - offset;
                var builder          = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter);
                var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null;
                results.Add(new SearchResultMatch(fileName, node.StartLocation, node.EndLocation, offset, length, builder, defaultTextColor));
            }, cancellationToken);
            if (highlighter != null)
            {
                highlighter.Dispose();
            }
            if (results.Count > 0)
            {
                callback(new SearchedFile(fileName, results));
            }
        }
		static IEnumerable<Tag> GetSpecialComments (IProjectContent ctx, string name)
		{
			var doc = ctx.GetFile (name) as ParsedDocument;
			if (doc == null)
				return Enumerable.Empty<Tag> ();
			return (IEnumerable<Tag>)doc.TagComments;
		}
        void ParseFiles(List <FileName> filesToParse, IProgressMonitor progressMonitor)
        {
            IProjectContent            cachedPC = TryReadFromCache(cacheFileName);
            ParseableFileContentFinder finder   = new ParseableFileContentFinder();

            object progressLock                   = new object();
            double fileCountInverse               = 1.0 / filesToParse.Count;
            int    fileCountLoadedFromCache       = 0;
            int    fileCountParsed                = 0;
            int    fileCountParsedAndSerializable = 0;

            Parallel.ForEach(
                filesToParse,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount,
                CancellationToken      = progressMonitor.CancellationToken
            },
                fileName => {
                ITextSource content            = finder.CreateForOpenFile(fileName);
                bool wasLoadedFromCache        = false;
                IUnresolvedFile unresolvedFile = null;
                if (content == null && cachedPC != null)
                {
                    unresolvedFile = cachedPC.GetFile(fileName);
                    if (unresolvedFile != null && unresolvedFile.LastWriteTime == File.GetLastWriteTimeUtc(fileName))
                    {
                        parserService.RegisterUnresolvedFile(fileName, project, unresolvedFile);
                        wasLoadedFromCache = true;
                    }
                }
                if (!wasLoadedFromCache)
                {
                    if (content == null)
                    {
                        try {
                            content = SD.FileService.GetFileContentFromDisk(fileName);
                        } catch (IOException) {
                        } catch (UnauthorizedAccessException) {
                        }
                    }
                    if (content != null)
                    {
                        unresolvedFile = parserService.ParseFile(fileName, content, project);
                    }
                }
                lock (progressLock) {
                    if (wasLoadedFromCache)
                    {
                        fileCountLoadedFromCache++;
                    }
                    else
                    {
                        fileCountParsed++;
                        if (IsSerializable(unresolvedFile))
                        {
                            fileCountParsedAndSerializable++;
                        }
                    }
//						SD.MainThread.InvokeAsyncAndForget(delegate { assemblyModel.Update(null, unresolvedFile); });
                    progressMonitor.Progress += fileCountInverse;
                }
            });
            LoggingService.Debug(projectContent.AssemblyName + ": ParseFiles() finished. "
                                 + fileCountLoadedFromCache + " files were re-used from CC cache; "
                                 + fileCountParsed + " files were parsed (" + fileCountParsedAndSerializable + " of those are serializable)");
            lock (lockObj) {
                serializedProjectContentIsUpToDate = (fileCountLoadedFromCache > 0 && fileCountParsedAndSerializable == 0);
            }
        }
        public override IEnumerable <MemberReference> FindReferences(Project project, IProjectContent content, IEnumerable <FilePath> possibleFiles, IProgressMonitor monitor, IEnumerable <object> members)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content", "Project content not set.");
            }
            SetPossibleFiles(possibleFiles);
            SetSearchedMembers(members);

            var scopes      = searchedMembers.Select(e => e is IEntity ? refFinder.GetSearchScopes((IEntity)e) : refFinder.GetSearchScopes((INamespace)e));
            var compilation = project != null?TypeSystemService.GetCompilation(project) : content.CreateCompilation();

            List <MemberReference> refs = new List <MemberReference> ();

            foreach (var opendoc in openDocuments)
            {
                foreach (var newRef in FindInDocument(opendoc.Item2))
                {
                    if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                    {
                        continue;
                    }
                    refs.Add(newRef);
                }
            }
            foreach (var file in files)
            {
                if (monitor != null)
                {
                    monitor.Step(1);
                }
                string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText(file);
                if (memberName != null && text.IndexOf(memberName, StringComparison.Ordinal) < 0 &&
                    (keywordName == null || text.IndexOf(keywordName, StringComparison.Ordinal) < 0))
                {
                    continue;
                }
                using (var editor = TextEditorData.CreateImmutable(text)) {
                    editor.Document.FileName = file;
                    var unit = new PlayScriptParser().Parse(editor);
                    if (unit == null)
                    {
                        continue;
                    }

                    var storedFile = content.GetFile(file);
                    var parsedFile = storedFile as CSharpUnresolvedFile;

                    if (parsedFile == null && storedFile is ParsedDocumentDecorator)
                    {
                        parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpUnresolvedFile;
                    }

                    if (parsedFile == null)
                    {
                        // for fallback purposes - should never happen.
                        parsedFile  = unit.ToTypeSystem();
                        content     = content.AddOrUpdateFiles(parsedFile);
                        compilation = content.CreateCompilation();
                    }
                    foreach (var scope in scopes)
                    {
                        refFinder.FindReferencesInFile(
                            scope,
                            parsedFile,
                            unit,
                            compilation,
                            (astNode, result) => {
                            var newRef = GetReference(project, result, astNode, unit, file, editor);
                            if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                            {
                                return;
                            }
                            refs.Add(newRef);
                        },
                            CancellationToken.None
                            );
                    }
                }
            }
            return(refs);
        }