public CSharpProject(Solution solution, string title, string fileName) { // Normalize the file name fileName = Path.GetFullPath(fileName); this.Solution = solution; this.Title = title; this.FileName = fileName; // Use MSBuild to open the .csproj var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName); // Figure out some compiler settings this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName"); this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false; this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false; string defineConstants = msbuildProject.GetPropertyValue("DefineConstants"); foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); } // Initialize the unresolved type system IProjectContent pc = new CSharpProjectContent(); pc = pc.SetAssemblyName(this.AssemblyName); pc = pc.SetProjectFileName(fileName); pc = pc.SetCompilerSettings(this.CompilerSettings); // Parse the C# code files foreach (var item in msbuildProject.GetItems("Compile")) { var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude)); Files.Add(file); } // Add parsed files to the type system pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile)); // Add referenced assemblies: foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) { IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile); pc = pc.AddAssemblyReferences(new [] { assembly }); } // Add project references: foreach (var item in msbuildProject.GetItems("ProjectReference")) { string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude); // Normalize the path; this is required to match the name with the referenced project's file name referencedFileName = Path.GetFullPath(referencedFileName); pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) }); } this.ProjectContent = pc; }
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(); }
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); }
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)); }
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 MemberCollectorTests() { _memberCollector = new CollectAllMembers.MemberCollector(); #region Initialize _compilation var referencedAssemblies = new Type[] { typeof(System.Exception), typeof(ICollection), typeof(IList <>) } .Select(t => t.Assembly.Location); IProjectContent dummyProject = new CSharpProjectContent(); dummyProject = dummyProject.AddAssemblyReferences( referencedAssemblies .Distinct() .Select( a => new CecilLoader().LoadAssemblyFile(a))); _compilation = new DefaultSolutionSnapshot(new [] { dummyProject }) .GetCompilation(dummyProject); #endregion }
public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles) { var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); return(pc.CreateCompilation()); }
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); }
public void ResetProject(Tuple <string, string>[] sourceFiles = null, params string[] assemblies) { Project = null; if (sourceFiles == null) { sourceFiles = new Tuple <string, string> [0]; //will happen only during the testing } var projectContents = new IUnresolvedAssembly[assemblies.Length]; Parallel.For(0, assemblies.Length, i => { projectContents[i] = new CecilLoader { DocumentationProvider = GetXmlDocumentation(assemblies[i]) }.LoadAssemblyFile(assemblies[i]); }); var unresolvedAsms = builtInLibs.Value.Concat(projectContents); var unresolvedFiles = new IUnresolvedFile[sourceFiles.Length]; Parallel.For(0, unresolvedFiles.Length, i => { var pair = sourceFiles[i]; var syntaxTree = new CSharpParser().Parse(pair.Item1, pair.Item2); syntaxTree.Freeze(); unresolvedFiles[i] = syntaxTree.ToTypeSystem(); }); IProjectContent project = new CSharpProjectContent(); project = project.AddAssemblyReferences(unresolvedAsms); project = project.AddOrUpdateFiles(unresolvedFiles); Project = project; }
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 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); }
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); }
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); }
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 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); }
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 void CreateCompilation (string parsedText, out IProjectContent pctx, out SyntaxTree syntaxTree, out CSharpUnresolvedFile unresolvedFile, bool expectErrors, params IUnresolvedAssembly[] references) { 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); syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); syntaxTree.Freeze(); if (!expectErrors && syntaxTree.Errors.Count > 0) { Console.WriteLine ("----"); Console.WriteLine (parsedText); Console.WriteLine ("----"); foreach (var error in syntaxTree.Errors) Console.WriteLine (error.Message); Assert.Fail ("Parse error."); } unresolvedFile = syntaxTree.ToTypeSystem(); pctx = pctx.AddOrUpdateFiles(unresolvedFile); }
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 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 void Main(string[] args) { // Parse options. string jasminJar = null; string outputJar = null; bool noConfig; string target; string debugLevel; bool debug; bool optimize; string define; List <string> reference = new List <string>(); string warnLevel; List <string> files; var options = new OptionSet() { { "jasmin=", "Path to Jasmin JAR", x => jasminJar = x }, { "out=", "The resulting JAR to create", x => outputJar = x }, { "noconfig", "", x => noConfig = true }, { "target=", "", x => target = x }, { "debug", "", x => debugLevel = x }, { "debug+", "", x => debug = true }, { "optimize+", "", x => optimize = true }, { "debug-", "", x => debug = false }, { "optimize-", "", x => optimize = false }, { "define", "", x => define = x }, { "reference:", "", reference.Add }, { "warn", "", x => warnLevel = x }, }; try { files = options.Parse(args); if (files.Count == 1 && files[0][0] == '@') { // Read command line from file. using (var reader = new StreamReader(files[0].Substring(1))) { //Console.WriteLine(reader.ReadToEnd()); files = options.Parse(reader.ReadToEnd().Split(' ')); } } } catch (OptionException ex) { Console.Write("cscjvm: "); Console.WriteLine(ex.Message); Console.WriteLine("Try `cscjvm --help' for more information."); return; } if (string.IsNullOrWhiteSpace(jasminJar)) { Console.WriteLine("Defaulting Jasmin JAR path to JASMIN_JAR environment variable."); jasminJar = Environment.GetEnvironmentVariable("JASMIN_JAR"); if (string.IsNullOrWhiteSpace(jasminJar)) { Console.WriteLine("Jasmin JAR path must be set."); return; } } Console.WriteLine("C# to JVM Compiler"); Console.WriteLine("Using Jasmin at: " + jasminJar); foreach (var arg in args) { Console.WriteLine("argument: " + arg); } IProjectContent project = new CSharpProjectContent(); var trees = new List <SyntaxTree>(); Console.WriteLine("Parsing C# files..."); var parser = new CSharpParser(); foreach (var filename in files) { using (var reader = new StreamReader(filename)) { trees.Add(parser.Parse(reader.ReadToEnd(), filename)); } } Console.WriteLine("Creating references..."); project = project.AddAssemblyReferences(GetProjectReferences(reference)); foreach (var tree in trees) { project = project.AddOrUpdateFiles(tree.ToTypeSystem()); } Console.WriteLine("Emitting Jasmin assembly..."); var output = new DirectoryInfo(Environment.CurrentDirectory).CreateSubdirectory("obj"); var sources = new List <string>(); string entryPoint = null; foreach (var tree in trees) { var unresolvedFile = tree.ToTypeSystem(); ICompilation compilation = project.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, tree, unresolvedFile); var typeVisitor = new JavaTypeVisitor(resolver, output); tree.AcceptVisitor(typeVisitor); sources.AddRange(typeVisitor.CreatedFiles); if (typeVisitor.EntryPoint != null) { entryPoint = typeVisitor.EntryPoint; } } if (entryPoint == null) { Console.WriteLine("No class with [EntryPoint] attribute. This JAR will be a library."); } Console.WriteLine("Compiling JAR..."); var jasmin = new Jasmin(jasminJar); using (var writer = new StreamWriter(outputJar)) { jasmin.CompileJar(output.FullName, sources, writer.BaseStream, entryPoint); } Console.WriteLine("Wrote JAR to " + outputJar); }
// 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); }
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 static TestRefactoringContext Create(List <string> contents, int mainIndex, bool expectErrors = false) { List <int> indexes = new List <int>(); List <int> selectionStarts = new List <int>(); List <int> selectionEnds = new List <int>(); List <IDocument> documents = new List <IDocument>(); List <CSharpUnresolvedFile> unresolvedFiles = new List <CSharpUnresolvedFile>(); List <SyntaxTree> units = new List <SyntaxTree>(); for (int i = 0; i < contents.Count; i++) { string content = contents[i]; 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; } indexes.Add(idx); selectionStarts.Add(selectionStart); selectionEnds.Add(selectionEnd); var doc = new StringBuilderDocument(content); var parser = new CSharpParser(); var unit = parser.Parse(content, "program_" + i + ".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 " + i + " contains unexpected parsing errors."); } else { Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any."); } unit.Freeze(); CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem(); units.Add(unit); documents.Add(doc); unresolvedFiles.Add(unresolvedFile); } IProjectContent pc = new CSharpProjectContent(); pc = pc.AddOrUpdateFiles(unresolvedFiles); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilation = pc.CreateCompilation(); List <TestRefactoringContext> contexts = new List <TestRefactoringContext>(); for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex) { var doc = documents [documentIndex]; var resolver = new CSharpAstResolver(compilation, units[documentIndex], unresolvedFiles[documentIndex]); TextLocation location = TextLocation.Empty; if (indexes[documentIndex] >= 0) { location = doc.GetLocation(indexes[documentIndex]); } var context = new TestRefactoringContext(doc, location, resolver) { selectionStart = selectionStarts[documentIndex], selectionEnd = selectionEnds[documentIndex], projectContexts = contexts }; contexts.Add(context); } return(contexts [mainIndex]); }
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 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 }; }