public void EndToEndCompileAndRun() { var expression = "6 * 7"; var text = @"public class Calculator { public static object Evaluate() { return $; } }".Replace("$", expression); var tree = SyntaxFactory.ParseSyntaxTree(text); var compilation = CSharpCompilation.Create( "calc.dll", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }); Assembly compiledAssembly; using (var stream = new MemoryStream()) { var compileResult = compilation.Emit(stream); compiledAssembly = Assembly.Load(stream.GetBuffer()); } Type calculator = compiledAssembly.GetType("Calculator"); MethodInfo evaluate = calculator.GetMethod("Evaluate"); string answer = evaluate.Invoke(null, null).ToString(); Assert.AreEqual("42", answer); }
public TestCode(string textWithMarker) { // $ marks the position in source code. It's better than passing a manually calculated // int, and is just for test convenience. $ is a char that is used nowhere in the C# // language. Position = textWithMarker.IndexOf('$'); if (Position != -1) { textWithMarker = textWithMarker.Remove(Position, 1); } Text = textWithMarker; SyntaxTree = SyntaxFactory.ParseSyntaxTree(Text); if (Position != -1) { Token = SyntaxTree.GetRoot().FindToken(Position); SyntaxNode = Token.Parent; } Compilation = CSharpCompilation .Create("test") .AddSyntaxTrees(SyntaxTree) .AddReferences(MetadataReference.CreateFromAssembly(typeof(object).Assembly)); SemanticModel = Compilation.GetSemanticModel(SyntaxTree); }
public void Write(TextWriter writer, bool declarations) { var references = _referencePaths.Select(p => MetadataReference.CreateFromFile(p)) .Concat(new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }) .ToArray(); var syntaxTrees = _inputs.Select(input => CSharpSyntaxTree.ParseText(input, CSharpParseOptions.Default)).ToArray(); var compilation = CSharpCompilation.Create("Test", syntaxTrees, references); foreach (var tree in syntaxTrees) { var model = compilation.GetSemanticModel(tree); var collector = new TypeCollector(); collector.Visit(tree.GetRoot()); var emitter = new TypeScriptEmitter(writer, model, declarations); foreach (var type in collector.Types) { emitter.Emit(type); } foreach (var e in collector.Enums) { emitter.Emit(e); } } }
public static IBob Compile(string text) { CSharpCompilation compilation = CSharpCompilation.Create(Path.GetRandomFileName()) .AddSyntaxTrees(CSharpSyntaxTree.ParseText(text)) .AddReferences(MetadataReference.CreateFromAssembly(Assembly.GetAssembly(typeof(Console)), MetadataReferenceProperties.Assembly)) .AddReferences(MetadataReference.CreateFromAssembly(typeof(Runner).Assembly)) .WithOptions(new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary)); foreach (Diagnostic diagnose in compilation.GetDiagnostics()) { Console.WriteLine(diagnose); } using (MemoryStream stream = new MemoryStream()) { compilation.Emit(stream); Assembly assembly = Assembly.Load(stream.ToArray()); foreach (Type type in assembly.GetTypes()) { if (typeof(IBob).IsAssignableFrom(type)) { return((IBob)Activator.CreateInstance(type)); } } } return(null); }
public static OmnisharpWorkspace AddProjectToWorkspace(OmnisharpWorkspace workspace, string filePath, string[] frameworks, Dictionary <string, string> sourceFiles) { var versionStamp = VersionStamp.Create(); var mscorlib = MetadataReference.CreateFromAssembly(AssemblyFromType(typeof(object))); var systemCore = MetadataReference.CreateFromAssembly(AssemblyFromType(typeof(Enumerable))); var references = new[] { mscorlib, systemCore }; foreach (var framework in frameworks) { var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), versionStamp, "OmniSharp+" + framework, "AssemblyName", LanguageNames.CSharp, filePath, metadataReferences: references); workspace.AddProject(projectInfo); foreach (var file in sourceFiles) { var document = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), file.Key, null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(file.Value), versionStamp)), file.Key); workspace.AddDocument(document); } } return(workspace); }
/// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> protected ImmutableArray <MetadataReference> GetReferencesForCompilation() { var references = _options.References; if (this.GlobalsType != null) { var globalsTypeAssembly = MetadataReference.CreateFromAssembly(this.GlobalsType.Assembly); if (!references.Contains(globalsTypeAssembly)) { references = references.Add(globalsTypeAssembly); } } if (_previous == null) { return(references); } else { // TODO (tomat): RESOLVED? bound imports should be reused from previous submission instead of passing // them to every submission in the chain. See bug #7802. var compilation = _previous.GetCompilation(); return(ImmutableArray.CreateRange(references.Union(compilation.References))); } }
public IEnumerable <Diagnostic> GetErrors(Compilation compilation, SemanticModel model, out Compilation result) { IEnumerable <Diagnostic> errors = null; result = compilation; try { errors = model.GetDiagnostics(); } catch { //td: revise this on newer versions of Roslyn //old diagnostics or nodes seems to linger on after being replaced var tree = model.SyntaxTree; var root = model.SyntaxTree.GetRoot().NormalizeWhitespace(); var linkerNodes = root.GetAnnotatedNodes(Compiler.LinkerAnnotationId); string currVersion = root.ToFullString(); root = SyntaxFactory.ParseCompilationUnit(currVersion); foreach (var linkNode in linkerNodes) { SyntaxNode rn = root.FindNode(linkNode.Span); if (rn != null) { var annotation = linkNode.GetAnnotations(Compiler.LinkerAnnotationId).First(); root = root.ReplaceNode(rn, rn.WithAdditionalAnnotations(annotation)); } } var trees = new List <SyntaxTree>(); foreach (var tt in result.SyntaxTrees) { if (tt == tree) { trees.Add(root.SyntaxTree); } else { trees.Add(tt); } } result = CSharpCompilation.Create(result.AssemblyName, syntaxTrees: trees, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly), MetadataReference.CreateFromAssembly(typeof(Enumerable).Assembly), MetadataReference.CreateFromAssembly(typeof(Dictionary <int, int>).Assembly), }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); model = result.GetSemanticModel(root.SyntaxTree); errors = model.GetDiagnostics(); } return(errors); }
public void Compile(string code, Stream peStream, Stream pdbStream) { var tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("temp", new[] { tree }, new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.Emit(peStream, pdbStream); peStream.Seek(0, SeekOrigin.Begin); }
protected override IEnumerable <MetadataReference> GetSolutionMetadataReferences() { foreach (MetadataReference reference in base.GetSolutionMetadataReferences()) { yield return(reference); } yield return(MetadataReference.CreateFromAssembly(typeof(ImportAttribute).Assembly)); }
static void Main(string[] args) { var greeting = "Hello World!" + 5; // Let's self-inspect this program and find out the type of 'greeting' var sourcePath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", // debug "..", // bin "Program.cs"); // Get the syntax tree from this source file var syntaxTree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourcePath)); // Run the compiler and get the semantic model var semanticModel = CSharpCompilation.Create("selfInspection") .AddSyntaxTrees(syntaxTree) .AddReferences( // Add reference to mscorlib MetadataReference.CreateFromAssembly(typeof(object).Assembly)) .GetSemanticModel(syntaxTree); // Look for variable declarator of 'greeting' var varNode = syntaxTree.GetRoot() .DescendantNodes() .OfType <LocalDeclarationStatementSyntax>() .Select(d => d.Declaration) .First(d => d.ChildNodes() .OfType <VariableDeclaratorSyntax>() .First() .Identifier .ValueText == "greeting") .Type; // Get the semantic information for variable declarator and print its type var semanticInfo = semanticModel.GetTypeInfo(varNode); Console.WriteLine(semanticInfo.Type.Name); // Here is an alternative: Find symbol by name based on cursor position // Find span of body of main method var mainStart = syntaxTree.GetRoot() .DescendantNodes() .OfType <MethodDeclarationSyntax>() .Single(m => m.Identifier.ValueText == "Main") .ChildNodes() .OfType <BlockSyntax>() .Single() .Span .Start; // Look for symbol 'greeting' based on location inside source var symbol = semanticModel .LookupSymbols(mainStart, name: "greeting") .First() as ILocalSymbol; Console.WriteLine(symbol.Type.Name); }
static void Main(string[] args) { // ATTENTION: This program is just for demo purposes. It is // easy to inject code. Add proper checks in practice. const string expressionShell = @"public class Calculator { public static object Evaluate() { return $; } }" ; while (true) { // Ask user for a C# expression Console.WriteLine("Please enter an expression:"); var expression = Console.ReadLine(); // Dynamically generate source code var dynamicCode = expressionShell.Replace("$", expression); // Parse and compile the source code var tree = SyntaxFactory.ParseSyntaxTree(dynamicCode); var compilation = CSharpCompilation.Create( "calc.dll", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }); // Check for errors var diagnostics = compilation.GetDiagnostics(); if (diagnostics.Count() > 0) { foreach (var diagnostic in diagnostics) { Console.WriteLine(diagnostic.GetMessage()); } } else { // Emit assembly in-memory (no DLL is generated on disk) Assembly compiledAssembly; using (var stream = new MemoryStream()) { var compileResult = compilation.Emit(stream); compiledAssembly = Assembly.Load(stream.GetBuffer()); } // Dynamically call method and print result var calculator = compiledAssembly.GetType("Calculator"); var evaluate = calculator.GetMethod("Evaluate"); Console.WriteLine(evaluate.Invoke(null, null).ToString()); } } }
public void TestWriteOnlyStream() { var tree = CSharpSyntaxTree.ParseText("class Program { static void Main() { } }"); var compilation = CSharpCompilation.Create("Program", new[] { tree }, new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithFeatures((new[] { "deterministic" }).AsImmutable())); var output = new WriteOnlyStream(); compilation.Emit(output); }
protected static Solution CreateSolution(params string[] code) { return(CreateSolution( new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly), MetadataReference.CreateFromAssembly(typeof(Debug).Assembly) }, code)); }
public static Solution GetSolutionFromText(string text) { using (var workspace = new AdhocWorkspace()) { return(workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(object).Assembly)) .AddDocument("foo.cs", text) .Project .Solution); } }
public void CreateFromAssembly() { var assembly = typeof(object).Assembly; var r = (PortableExecutableReference)MetadataReference.CreateFromAssembly(assembly); Assert.Equal(assembly.Location, r.FilePath); Assert.Equal(assembly.Location, r.Display); Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind); Assert.False(r.Properties.EmbedInteropTypes); Assert.True(r.Properties.Aliases.IsDefault); }
public IEnumerable <Diagnostic> GetErrors(Compilation compilation, out Compilation result, Dictionary <SyntaxTree, SyntaxTree> track = null) { //td: !!! fix IEnumerable <Diagnostic> errors = null; result = compilation; try { errors = result.GetDiagnostics(); } catch { //td: !!! recompile before first compilation, dont work var trees = new List <SyntaxTree>(); foreach (var tree in compilation.SyntaxTrees) { var root = tree.GetRoot().NormalizeWhitespace(); var linkerNodes = root.GetAnnotatedNodes(Compiler.LinkerAnnotationId); string currVersion = root.ToFullString(); root = SyntaxFactory.ParseCompilationUnit(currVersion); foreach (var linkNode in linkerNodes) { SyntaxNode rn = root.FindNode(linkNode.Span); if (rn != null) { var annotation = linkNode.GetAnnotations(Compiler.LinkerAnnotationId).First(); root = root.ReplaceNode(rn, rn.WithAdditionalAnnotations(annotation)); } } if (track != null) { track[tree] = root.SyntaxTree; } trees.Add(root.SyntaxTree); } result = CSharpCompilation.Create(result.AssemblyName, syntaxTrees: trees, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly), MetadataReference.CreateFromAssembly(typeof(Enumerable).Assembly), }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); errors = result.GetDiagnostics(); } return(errors); }
public void CreateFromAssembly_WithPropertiesAndDocumentation() { var doc = new TestDocumentationProvider(); var assembly = typeof(object).Assembly; var r = (PortableExecutableReference)MetadataReference.CreateFromAssembly(assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true), documentation: doc); Assert.Equal(assembly.Location, r.FilePath); Assert.Equal(assembly.Location, r.Display); Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind); Assert.True(r.Properties.EmbedInteropTypes); AssertEx.Equal(ImmutableArray.Create("a", "b"), r.Properties.Aliases); Assert.Same(doc, r.DocumentationProvider); }
public async Task WhenClassContainsEmptyFinalizerThenReturnsError(string code) { var references = new[] { MetadataReference.CreateFromAssembly(typeof(IAvailability).Assembly), MetadataReference.CreateFromAssembly(typeof(object).Assembly), MetadataReference.CreateFromAssembly(typeof(Debug).Assembly) }; var solution = CreateSolution(references, code); var results = await _inspector.Inspect(solution); CollectionAssert.IsNotEmpty(results); }
private IRoot LoadFromInternal(SyntaxTree tree, string filePath) { //corporation.CheckContainer(); var compilation = CSharpCompilation.Create("MyCompilation", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }); var model = compilation.GetSemanticModel(tree); var root = corporation.Create(tree.GetCompilationUnitRoot(), null, model).FirstOrDefault() as IRoot; //var root = corporation.CreateFrom<IRoot>(tree.GetCompilationUnitRoot(), null, model).FirstOrDefault(); root.FilePath = filePath; return(root); }
public TestHostProject( TestWorkspace workspace, string name = null, string language = null, CompilationOptions compilationOptions = null, ParseOptions parseOptions = null, IEnumerable <TestHostDocument> documents = null, IEnumerable <TestHostDocument> additionalDocuments = null, IEnumerable <TestHostProject> projectReferences = null, IEnumerable <MetadataReference> metadataReferences = null, IEnumerable <AnalyzerReference> analyzerReferences = null, string assemblyName = null) { _name = name ?? "TestProject"; _id = ProjectId.CreateNewId(debugName: this.Name); language = language ?? LanguageNames.CSharp; _languageServices = workspace.Services.GetLanguageServices(language); _compilationOptions = compilationOptions ?? this.LanguageServiceProvider.GetService <ICompilationFactoryService>().GetDefaultCompilationOptions(); _parseOptions = parseOptions ?? this.LanguageServiceProvider.GetService <ISyntaxTreeFactoryService>().GetDefaultParseOptions(); this.Documents = documents ?? SpecializedCollections.EmptyEnumerable <TestHostDocument>(); this.AdditionalDocuments = additionalDocuments ?? SpecializedCollections.EmptyEnumerable <TestHostDocument>(); _projectReferences = projectReferences != null?projectReferences.Select(p => new ProjectReference(p.Id)) : SpecializedCollections.EmptyEnumerable <ProjectReference>(); _metadataReferences = metadataReferences ?? new MetadataReference[] { MetadataReference.CreateFromAssembly(typeof(int).Assembly) }; _analyzerReferences = analyzerReferences ?? SpecializedCollections.EmptyEnumerable <AnalyzerReference>(); _assemblyName = assemblyName ?? "TestProject"; _version = VersionStamp.Create(); _outputFilePath = GetTestOutputFilePath(_filePath); if (documents != null) { foreach (var doc in documents) { doc.SetProject(this); } } if (additionalDocuments != null) { foreach (var doc in additionalDocuments) { doc.SetProject(this); } } }
private AssemblyNeutralWorker DoAssemblyNeutralCompilation(params string[] fileContents) { var compilation = CSharpCompilation.Create("test", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), references: new[] { MetadataReference.CreateFromAssembly(typeof(object).GetTypeInfo().Assembly) }, syntaxTrees: fileContents.Select(text => CSharpSyntaxTree.ParseText(text))); var worker = new AssemblyNeutralWorker(compilation, new Dictionary <string, MetadataReference>()); worker.FindTypeCompilations(compilation.GlobalNamespace); worker.OrderTypeCompilations(); return(worker); }
public void CA2214SpecialInheritanceCSharp() { var source = @" class C : System.Web.UI.Control { C() { // no diagnostics because we inherit from System.Web.UI.Control Foo(); OnLoad(null); } protected abstract Foo(); } class D : System.Windows.Forms.Control { D() { // no diagnostics because we inherit from System.Web.UI.Control Foo(); OnPaint(null); } protected abstract Foo(); } class ControlBase : System.Windows.Forms.Control { } class E : ControlBase { E() { OnLoad(null); // no diagnostics when we're not an immediate descendant of a special class } } "; var document = CreateDocument(source, LanguageNames.CSharp); var project = document.Project.AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(System.Web.UI.Control).Assembly)); project = project.AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(System.Windows.Forms.Control).Assembly)); var analyzer = GetCSharpDiagnosticAnalyzer(); GetSortedDiagnostics(analyzer, project.Documents.Single()).Verify(analyzer); }
public static Solution GetSolutionFromFiles(params string[] filePaths) { using (var workspace = new AdhocWorkspace()) { var project = workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(object).Assembly)); foreach (var filePath in filePaths) { var file = new FileInfo(filePath); var document = project.AddDocument(file.Name, File.ReadAllText(file.FullName, Encoding.UTF8)); project = document.Project; } return(project.Solution); } }
public static CSharpCompilation ToCompilationUnit(Expression e) { //TODO: dump with all namespaces to prevent name clash var tree = CSharpSyntaxTree.ParseText(ExpressionToCodeLib.ExpressionToCode.ToCode(e)); //TODO: grab all references from Expression tree var ref1 = MetadataReference.CreateFromAssembly(typeof(object).Assembly); var ref2 = MetadataReference.CreateFromAssembly(typeof(Func <>).Assembly); var compilation = CSharpCompilation.Create("ExpressionsConverter.ToCompilationUnit", new List <SyntaxTree> { tree }, new List <MetadataReference> { ref1, ref2 }); return(compilation); }
public void CreateFrom_Errors() { Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromImage(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromImage(default(ImmutableArray <byte>))); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromFile(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromFile(null, default(MetadataReferenceProperties))); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromStream(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromAssembly(null)); Assert.Throws <ArgumentException>(() => MetadataReference.CreateFromAssembly(typeof(object).Assembly, new MetadataReferenceProperties(MetadataImageKind.Module))); var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Foo" }, System.Reflection.Emit.AssemblyBuilderAccess.Run); Assert.Throws <NotSupportedException>(() => MetadataReference.CreateFromAssembly(dynamicAssembly)); }
public CompletionProvider(ScriptCs.ScriptServices service, ICSharpCode.AvalonEdit.Document.TextDocument text) { _simp = new SimpleCompletionProvider(service, text); var currentPath = Assembly.GetExecutingAssembly().Location; currentPath = Path.GetDirectoryName(currentPath); var f1 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.Features.dll"); var f2 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.CSharp.Features"); var f3 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.Workspaces.Desktop"); if (!File.Exists(f1)) { File.WriteAllBytes(f1, Resources.Microsoft_CodeAnalysis_Features); } if (!File.Exists(f2)) { File.WriteAllBytes(f2, Resources.Microsoft_CodeAnalysis_CSharp_Features); } if (!File.Exists(f3)) { File.WriteAllBytes(f3, Resources.Microsoft_CodeAnalysis_Workspaces_Desktop); } _host = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(new[] { Assembly.LoadFrom(f1), Assembly.LoadFrom(f2) })); _ws = new InteractiveWorkspace(_host); _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Interactive); _references = _assemblyTypes.Select(t => MetadataReference.CreateFromAssembly(t.Assembly)).ToArray(); _compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: _assemblyTypes.Select(x => x.Namespace).ToImmutableArray()); var container = new CompositionContainer(new AssemblyCatalog(typeof(ISignatureHelpProvider).Assembly), CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); _signatureHelpProviders = container.GetExportedValues <ISignatureHelpProvider>().ToArray(); }
public CodeGenTests() { var workspace = new CustomWorkspace(); var project = workspace.CurrentSolution.AddProject("test", "test", "C#") .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(string).Assembly)) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(GenerateImmutableAttribute).Assembly)) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(CodeGenerationAttribute).Assembly)) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(Optional).Assembly)) .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(ImmutableArray).Assembly)) .AddMetadataReference(MetadataReference.CreateFromAssembly(Assembly.LoadWithPartialName("System.Runtime"))); var inputDocument = project.AddDocument("input.cs", string.Empty); this.inputDocumentId = inputDocument.Id; project = inputDocument.Project; this.projectId = inputDocument.Project.Id; this.solution = project.Solution; }
private async Task <IMethodSymbol> GetMethodSymbolAsync(string file, string name) { var code = File.ReadAllText(file); var tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create( Guid.NewGuid().ToString("N"), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly), }); var model = compilation.GetSemanticModel(tree); var root = await tree.GetRootAsync().ConfigureAwait(false); return(model.GetDeclaredSymbol(IMethodSymbolExtensionsTests.FindMethodDeclaration(root, name))); }
private void CreateProxy(string svcutil, string wsdlUri, string outFilePath, string ns) { Console.WriteLine("SvcUtil {0}", svcutil); Console.WriteLine("WSDL {0}", wsdlUri); Console.WriteLine("Code file {0}", outFilePath); Console.WriteLine("Code file namespace {0}", ns); Console.WriteLine(); Console.WriteLine("Processing WSDL {0}", wsdlUri); // 1. generate raw code var csFilePath = Path.GetTempFileName() + ".cs"; GenerateRawCode(svcutil, wsdlUri, csFilePath); Console.WriteLine("Raw file: {0}", csFilePath); // 2. create syntax tree and semantic tree SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(csFilePath)); var mscorlib = MetadataReference.CreateFromAssembly(typeof(object).Assembly); var serialization = MetadataReference.CreateFromAssembly(typeof(ServiceContractAttribute).Assembly); var serializer = MetadataReference.CreateFromAssembly(typeof(XmlEnumAttribute).Assembly); var compilation = CSharpCompilation.Create("ServiceReference", new[] { syntaxTree }, new[] { mscorlib, serialization, serializer }); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); // 3. Parse trees Console.WriteLine("Gathering info..."); var metadata = ParseTree(root, semanticModel); // 4. Generate source code Console.WriteLine("Code generation..."); var newRoot = GenerateCode(metadata, ns); MSBuildWorkspace workspace = MSBuildWorkspace.Create(); var res = Formatter.Format(newRoot, workspace); File.WriteAllText(outFilePath, res.ToFullString()); Console.WriteLine("DONE!"); Console.WriteLine(); }
public void VBBackingFields_DebuggerBrowsable() { string source = @" Imports System Class C Public WithEvents WE As C Public Event E As Action Public Property A As Integer End Class "; var compilation = VB.VisualBasicCompilation.Create( "foo", new[] { VB.VisualBasicSyntaxTree.ParseText(source) }, new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }, new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug)); Assembly a; using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); a = Assembly.Load(stream.ToArray()); } var c = a.GetType("C"); var obj = Activator.CreateInstance(c); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "C", "A: 0", "WE: null" ); var attrsA = c.GetField("_A", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsWE = c.GetField("_WE", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsE = c.GetField("EEvent", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); Assert.Equal(1, attrsA.Length); Assert.Equal(1, attrsWE.Length); Assert.Equal(1, attrsE.Length); }