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); }
private void CompileAndResolve() { _unresolvedFile = SyntaxTree.ToTypeSystem(); _projectContent = _projectContent.AddOrUpdateFiles(_unresolvedFile); _compilation = _projectContent.CreateCompilation(); _resolver = new CSharpAstResolver(_compilation, SyntaxTree, _unresolvedFile); }
/// <summary> /// Initializes a new instance of the <see cref="CSharpCompletionContext"/> class. /// </summary> /// <param name="document">The document, make sure the FileName property is set on the document.</param> /// <param name="offset">The offset.</param> /// <param name="projectContent">Content of the project.</param> /// <param name="usings">The usings.</param> /// <param name="variables">The variables</param> /// <param name="namespace">The namespace.</param> public CSharpCompletionContext(IDocument document, int offset, IProjectContent projectContent, string usings = null, string variables = null, string @namespace = null) { OriginalDocument = document; OriginalOffset = offset; OriginalUsings = usings; OriginalVariables = variables; OriginalNamespace = @namespace; //if the document is a c# script we have to soround the document with some code. Document = PrepareCompletionDocument(document, ref offset, usings, variables, @namespace); Offset = offset; var syntaxTree = new CSharpParser().Parse(Document, Document.FileName); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); ProjectContent = projectContent.AddOrUpdateFiles(unresolvedFile); //note: it's important that the project content is used that is returned after adding the unresolved file Compilation = ProjectContent.CreateCompilation(); var location = Document.GetLocation(Offset); Resolver = unresolvedFile.GetResolver(Compilation, location); TypeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(Compilation, location); CompletionContextProvider = new DefaultCompletionContextProvider(Document, unresolvedFile); }
public Project(StructEx.Solution solution, string title, string fileName) : base(solution, title, fileName) { Files = new List <File>(); ProjectContent = new CSharpProjectContent(); ResolvedReferencedAssemblies = new List <IUnresolvedAssembly>(); ProjectContent = ProjectContent.SetAssemblyName(AssemblyName); ProjectContent = ProjectContent.SetProjectFileName(fileName); ProjectContent = ProjectContent.SetCompilerSettings(Utils.Convert.ToCompilerSettings(CompilerSettings)); foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile")) { Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude))); } var files = Files.Select(f => f.UnresolvedTypeSystemForFile); ProjectContent = ProjectContent.AddOrUpdateFiles(files); foreach (var projectReference in ReferencedProjects) { ProjectContent = ProjectContent.AddAssemblyReferences(new[] { new ProjectReference(projectReference) }); } ResolveAssemblies(); }
public void AddCodeFile(string fileName, string code) { IUnresolvedFile oldFile = projectContent.GetFile(fileName); IUnresolvedFile newFile = Parse(fileName, code); projectContent = projectContent.AddOrUpdateFiles(newFile); }
public CSharpProject( ICSharpFileFactory cSharpFileFactory, MicrosoftBuildProject msBuildProject, string title) { Title = title; AssemblyName = msBuildProject.AssemblyName; FileName = msBuildProject.FileName; CompilerSettings = #region new CompilerSettings new CompilerSettings { AllowUnsafeBlocks = msBuildProject.AllowUnsafeBlocks, CheckForOverflow = msBuildProject.CheckForOverflowUnderflow, }; CompilerSettings.ConditionalSymbols.AddRange(msBuildProject.DefineConstants); #endregion ProjectContent = new CSharpProjectContent(); ProjectContent = ProjectContent.SetAssemblyName(msBuildProject.AssemblyName); ProjectContent = ProjectContent.SetProjectFileName(msBuildProject.FileName.FullPath); ProjectContent = ProjectContent.SetCompilerSettings(CompilerSettings); Files = msBuildProject.CompiledFileNames.Select( f => cSharpFileFactory.BuildCSharpFile(this, new FilePath(f))).ToList(); ProjectContent = ProjectContent.AddOrUpdateFiles( Files.Select(f => f.UnresolvedTypeSystemForFile)); ProjectContent = ProjectContent.AddAssemblyReferences(msBuildProject.ReferencedAssemblies); }
void AnalyzeFile(ProjectFile file, IProjectContent content) { var me = new object(); var owner = processedFiles.AddOrUpdate(file.Name, me, (key, old) => old); if (me != owner) { return; } if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested) { return; } TextEditorData editor; try { editor = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath); } catch (FileNotFoundException) { // Swallow exception and ignore this file return; } var document = TypeSystemService.ParseFile(file.Project, editor); if (document == null) { return; } var compilation = content.AddOrUpdateFiles(document.ParsedFile).CreateCompilation(); CSharpAstResolver resolver; using (var timer = ExtensionMethods.ResolveCounter.BeginTiming()) { resolver = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile); resolver.ApplyNavigator(new ExtensionMethods.ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Resolve, null)); } var context = document.CreateRefactoringContextWithEditor(editor, resolver, tokenSource.Token); CodeIssueProvider[] codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray(); foreach (var provider in codeIssueProvider) { var severity = provider.GetSeverity(); if (severity == Severity.None || tokenSource.IsCancellationRequested) { return; } try { foreach (var issue in provider.GetIssues(context, tokenSource.Token)) { AddIssue(file, provider, issue); } } catch (OperationCanceledException) { // The operation was cancelled, no-op as the user-visible parts are // handled elsewhere } } }
protected Tuple <CSharpAstResolver, AstNode> PrepareResolver(string code) { SyntaxTree syntaxTree = new CSharpParser().Parse(code.Replace("$", ""), "code.cs"); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node"); SetUp(); CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem(); project = project.AddOrUpdateFiles(unresolvedFile); compilation = project.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile); return(Tuple.Create(resolver, FindNode(syntaxTree, dollars[0], dollars[1]))); }
public void AddOrUpdateCSharpFile(CSharpFile csharpFile) { if (Files.All(f => !f.FileName.Equals(csharpFile.FileName))) { Files.Add(csharpFile); } ProjectContent = ProjectContent.AddOrUpdateFiles(csharpFile.UnresolvedTypeSystemForFile); }
void Init(string program) { pc = new CSharpProjectContent(); pc = pc.SetAssemblyName("MyAssembly"); unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem(); pc = pc.AddOrUpdateFiles(unresolvedFile); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib }); compilation = pc.CreateCompilation(); }
protected override void DoParseStep() { if (document == null) { return; } var unresolvedFile = CSharpParsingHelpers.CreateCSharpUnresolvedFile(document); projectContent = projectContent.AddOrUpdateFiles(unresolvedFile); }
public CSharpCodeCompletionContext(IDocument document, int offset, IProjectContent projectContent) { this.document = new ReadOnlyDocument(document, document.FileName); this.offset = offset; var unresolvedFile = CSharpParsingHelpers.CreateCSharpUnresolvedFile(this.document); this.projectContent = projectContent.AddOrUpdateFiles(unresolvedFile); completionContextProvider = new DefaultCompletionContextProvider(this.document, unresolvedFile); var compilation = this.projectContent.CreateCompilation(); var location = this.document.GetLocation(this.offset); typeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, location); }
private void AddOrUpdateFiles() { typeSystemCache.Clear(); var unresolvedFiles = new IUnresolvedFile[sourceFiles.Count]; Parallel.For(0, unresolvedFiles.Length, i => { var syntaxTree = sourceFiles[i].SyntaxTree; unresolvedFiles[i] = GetTypeSystem(syntaxTree); }); project = project.AddOrUpdateFiles(unresolvedFiles); compilation = project.CreateCompilation(); }
private IProjectContent AddCompileFilesToProject(Project msbuildProject, IProjectContent pc) { foreach (var item in msbuildProject.GetItems("Compile")) { var filepath = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude); if (File.Exists(filepath)) { var file = new CSharpFile(this, filepath); Files.Add(file); } } pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile)); return(pc); }
public void SetUp() { pc = new CSharpProjectContent(); pc = pc.SetAssemblyName("MyAssembly"); unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem(); pc = pc.AddOrUpdateFiles(unresolvedFile); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib }); compilation = pc.CreateCompilation(); baseClass = compilation.RootNamespace.GetTypeDefinition("Base", 1); nestedClass = baseClass.NestedTypes.Single(); derivedClass = compilation.RootNamespace.GetTypeDefinition("Derived", 2); systemClass = compilation.RootNamespace.GetChildNamespace("NS").GetTypeDefinition("System", 0); }
public void ProcessInput(string input, string sourceFile) { if (string.IsNullOrEmpty(sourceFile)) { return; } //see if it contains the word class, enum or struct //todo: this is buggy because if two classes are evaluated seperately, the original file will overwrite it // if the file is a script we should try to extract the class name and use it as the file name. sciptname + class // we can probably use the AST for that. if (input.Contains("class ") || input.Contains("enum ") || input.Contains("struct ")) { var syntaxTree = new CSharpParser().Parse(input, sourceFile); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); projectContent = projectContent.AddOrUpdateFiles(unresolvedFile); } }
public virtual IProjectContent GetProjectContext() { if (Project == null) { if (singleFileContext == null) { singleFileContext = new ICSharpCode.NRefactory.CSharp.CSharpProjectContent(); singleFileContext = singleFileContext.AddAssemblyReferences(new [] { Mscorlib, System, SystemCore }); } if (parsedDocument != null) { return(singleFileContext.AddOrUpdateFiles(parsedDocument.ParsedFile)); } return(singleFileContext); } return(TypeSystemService.GetProjectContext(Project)); }
public static void LoadBaseType(IProjectContent prj) { try { if (BaseTypeFile == null) { var source = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "ALBASE.al"); var asyntaxTree = parser.Parse(source, AppDomain.CurrentDomain.BaseDirectory + "ALBASE.al"); asyntaxTree.Freeze(); BaseTypeFile = asyntaxTree.ToTypeSystem(); } prj.AddOrUpdateFiles(BaseTypeFile); } catch { BaseTypeFile = null; } }
public void ParseInformationUpdated(IUnresolvedFile oldFile, IUnresolvedFile newFile) { // This method is called by the parser service within the parser service (per-file) lock. lock (lockObj) { if (!disposed) { if (newFile != null) { projectContent = projectContent.AddOrUpdateFiles(newFile); } else { projectContent = projectContent.RemoveFiles(oldFile.FileName); } serializedProjectContentIsUpToDate = false; SD.ParserService.InvalidateCurrentSolutionSnapshot(); SD.MainThread.InvokeAsyncAndForget(delegate { assemblyModel.Update(oldFile, newFile); }); } } }
private IProjectContent AddFileToProject(IProjectContent project, string fileName) { string code = string.Empty; try { code = System.IO.File.ReadAllText(fileName); } catch (Exception) { _log.ErrorFormat("Could not find file to AddFileToProject, Name: {0}", fileName); } SyntaxTree syntaxTree = new CSharpParser().Parse(code, fileName); CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem(); if (syntaxTree.Errors.Count == 0) { project = project.AddOrUpdateFiles(unresolvedFile); } return(project); }
/// <summary> /// Initializes a new instance of the <see cref="CSharpCompletionContext"/> class. /// </summary> /// <param name="document">The document, make sure the FileName property is set on the document.</param> /// <param name="offset">The offset.</param> /// <param name="projectContent">Content of the project.</param> /// <param name="usings">The usings.</param> public CSharpCompletionContext(IDocument document, int offset, IProjectContent projectContent, string usings = null) { OriginalDocument = document; OriginalOffset = offset; //if the document is a c# script we have to soround the document with some code. Document = PrepareCompletionDocument(document, ref offset, usings); Offset = offset; var syntaxTree = new CSharpParser().Parse(Document, Document.FileName); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); ProjectContent = projectContent.AddOrUpdateFiles(unresolvedFile); //note: it's important that the project content is used that is returned after adding the unresolved file Compilation = ProjectContent.CreateCompilation(); var location = Document.GetLocation(Offset); Resolver = unresolvedFile.GetResolver(Compilation, location); TypeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(Compilation, location); CompletionContextProvider = new DefaultCompletionContextProvider(Document, unresolvedFile); }
private IProjectContent AddCompileFilesToProject(Project msbuildProject, IProjectContent pc) { foreach (var item in msbuildProject.GetItems("Compile")) { var filepath = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude); if (File.Exists(filepath)) { var file = new CSharpFile(this, filepath); Files.Add(file); } } pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile)); return pc; }
public override IEnumerable<MemberReference> FindReferences (Project project, IProjectContent content, IEnumerable<FilePath> possibleFiles, IEnumerable<object> members) { 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 = 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) { 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 (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; }
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); }
void AnalyzeFile (ProjectFile file, IProjectContent content) { var me = new object (); var owner = processedFiles.AddOrUpdate (file.Name, me, (key, old) => old); if (me != owner) return; if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested) return; TextEditorData editor; try { editor = TextFileProvider.Instance.GetReadOnlyTextEditorData (file.FilePath); } catch (FileNotFoundException) { // Swallow exception and ignore this file return; } var document = TypeSystemService.ParseFile (file.Project, editor); if (document == null) return; var compilation = content.AddOrUpdateFiles (document.ParsedFile).CreateCompilation (); CSharpAstResolver resolver; using (var timer = ExtensionMethods.ResolveCounter.BeginTiming ()) { resolver = new CSharpAstResolver (compilation, document.GetAst<SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile); resolver.ApplyNavigator (new ExtensionMethods.ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null)); } var context = document.CreateRefactoringContextWithEditor (editor, resolver, tokenSource.Token); var codeIssueProviders = RefactoringService.GetInspectors (editor.MimeType) .SelectMany (p => p.GetEffectiveProviderSet ()) .ToList (); foreach (var provider in codeIssueProviders) { var severity = provider.GetSeverity (); if (severity == Severity.None || !provider.GetIsEnabled () || tokenSource.IsCancellationRequested) continue; try { foreach (var issue in provider.GetIssues (context, tokenSource.Token)) { AddIssue (file, provider, issue); } } catch (OperationCanceledException) { // The operation was cancelled, no-op as the user-visible parts are // handled elsewhere } } }