public static PreparedCompilation CreateCompilation(IEnumerable <ISourceFile> sourceFiles, IEnumerable <IAssemblyReference> references, IList <string> defineConstants) { IProjectContent project = new CSharpProjectContent(); var files = sourceFiles.Select(f => { using (var rdr = f.Open()) { var syntaxTree = CreateParser(defineConstants).Parse(rdr, f.Filename); var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree); syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree); return(new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = f.Filename })); } }).ToList(); foreach (var f in files) { var tcv = new TypeSystemConvertVisitor(f.ParsedFile); f.SyntaxTree.AcceptVisitor(tcv); project = project.AddOrUpdateFiles(f.ParsedFile); } project = project.AddAssemblyReferences(references); return(new PreparedCompilation(project.CreateCompilation(), files)); }
protected void Prepare(string source, bool minimizeNames = true, bool expectErrors = false) { IProjectContent project = new CSharpProjectContent(); var parser = new CSharpParser(); using (var rdr = new StringReader(source)) { var pf = new CSharpUnresolvedFile("File.cs"); var syntaxTree = parser.Parse(rdr, pf.FileName); syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.AddOrUpdateFiles(pf); } project = project.AddAssemblyReferences(new[] { Files.Mscorlib }); var compilation = project.CreateCompilation(); _errorReporter = new MockErrorReporter(!expectErrors); Metadata = new MetadataImporter(_errorReporter, compilation, new CompilerOptions { MinimizeScript = minimizeNames }); Metadata.Prepare(compilation.GetAllTypeDefinitions()); AllErrors = _errorReporter.AllMessages.ToList().AsReadOnly(); AllErrorTexts = _errorReporter.AllMessages.Select(m => m.FormattedMessage).ToList().AsReadOnly(); if (expectErrors) { Assert.That(AllErrorTexts, Is.Not.Empty, "Compile should have generated errors"); } else { Assert.That(AllErrorTexts, Is.Empty, "Compile should not generate errors"); } AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName); }
static public ClassMapper analysecode(string sourceText, string file) { StringBuilder b = new StringBuilder(); ClassMapper mapper = new ClassMapper(); mapper.filename = file; string filename = file; //string sourceText = File.ReadAllText(filename); var parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(sourceText, file); var pc = new CSharpProjectContent(); pc = (CSharpProjectContent)pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()); ICompilation compilation = pc.CreateCompilation(); var resolver = new CSharpAstResolver(compilation, syntaxTree, syntaxTree.ToTypeSystem()); var classVisitor = new ClassVisitor(resolver); classVisitor.filename = filename; classVisitor.b = b; classVisitor.wm = new CacheManager(); classVisitor.mapper = mapper; classVisitor.syntax = syntaxTree; syntaxTree.AcceptVisitor(classVisitor); mapper.syntax = syntaxTree; return(mapper); }
private void Prepare(string source, Action preparer) { IProjectContent project = new CSharpProjectContent(); var parser = new CSharpParser(); using (var rdr = new StringReader(source)) { var pf = new CSharpUnresolvedFile { FileName = "File.cs" }; var syntaxTree = parser.Parse(rdr, pf.FileName); syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.AddOrUpdateFiles(pf); } project = project.AddAssemblyReferences(new[] { Files.Mscorlib }); var compilation = project.CreateCompilation(); AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName); var er = new MockErrorReporter(true); var s = new AttributeStore(compilation, er); Metadata = new MetadataImporter(er, compilation, s, new CompilerOptions()); preparer(); Metadata.Prepare(compilation.GetAllTypeDefinitions()); Assert.That(er.AllMessages, Is.Empty, "Should not generate errrors"); }
public void SetUp() { SD.InitializeForUnitTests(); textEditor = new MockTextEditor(); textEditor.Document.Text = program; var parseInfo = textEditor.CreateParseInformation(); this.project = MockRepository.GenerateStrictMock <IProject>(); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock <IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled( i => { var syntaxTree = new CSharpParser().Parse(textEditor.Document, textEditor.FileName); i.ReturnValue = new CSharpFullParseInformation(syntaxTree.ToTypeSystem(), null, syntaxTree); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock <IFileService>()); IViewContent view = MockRepository.GenerateStrictMock <IViewContent>(); view.Stub(v => v.GetService(typeof(ITextEditor))).Return(textEditor); SD.FileService.Stub(f => f.OpenFile(textEditor.FileName, false)).Return(view); gen = new CSharpCodeGenerator(); }
void SetUpWithCode(FileName fileName, ITextSource textSource) { IProject project = MockRepository.GenerateStrictMock <IProject>(); var parseInfo = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock <IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(fileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(fileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(fileName, textSource)).WhenCalled( i => { i.ReturnValue = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock <IFileService>()); IViewContent view = MockRepository.GenerateStrictMock <IViewContent>(); SD.FileService.Stub(f => f.OpenFile(fileName, false)).Return(view); }
public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles) { var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); return(pc.CreateCompilation()); }
static int GetIndex(string text) { var editorText = new StringBuilder(); int trigger = 0, end = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == '@') { trigger = editorText.Length; continue; } if (text[i] == '$') { end = editorText.Length; continue; } editorText.Append(text [i]); } var doc = new ReadOnlyDocument(editorText.ToString()); var pctx = new CSharpProjectContent(); var rctx = new CSharpTypeResolveContext(pctx.CreateCompilation().MainAssembly); var ctxProvider = new DefaultCompletionContextProvider(doc, new CSharpUnresolvedFile()); var engine = new CSharpParameterCompletionEngine(doc, ctxProvider, new ParameterCompletionTests.TestFactory(pctx), pctx, rctx); return(engine.GetCurrentParameterIndex(trigger, end)); }
void ResolveButtonClick(object sender, EventArgs e) { IProjectContent project = new CSharpProjectContent(); var unresolvedFile = syntaxTree.ToTypeSystem(); project = project.AddOrUpdateFiles(unresolvedFile); //project = project.AddAssemblyReferences(builtInLibs.Value); ICompilation compilation = project.CreateCompilation(); ResolveResult result; if (csharpTreeView.SelectedNode != null) { var selectedNode = (AstNode)csharpTreeView.SelectedNode.Tag; CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile); result = resolver.Resolve(selectedNode); // CSharpAstResolver.Resolve() never returns null } else { TextLocation location = GetTextLocation(csharpCodeTextBox, csharpCodeTextBox.SelectionStart); result = ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location); if (result == null) { MessageBox.Show("Could not find a resolvable node at the caret location."); return; } } using (var dlg = new SemanticTreeDialog(result)) dlg.ShowDialog(); }
public static IList <ITypeDefinition> GetNestedTypes(AssemblyDefinition assemblyDefinition, string fullTypeName) { var loader = new CecilLoader(); loader.IncludeInternalMembers = true; var bridgeAssemblyDefinition = MonoCecilAssemblyHelper.GetBridgeAssemlyDefinition(); var bridgeAssembly = loader.LoadAssembly(bridgeAssemblyDefinition); IProjectContent project = new CSharpProjectContent(); project = project.AddAssemblyReferences(bridgeAssembly); var compilation = project.CreateCompilation(); var ctx = new SimpleTypeResolveContext(compilation); var unresolvedAssembly = loader.LoadAssembly(assemblyDefinition); var assembly = unresolvedAssembly.Resolve(ctx); var parentType = assembly.GetAllTypeDefinitions().FirstOrDefault(x => x.FullName == fullTypeName); if (parentType == null) { return(new List <ITypeDefinition>()); } var nested = parentType.NestedTypes; return(nested); }
void ResolveButtonClick(object sender, EventArgs e) { IProjectContent project = new CSharpProjectContent(); var parsedFile = compilationUnit.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); project = project.AddAssemblyReferences(builtInLibs.Value); ICompilation compilation = project.CreateCompilation(); StoreInDictionaryNavigator navigator; if (csharpTreeView.SelectedNode != null) { navigator = new StoreInDictionaryNavigator((AstNode)csharpTreeView.SelectedNode.Tag); } else { navigator = new StoreInDictionaryNavigator(); } CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile); resolver.ApplyNavigator(navigator); csharpTreeView.BeginUpdate(); ShowResolveResultsInTree(csharpTreeView.Nodes, navigator); csharpTreeView.EndUpdate(); }
void SetUpWithCode(string code, int offset) { textEditor.Document.Text = code; textEditor.Caret.Offset = offset; var parseInfo = textEditor.CreateParseInformation(); IProject project = MockRepository.GenerateStrictMock <IProject>(); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock <IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled( i => { var p = new XamlParser(); p.TaskListTokens = TaskListTokens; i.ReturnValue = p.Parse(textEditor.FileName, textEditor.Document, true, project, CancellationToken.None); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock <IFileService>()); IViewContent view = MockRepository.GenerateStrictMock <IViewContent>(); view.Stub(v => v.GetService(typeof(ITextEditor))).Return(textEditor); SD.FileService.Stub(f => f.OpenFile(textEditor.FileName, false)).Return(view); }
public TestRefactoringContext(string content) { int idx = content.IndexOf("$"); if (idx >= 0) { content = content.Substring(0, idx) + content.Substring(idx + 1); } doc = new ReadOnlyDocument(content); var parser = new CSharpParser(); Unit = parser.Parse(content, "program.cs"); if (parser.HasErrors) { parser.ErrorPrinter.Errors.ForEach(e => Console.WriteLine(e.Message)); } Assert.IsFalse(parser.HasErrors, "File contains parsing errors."); parsedFile = Unit.ToTypeSystem(); IProjectContent pc = new CSharpProjectContent(); pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); compilation = pc.CreateCompilation(); resolver = new CSharpAstResolver(compilation, Unit, parsedFile); if (idx >= 0) { Location = doc.GetLocation(idx); } }
internal static IParameterDataProvider CreateProvider(string text) { string parsedText; string editorText; int cursorPosition = text.IndexOf('$'); int endPos = text.IndexOf('$', cursorPosition + 1); if (endPos == -1) { parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); } else { parsedText = text.Substring(0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring(endPos + 1); editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument(editorText); IProjectContent pctx = new CSharpProjectContent(); pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilationUnit = new CSharpParser().Parse(parsedText, "program.cs"); var parsedFile = compilationUnit.ToTypeSystem(); pctx = pctx.UpdateProjectContent(null, parsedFile); var cmp = pctx.CreateCompilation(); var loc = doc.GetLocation(cursorPosition); var engine = new CSharpParameterCompletionEngine(doc, new TestFactory(pctx)); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp)); var curDef = parsedFile.GetInnermostTypeDefinition(loc); if (curDef != null) { rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition()); var curMember = parsedFile.GetMember(loc); if (curMember != null) { rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx)); } } engine.ctx = rctx; engine.CSharpParsedFile = parsedFile; engine.ProjectContent = pctx; engine.Unit = compilationUnit; return(engine.GetParameterDataProvider(cursorPosition, doc.GetCharAt(cursorPosition - 1))); }
public static TestRefactoringContext Create(string content) { int idx = content.IndexOf("$"); if (idx >= 0) { content = content.Substring(0, idx) + content.Substring(idx + 1); } int idx1 = content.IndexOf("<-"); int idx2 = content.IndexOf("->"); int selectionStart = 0; int selectionEnd = 0; if (0 <= idx1 && idx1 < idx2) { content = content.Substring(0, idx2) + content.Substring(idx2 + 2); content = content.Substring(0, idx1) + content.Substring(idx1 + 2); selectionStart = idx1; selectionEnd = idx2 - 2; idx = selectionEnd; } var doc = new StringBuilderDocument(content); var parser = new CSharpParser(); var unit = parser.Parse(content, "program.cs"); if (parser.HasErrors) { parser.ErrorPrinter.Errors.ForEach(e => Console.WriteLine(e.Message)); } Assert.IsFalse(parser.HasErrors, "File contains parsing errors."); unit.Freeze(); var parsedFile = unit.ToTypeSystem(); IProjectContent pc = new CSharpProjectContent(); pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilation = pc.CreateCompilation(); var resolver = new CSharpAstResolver(compilation, unit, parsedFile); TextLocation location = TextLocation.Empty; if (idx >= 0) { location = doc.GetLocation(idx); } return(new TestRefactoringContext(doc, location, resolver) { selectionStart = selectionStart, selectionEnd = selectionEnd }); }
public void TestParseTypeName() { var result = IdStringProvider.ParseTypeName("T:System.Collections.Generic.List{T}"); Assert.IsNotNull(result); var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var type = result.Resolve(pc.CreateCompilation()); Assert.AreEqual("System.Collections.Generic.List", type.FullName); Assert.AreEqual(1, type.TypeParameterCount); }
public void ResolveTypeWithUnknownAttributes() { const String source = "namespace ns\r\n" + "{\r\n" + " public enum EE {v1 = 13, v2 = 666}\r\n" + " [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple = true)]\r\n" + " public class AttrA : System.Attribute\r\n" + " {\r\n" + " }\r\n" + " [System.AttributeUsage(System.AttributeTargets.Method)]\r\n" + " public class AttrB : System.Attribute\r\n" + " {\r\n" + " public AttrB(int i, string s, EE e) {}\r\n" + " }\r\n" + " public class SomeClass\r\n" + " {\r\n" + " [AttrA]\r\n" + " [AttrB(666, \"iddqd\", EE.v1)]\r\n" + " [AttrC]\r\n" + " public void M()\r\n" + " { }\r\n" + " }\r\n" + "}"; CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(source); syntaxTree.FileName = "example.cs"; CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem(); IProjectContent content = new CSharpProjectContent(); content = content.AddOrUpdateFiles(unresolvedTypeSystem); CecilLoader loader = new CecilLoader(); AssemblyDefinition mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location); IUnresolvedAssembly mscorlibAssembly = loader.LoadAssembly(mscorlibAssemblyDefinition); content = content.AddAssemblyReferences(mscorlibAssembly); ICompilation compilation = content.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree); MethodDeclaration method = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "M"); ResolveResult result = resolver.Resolve(method); MemberResolveResult memberResult = (MemberResolveResult)result; IMember member = memberResult.Member; foreach (IAttribute attribute in member.Attributes) { Console.WriteLine("attribute.AttributeType = {0}, attribute.AttributeType.Kind = {1}", attribute.AttributeType.FullName, attribute.AttributeType.Kind); Console.WriteLine("attribute.PositionalArguments.Count = {0}", attribute.PositionalArguments.Count); ProcessPositionalArgs(attribute.PositionalArguments); Console.WriteLine("attribute.NamedArguments.Count = {0}", attribute.NamedArguments.Count); Console.WriteLine(); } }
internal static StubbedRefactoringContext Create(SyntaxTree tree, bool supportsVersion5 = true) { IProjectContent pc = new CSharpProjectContent(); pc = pc.AddAssemblyReferences(CecilLoaderTests.Mscorlib); pc = pc.AddOrUpdateFiles(new[] { tree.ToTypeSystem() }); var compilation = pc.CreateCompilation(); var resolver = new CSharpAstResolver(compilation, tree); return(new StubbedRefactoringContext(resolver, supportsVersion5)); }
public virtual void Parse() { if (References.Where(t => t.IndexOf("mscorlib.dll", StringComparison.InvariantCultureIgnoreCase) >= 0).FirstOrDefault() == null) //Don't add mscorlib twice { string mscorlib = null; if (!String.IsNullOrEmpty(TargetFrameworkVersion)) { if (TargetFrameworkVersion == "v2.0" || TargetFrameworkVersion == "v3.0" || TargetFrameworkVersion == "v3.5") { mscorlib = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll"); } } if (mscorlib == null) { mscorlib = typeof(string).Assembly.Location; } References.Add(mscorlib); } NFiles = new List <NFile>(); CSharpParser = new CSharpParser(); if (Defines != null) { Defines.ForEach(t => CSharpParser.CompilerSettings.ConditionalSymbols.Add(t)); } NFiles = SourceFiles.Select(t => new NFile { Filename = t, Project = this }).ToList(); AssemblyReferences = References.Select(t => new NAssembly { Filename = t }).ToList(); //danel: parser.ErrorPrinter ParseCsFiles(); LoadAssemblies(); var ms = StopwatchHelper.TimeInMs(LoadAssemblies); FormatLine("{0} References End: {1}ms", AssemblyReferences.Count, ms); ProjectContent = new CSharpProjectContent(); ProjectContent = (CSharpProjectContent)ProjectContent.SetAssemblyName(AssemblyName); ProjectContent = (CSharpProjectContent)ProjectContent.AddAssemblyReferences(AssemblyReferences.Select(t => t.UnresolvedAssembly).Where(t => t != null)); ProjectContent = (CSharpProjectContent)ProjectContent.AddOrUpdateFiles(NFiles.Select(t => t.UnresolvedFile)); ProjectContent.Tag = this; ms = StopwatchHelper.TimeInMs(() => Compilation = ProjectContent.CreateCompilation()); Compilation.CacheManager.SetShared(typeof(NProject), this); FormatLine("CreateCompilation {0}ms", ms); //Navigator = CreateNavigator(null); //ApplyNavigator will happen BeforeExport only on needed files, in parallel }
private void FindReferencesButtonClick(object sender, EventArgs e) { if (csharpTreeView.SelectedNode == null) { return; } IProjectContent project = new CSharpProjectContent(); var unresolvedFile = _syntaxTree.ToTypeSystem(); project = project.AddOrUpdateFiles(unresolvedFile); project = project.AddAssemblyReferences(_builtInLibs.Value); ICompilation compilation = project.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, _syntaxTree, unresolvedFile); AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag; IEntity entity; MemberResolveResult mrr = resolver.Resolve(node) as MemberResolveResult; TypeResolveResult trr = resolver.Resolve(node) as TypeResolveResult; if (mrr != null) { entity = mrr.Member; } else if (trr != null) { entity = trr.Type.GetDefinition(); } else { return; } FindReferences fr = new FindReferences(); int referenceCount = 0; FoundReferenceCallback callback = delegate(AstNode matchNode, ResolveResult result) { Debug.WriteLine(matchNode.StartLocation + " - " + matchNode + " - " + result); referenceCount++; }; var searchScopes = fr.GetSearchScopes(entity); Debug.WriteLine("Find references to " + entity.ReflectionName); fr.FindReferencesInFile(searchScopes, unresolvedFile, _syntaxTree, compilation, callback, CancellationToken.None); MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName); }
protected string Process(IEnumerable <JsType> types, IScriptSharpMetadataImporter metadataImporter = null) { metadataImporter = metadataImporter ?? new MockScriptSharpMetadataImporter(); IProjectContent proj = new CSharpProjectContent(); proj = proj.AddAssemblyReferences(new[] { Common.Mscorlib }); var comp = proj.CreateCompilation(); var er = new MockErrorReporter(true); var obj = new OOPEmulator.ScriptSharpOOPEmulator(comp, metadataImporter, new MockRuntimeLibrary(), er); Assert.That(er.AllMessages, Is.Empty, "Should not have errors"); var rewritten = obj.Rewrite(types, comp); return(string.Join("", rewritten.Select(s => OutputFormatter.Format(s, allowIntermediates: true)))); }
void HandleClicked(object sender, EventArgs e) { var parser = new CSharpParser(); var unit = parser.Parse(textview1.Buffer.Text, "dummy.cs"); var unresolvedFile = unit.ToTypeSystem(); IProjectContent project = new CSharpProjectContent(); project = project.AddOrUpdateFiles(unresolvedFile); project = project.AddAssemblyReferences(builtInLibs.Value); CSharpAstResolver resolver = new CSharpAstResolver(project.CreateCompilation(), unit, unresolvedFile); ShowUnit(unit, resolver); }
private void Prepare(string source, IRuntimeLibrary runtimeLibrary = null, bool expectErrors = false, bool MinimizeNames = false) { IProjectContent project = new CSharpProjectContent(); var parser = new CSharpParser(); using (var rdr = new StringReader(source)) { var pf = new CSharpUnresolvedFile() { FileName = "File.cs" }; var syntaxTree = parser.Parse(rdr, pf.FileName); syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.AddOrUpdateFiles(pf); } project = project.AddAssemblyReferences(new[] { Files.Mscorlib, Files.Web, Files.Knockout }); _compilation = project.CreateCompilation(); var options = new CompilerOptions { MinimizeScript = MinimizeNames }; _errorReporter = new MockErrorReporter(!expectErrors); var s = new AttributeStore(_compilation, _errorReporter); s.RunAttributeCode(); _metadata = new MetadataImporter(_errorReporter, _compilation, s, options); _metadata.Prepare(_compilation.GetAllTypeDefinitions()); _allErrors = _errorReporter.AllMessages.ToList().AsReadOnly(); if (expectErrors) { Assert.That(_allErrors, Is.Not.Empty, "Compile should have generated errors"); } else { Assert.That(_allErrors, Is.Empty, "Compile should not generate errors"); } var rtl = new RuntimeLibrary(_metadata, _errorReporter, _compilation, new Namer(), s); }
private void TestCommonBody(String source) { CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(source); syntaxTree.FileName = "example.cs"; BaseReferenceExpression baseRef = syntaxTree.Descendants.OfType <BaseReferenceExpression>().First(); ExpressionStatement expr = MoveToParent <ExpressionStatement>(baseRef); CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem(); IProjectContent content = new CSharpProjectContent(); content = content.AddOrUpdateFiles(unresolvedTypeSystem); CecilLoader loader = new CecilLoader(); AssemblyDefinition mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location); IUnresolvedAssembly mscorlibAssembly = loader.LoadAssembly(mscorlibAssemblyDefinition); content = content.AddAssemblyReferences(mscorlibAssembly); ICompilation compilation = content.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree); ShowSubtree(expr, 0, resolver); }
static TestSemanticHighlightingVisitor CreateHighighting(string text) { var syntaxTree = SyntaxTree.Parse(text, "a.cs"); if (syntaxTree.Errors.Count > 0) { Console.WriteLine(text); Console.WriteLine("---"); syntaxTree.Errors.ForEach(err => Console.WriteLine(err.Message)); Assert.Fail("parse error."); } var project = new CSharpProjectContent().AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var file = syntaxTree.ToTypeSystem(); project = project.AddOrUpdateFiles(file); var resolver = new CSharpAstResolver(project.CreateCompilation(), syntaxTree, file); var result = new TestSemanticHighlightingVisitor(resolver); syntaxTree.AcceptVisitor(result); return(result); }
public TestRefactoringContext(string content) { int idx = content.IndexOf ("$"); if (idx >= 0) content = content.Substring (0, idx) + content.Substring (idx + 1); doc = new ReadOnlyDocument (content); var parser = new CSharpParser (); Unit = parser.Parse (content, "program.cs"); if (parser.HasErrors) parser.ErrorPrinter.Errors.ForEach (e => Console.WriteLine (e.Message)); Assert.IsFalse (parser.HasErrors, "File contains parsing errors."); parsedFile = Unit.ToTypeSystem(); IProjectContent pc = new CSharpProjectContent(); pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); compilation = pc.CreateCompilation(); resolver = new CSharpAstResolver(compilation, Unit, parsedFile); if (idx >= 0) Location = doc.GetLocation (idx); }
public void MethodParamsReturnAttributes() { const String source = "namespace ns\r\n" + "{\r\n" + " [System.AttributeUsage(System.AttributeTargets.Parameter)]\r\n" + " public class AttrA : System.Attribute\r\n" + " {\r\n" + " }\r\n" + " [System.AttributeUsage(System.AttributeTargets.ReturnValue)]\r\n" + " public class AttrB : System.Attribute\r\n" + " {\r\n" + " }\r\n" + " public class SomeClass\r\n" + " {\r\n" + " [return: AttrB]\r\n" + " public string SomeMethod(int p1, [AttrA]string p2) { return \"iddqd\"; }\r\n" + " }\r\n" + "}"; CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(source); syntaxTree.FileName = "example.cs"; CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem(); IProjectContent content = new CSharpProjectContent(); content = content.AddOrUpdateFiles(unresolvedTypeSystem); CecilLoader loader = new CecilLoader(); AssemblyDefinition mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location); IUnresolvedAssembly mscorlibAssembly = loader.LoadAssembly(mscorlibAssemblyDefinition); content = content.AddAssemblyReferences(mscorlibAssembly); ICompilation compilation = content.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree); MethodDeclaration method = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "SomeMethod"); ResolveResult result = resolver.Resolve(method); MemberResolveResult memberResult = (MemberResolveResult)result; IMember member = memberResult.Member; }
public void AnalyzeCSharpFile(string path) { mapper = new ClassMapper(); if (mappers == null) { mappers = new ArrayList(); } mappers.Add(mapper); mapper.filename = path; string filename = path; string sourceText = File.ReadAllText(filename); CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(sourceText, Path.GetFileNameWithoutExtension(filename)); var pc = new CSharpProjectContent(); pc = (CSharpProjectContent)pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()); ICompilation compilation = pc.CreateCompilation(); var resolver = new CSharpAstResolver(compilation, syntaxTree, syntaxTree.ToTypeSystem()); var classVisitor = new ClassVisitor(resolver); classVisitor.filename = path; classVisitor.b = b; classVisitor.wm = wm; classVisitor.mapper = mapper; classVisitor.syntax = syntaxTree; syntaxTree.AcceptVisitor(classVisitor); syntax = syntaxTree; }
public void SetUp() { SD.InitializeForUnitTests(); textEditor = new MockTextEditor(); textEditor.Document.Text = programStart + "override " + programEnd; textEditor.Caret.Offset = programStart.Length + "override ".Length; var parseInfo = textEditor.CreateParseInformation(); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock <IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled( i => { var syntaxTree = new CSharpParser().Parse(textEditor.Document, textEditor.FileName); i.ReturnValue = new CSharpFullParseInformation(syntaxTree.ToTypeSystem(), null, syntaxTree); }); CSharpCompletionBinding completion = new CSharpCompletionBinding(); keyPressResult = completion.HandleKeyPressed(textEditor, ' '); }
public static IEnumerable <ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time { var doc = new ReadOnlyDocument(editorText); var location = doc.GetLocation(offset); string parsedText = editorText; // TODO: Why are there different values in test cases? var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); var mb = new DefaultCompletionContextProvider(doc, unresolvedFile); IProjectContent pctx = new CSharpProjectContent(); var refs = new List <IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value }; pctx = pctx.AddAssemblyReferences(refs); pctx = pctx.AddOrUpdateFiles(unresolvedFile); var cmp = pctx.CreateCompilation(); var resolver3 = unresolvedFile.GetResolver(cmp, location); var engine = new CSharpCompletionEngine(doc, mb, new TestCompletionDataFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono(); var data = engine.GetCompletionData(offset, controlSpace: false); return(data); }
static int GetIndex(string text) { var editorText = new StringBuilder(); int trigger = 0, end = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == '@') { trigger = editorText.Length; continue; } if (text[i] == '$') { end = editorText.Length; continue; } editorText.Append(text [i]); } var doc = new ReadOnlyDocument(editorText.ToString ()); var pctx = new CSharpProjectContent(); var rctx = new CSharpTypeResolveContext(pctx.CreateCompilation().MainAssembly); var ctxProvider = new DefaultCompletionContextProvider(doc, new CSharpUnresolvedFile()); var engine = new CSharpParameterCompletionEngine(doc, ctxProvider, new ParameterCompletionTests.TestFactory(pctx), pctx, rctx); return engine.GetCurrentParameterIndex(trigger, end); }
Tuple<ReadOnlyDocument, CSharpCompletionEngine> GetContent (string text, CompilationUnit compilationUnit) { var doc = new ReadOnlyDocument (text); IProjectContent pctx = new CSharpProjectContent (); pctx = pctx.AddAssemblyReferences (new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var parsedFile = compilationUnit.ToTypeSystem (); pctx = pctx.UpdateProjectContent (null, parsedFile); var cmp = pctx.CreateCompilation (); var engine = new CSharpCompletionEngine (doc, new TestFactory (), pctx, new CSharpTypeResolveContext (cmp.MainAssembly), compilationUnit, parsedFile); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono (); return Tuple.Create (doc, engine); }
static CompletionDataList CreateProvider (string text, bool isCtrlSpace) { string parsedText; string editorText; int cursorPosition = text.IndexOf ('$'); int endPos = text.IndexOf ('$', cursorPosition + 1); if (endPos == -1) { parsedText = editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1); } else { parsedText = text.Substring (0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring (endPos + 1); editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring (endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument (editorText); IProjectContent pctx = new CSharpProjectContent (); pctx = pctx.AddAssemblyReferences (new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilationUnit = new CSharpParser ().Parse (parsedText, "program.cs"); compilationUnit.Freeze (); var parsedFile = compilationUnit.ToTypeSystem (); pctx = pctx.UpdateProjectContent (null, parsedFile); var cmp = pctx.CreateCompilation (); var loc = doc.GetLocation (cursorPosition); var rctx = new CSharpTypeResolveContext (cmp.MainAssembly); rctx = rctx.WithUsingScope (parsedFile.GetUsingScope (loc).Resolve (cmp)); var curDef = parsedFile.GetInnermostTypeDefinition (loc); if (curDef != null) { var resolvedDef = curDef.Resolve (rctx).GetDefinition (); rctx = rctx.WithCurrentTypeDefinition (resolvedDef); var curMember = resolvedDef.Members.FirstOrDefault (m => m.Region.Begin <= loc && loc < m.BodyRegion.End); if (curMember != null) rctx = rctx.WithCurrentMember (curMember); } var engine = new CSharpCompletionEngine (doc, new TestFactory (), pctx, rctx, compilationUnit, parsedFile); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono (); var data = engine.GetCompletionData (cursorPosition, isCtrlSpace); return new CompletionDataList () { Data = data, AutoCompleteEmptyMatch = engine.AutoCompleteEmptyMatch, AutoSelect = engine.AutoSelect, DefaultCompletionString = engine.DefaultCompletionString }; }
public static TestRefactoringContext Create (string content) { int idx = content.IndexOf ("$"); if (idx >= 0) content = content.Substring (0, idx) + content.Substring (idx + 1); int idx1 = content.IndexOf ("<-"); int idx2 = content.IndexOf ("->"); int selectionStart = 0; int selectionEnd = 0; if (0 <= idx1 && idx1 < idx2) { content = content.Substring (0, idx2) + content.Substring (idx2 + 2); content = content.Substring (0, idx1) + content.Substring (idx1 + 2); selectionStart = idx1; selectionEnd = idx2 - 2; idx = selectionEnd; } var doc = new StringBuilderDocument (content); var parser = new CSharpParser (); var unit = parser.Parse (content, "program.cs"); if (parser.HasErrors) parser.ErrorPrinter.Errors.ForEach (e => Console.WriteLine (e.Message)); Assert.IsFalse (parser.HasErrors, "File contains parsing errors."); unit.Freeze (); var parsedFile = unit.ToTypeSystem (); IProjectContent pc = new CSharpProjectContent (); pc = pc.UpdateProjectContent (null, parsedFile); pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilation = pc.CreateCompilation (); var resolver = new CSharpAstResolver (compilation, unit, parsedFile); TextLocation location = TextLocation.Empty; if (idx >= 0) location = doc.GetLocation (idx); return new TestRefactoringContext(doc, location, resolver) { selectionStart = selectionStart, selectionEnd = selectionEnd }; }
static Tuple<ReadOnlyDocument, CSharpCompletionEngine> GetContent(string text, SyntaxTree syntaxTree) { var doc = new ReadOnlyDocument(text); IProjectContent pctx = new CSharpProjectContent(); pctx = pctx.AddAssemblyReferences(new [] { mscorlib.Value, systemAssembly.Value, systemCore.Value, systemXmlLinq.Value }); var unresolvedFile = syntaxTree.ToTypeSystem(); pctx = pctx.AddOrUpdateFiles(unresolvedFile); var cmp = pctx.CreateCompilation(); var mb = new DefaultCompletionContextProvider(doc, unresolvedFile); var engine = new CSharpCompletionEngine (doc, mb, new TestFactory (new CSharpResolver (new CSharpTypeResolveContext (cmp.MainAssembly))), pctx, new CSharpTypeResolveContext (cmp.MainAssembly)); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono (); return Tuple.Create (doc, engine); }
internal static IParameterDataProvider CreateProvider (string text) { string parsedText; string editorText; int cursorPosition = text.IndexOf ('$'); int endPos = text.IndexOf ('$', cursorPosition + 1); if (endPos == -1) parsedText = editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1); else { parsedText = text.Substring (0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring (endPos + 1); editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring (endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument (editorText); IProjectContent pctx = new CSharpProjectContent (); pctx = pctx.AddAssemblyReferences (new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilationUnit = new CSharpParser ().Parse (parsedText, "program.cs"); var parsedFile = compilationUnit.ToTypeSystem (); pctx = pctx.UpdateProjectContent (null, parsedFile); var cmp = pctx.CreateCompilation (); var loc = doc.GetLocation (cursorPosition); var engine = new CSharpParameterCompletionEngine (doc, new TestFactory (pctx)); var rctx = new CSharpTypeResolveContext (cmp.MainAssembly); rctx = rctx.WithUsingScope (parsedFile.GetUsingScope (loc).Resolve (cmp)); var curDef = parsedFile.GetInnermostTypeDefinition (loc); if (curDef != null) { rctx = rctx.WithCurrentTypeDefinition (curDef.Resolve (rctx).GetDefinition ()); var curMember = parsedFile.GetMember (loc); if (curMember != null) rctx = rctx.WithCurrentMember (curMember.CreateResolved (rctx)); } engine.ctx = rctx; engine.CSharpParsedFile = parsedFile; engine.ProjectContent = pctx; engine.Unit = compilationUnit; return engine.GetParameterDataProvider (cursorPosition, doc.GetCharAt (cursorPosition - 1)); }
public static CSharpCompletionEngine CreateEngine(string text, out int cursorPosition, params IUnresolvedAssembly[] references) { string parsedText; string editorText; cursorPosition = text.IndexOf('$'); int endPos = text.IndexOf('$', cursorPosition + 1); if (endPos == -1) { if (cursorPosition < 0) { parsedText = editorText = text; } else { parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); } } else { parsedText = text.Substring(0, cursorPosition) + new string(' ', endPos - cursorPosition) + text.Substring(endPos + 1); editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument(editorText); IProjectContent pctx = new CSharpProjectContent(); var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value, systemXmlLinq.Value }; if (references != null) refs.AddRange (references); pctx = pctx.AddAssemblyReferences(refs); var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); pctx = pctx.AddOrUpdateFiles(unresolvedFile); var cmp = pctx.CreateCompilation(); var loc = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation (1, 1); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp)); var curDef = unresolvedFile.GetInnermostTypeDefinition(loc); if (curDef != null) { var resolvedDef = curDef.Resolve(rctx).GetDefinition(); rctx = rctx.WithCurrentTypeDefinition(resolvedDef); var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= loc && loc < m.BodyRegion.End); if (curMember != null) { rctx = rctx.WithCurrentMember(curMember); } } var mb = new DefaultCompletionContextProvider(doc, unresolvedFile); mb.AddSymbol ("TEST"); var engine = new CSharpCompletionEngine(doc, mb, new TestFactory(new CSharpResolver (rctx)), pctx, rctx); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono(); return engine; }
public static TestRefactoringContext Create(string content, bool expectErrors = false) { int idx = content.IndexOf ("$"); if (idx >= 0) content = content.Substring (0, idx) + content.Substring (idx + 1); int idx1 = content.IndexOf ("<-"); int idx2 = content.IndexOf ("->"); int selectionStart = 0; int selectionEnd = 0; if (0 <= idx1 && idx1 < idx2) { content = content.Substring (0, idx2) + content.Substring (idx2 + 2); content = content.Substring (0, idx1) + content.Substring (idx1 + 2); selectionStart = idx1; selectionEnd = idx2 - 2; idx = selectionEnd; } var doc = new StringBuilderDocument(content); var parser = new CSharpParser(); var unit = parser.Parse(content, "program.cs"); if (!expectErrors) { if (parser.HasErrors) { Console.WriteLine (content); Console.WriteLine ("----"); } foreach (var error in parser.Errors) { Console.WriteLine(error.Message); } Assert.IsFalse(parser.HasErrors, "The file contains unexpected parsing errors."); } else { Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file doesn't contain any."); } unit.Freeze (); var unresolvedFile = unit.ToTypeSystem (); IProjectContent pc = new CSharpProjectContent (); pc = pc.AddOrUpdateFiles (unresolvedFile); pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilation = pc.CreateCompilation (); var resolver = new CSharpAstResolver (compilation, unit, unresolvedFile); TextLocation location = TextLocation.Empty; if (idx >= 0) location = doc.GetLocation (idx); return new TestRefactoringContext(doc, location, resolver) { selectionStart = selectionStart, selectionEnd = selectionEnd }; }
// i'm not using this... public static CSharpCompletionEngine CreateEngine(string text, out int cursorPosition, params IUnresolvedAssembly[] references) { string parsedText; string editorText; cursorPosition = text.IndexOf('$'); int endPos = text.IndexOf('$', cursorPosition + 1); if (endPos == -1) { if (cursorPosition < 0) { parsedText = editorText = text; } else { parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); } } else { parsedText = text.Substring(0, cursorPosition) + new string(' ', endPos - cursorPosition) + text.Substring(endPos + 1); editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument(editorText); IProjectContent projContent = new CSharpProjectContent(); var refs = new List <IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value, systemXmlLinq.Value }; if (references != null) { refs.AddRange(references); } projContent = projContent.AddAssemblyReferences(refs); // Parse => SyntaxTree var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); // Add CSharpUnresolvedFile to CSharpProjectContent projContent = projContent.AddOrUpdateFiles(unresolvedFile); // Create a TypeSystem.ICompilation that allows resolving within the project. var compilation = projContent.CreateCompilation(); var textCursorLocation = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation(1, 1); #region Create and Refine the type resolution context as much as possible var typeResolveContext = new CSharpTypeResolveContext(compilation.MainAssembly); typeResolveContext = typeResolveContext.WithUsingScope(unresolvedFile.GetUsingScope(textCursorLocation).Resolve(compilation)); var curDef = unresolvedFile.GetInnermostTypeDefinition(textCursorLocation); if (curDef != null) { var resolvedDef = curDef.Resolve(typeResolveContext).GetDefinition(); typeResolveContext = typeResolveContext.WithCurrentTypeDefinition(resolvedDef); var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= textCursorLocation && textCursorLocation < m.BodyRegion.End); if (curMember != null) { typeResolveContext = typeResolveContext.WithCurrentMember(curMember); } } #endregion // Cool! Marry the concept of content & typed var completionContext = new DefaultCompletionContextProvider(doc, unresolvedFile); #region Add Preprocessor Symbols completionContext.AddSymbol("TEST"); foreach (var sym in syntaxTree.ConditionalSymbols) { completionContext.AddSymbol(sym); } #endregion var engine = new CSharpCompletionEngine(doc, completionContext, new TestCompletionDataFactory(new CSharpResolver(typeResolveContext)), projContent, typeResolveContext); engine.EolMarker = Environment.NewLine; engine.FormattingPolicy = FormattingOptionsFactory.CreateMono(); return(engine); }