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(); }
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)); }
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 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); }
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 void GenerateTypeSystem() { IProjectContent pc = new CSharpProjectContent(); CSharpParser parser = new CSharpParser(); parser.GenerateTypeSystemMode = true; foreach (string fileName in fileNames) { CompilationUnit cu; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) { cu = parser.Parse(fs, fileName); } var parsedFile = cu.ToTypeSystem(); foreach (var td in parsedFile.GetAllTypeDefinitions()) { Assert.AreSame(parsedFile, td.ParsedFile); foreach (var member in td.Members) { Assert.AreSame(parsedFile, member.ParsedFile); Assert.AreSame(td, member.DeclaringTypeDefinition); } } pc = pc.UpdateProjectContent(null, parsedFile); } }
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); }
public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles) { var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); return(pc.CreateCompilation()); }
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 GenerateTypeSystem() { IProjectContent pc = new CSharpProjectContent(); CSharpParser parser = new CSharpParser(); parser.GenerateTypeSystemMode = true; foreach (string fileName in fileNames) { SyntaxTree syntaxTree; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) { syntaxTree = parser.Parse(fs, fileName); } var unresolvedFile = syntaxTree.ToTypeSystem(); foreach (var td in unresolvedFile.GetAllTypeDefinitions()) { Assert.AreSame(unresolvedFile, td.UnresolvedFile); foreach (var member in td.Members) { Assert.AreSame(unresolvedFile, member.UnresolvedFile); Assert.AreSame(td, member.DeclaringTypeDefinition); } } pc = pc.AddOrUpdateFiles(unresolvedFile); } }
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 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 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)); }
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(); }
IEntity Lookup(string cref) { string program = @"using System; using System.Collections.Generic; /// <summary/> class Test { int @int; void M(int a) {} void Overloaded(int a) {} void Overloaded(string a) {} void Overloaded(ref int a) {} public int this[int index] { get { return 0; } } public static int operator +(Test a, int b) { return 0; } public static implicit operator Test(int a) { return 0; } public static implicit operator int(Test a) { return 0; } } interface IGeneric<A, B> { void Test<T>(ref T[,] a); } class Impl<T> : IGeneric<List<string>[,], T> { void IGeneric<List<string>[,], T>.Test<X>(ref X[,] a) {} }"; var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var syntaxTree = SyntaxTree.Parse(program, "program.cs"); var compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation(); var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.First(); IEntity entity = typeDefinition.Documentation.ResolveCref(cref); Assert.IsNotNull(entity, "ResolveCref() returned null."); return(entity); }
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); }
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); }
void Init(string program) { var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var syntaxTree = SyntaxTree.Parse(program, "program.cs"); compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); }
void Init(string program) { var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var cu = new CSharpParser().Parse(new StringReader(program), "program.cs"); compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); }
public Project(IFileSystem fileSystem, Logger logger) { _fileSystem = fileSystem; _logger = logger; Files = new List <CSharpFile> (); References = new List <IAssemblyReference>(); ProjectContent = new CSharpProjectContent(); }
private IProjectContent CreateCSharpProjectContent(string fileName) { IProjectContent pc = new CSharpProjectContent(); pc = pc.SetAssemblyName(AssemblyName); pc = pc.SetProjectFileName(fileName); pc = pc.SetCompilerSettings(CompilerSettings); return(pc); }
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; }
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 }); }
// Token: 0x06000021 RID: 33 RVA: 0x0000291C File Offset: 0x00000B1C private IProjectContent GetCSharpProjectContent(VSProject vsproject) { IProjectContent projectContent = new CSharpProjectContent(); Properties properties = vsproject.Project.ConfigurationManager.ActiveConfiguration.Properties; string fullName = vsproject.Project.FullName; projectContent = projectContent.SetAssemblyName(vsproject.Project.Properties.Item("AssemblyName").Value.ToString()); projectContent = projectContent.SetProjectFileName(Path.GetFileName(fullName)); projectContent = projectContent.SetLocation(fullName); return(projectContent.SetCompilerSettings(this.GetCompilerSettingsFromVSProject(vsproject))); }
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 void AnErrorIsIssuedIfTheMainMethodHasParameters() { var er = new MockErrorReporter(); var invoker = new OOPEmulatorInvoker(new MockOOPEmulator(), new MockMetadataImporter(), er); var cu = new CSharpParser().Parse(@"class MyClass { public void Main(string[] args) { } }", "file.cs").ToTypeSystem(); var compilation = new CSharpProjectContent().AddOrUpdateFiles(new IUnresolvedFile[] { cu }).AddAssemblyReferences(new[] { MinimalCorlib.Instance }).CreateCompilation(); var typeResolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); invoker.Process(cu.GetAllTypeDefinitions().Select(t => new JsClass(t.Resolve(typeResolveContext).GetDefinition())).ToList <JsType>(), compilation.FindType(new FullTypeName("MyClass")).GetMethods().Single(m => m.Name == "Main")); Assert.That(er.AllMessages, Has.Count.EqualTo(1)); Assert.That(er.AllMessages.Any(m => m.Code == 7800 && (string)m.Args[0] == "MyClass.Main")); }
public void AssemblyAndModuleAttributesDoNotAppearOnTypes() { var parser = new CSharpParser(); var cu = parser.Parse("[assembly: My1][module: My2][My3]class C {} public class My1Attribute : System.Attribute {} public class My2Attribute : System.Attribute {} public class My3Attribute : System.Attribute {}", "File.cs"); var ts = cu.ToTypeSystem(); var compilation = new CSharpProjectContent() .UpdateProjectContent(null, ts) .AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }) .CreateCompilation(); var type = ReflectionHelper.ParseReflectionName("C").Resolve(compilation).GetDefinition(); Assert.That(type.Attributes.Select(a => a.AttributeType.FullName).ToList(), Is.EqualTo(new[] { "My3Attribute" })); }
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); }
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); }
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 }; }
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 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); }
internal CSharpAssembly(ICompilation compilation, CSharpProjectContent projectContent) { this.compilation = compilation; this.projectContent = projectContent; this.context = new SimpleTypeResolveContext(this); }
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); }
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 }; }
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; }