private static CompilationUnit[] ExtractCompilationUnits(Project project) { using (var logger = LogManager.GetLogger("Test execution")) { var csharpTrees = new List <SyntaxTree>(project.CompileItems.Length); var visualBasicTrees = new List <SyntaxTree>(project.CompileItems.Length); foreach (var item in project.CompileItems) { if (!File.Exists(item)) { logger.Error($"File {item} doesn't exist"); continue; } var code = File.ReadAllText(item); if (Path.GetExtension(item).EqualsNoCase(".vb")) { visualBasicTrees.Add(VisualBasicSyntaxTree.ParseText(code, VisualBasicParseOptions.Default, item)); } else { // NOTE: currently is assumed that all this files is C# // TODO: fix it in the future csharpTrees.Add(CSharpSyntaxTree.ParseText(code, CSharpParseOptions.Default, item)); } } var references = new List <MetadataReference>(project.AssemblyReferences.Length + project.ProjectReferences.Length); foreach (var item in project.AssemblyReferences) { references.Add(MetadataReference.CreateFromFile(item)); } foreach (var item in project.ProjectReferences) { foreach (var unit in ExtractCompilationUnits(item)) { references.Add(unit.Compilation.ToMetadataReference()); } } var visualBasicOptions = new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, rootNamespace: project.RootNamespace, globalImports: project.Imports.Select(GlobalImport.Parse), optionCompareText: project.OptionCompare, optionExplicit: project.OptionExplicit, optionInfer: project.OptionInfer, optionStrict: project.OptionStrict ? OptionStrict.On : OptionStrict.Off); return(new CompilationUnit[] { CSharpCompilation.Create($"{project.ProjectName}_{LanguageNames.CSharp}") .AddSyntaxTrees(csharpTrees) .AddReferences(references), VisualBasicCompilation.Create($"{project.ProjectName}_{LanguageNames.VisualBasic}", options: visualBasicOptions) .AddSyntaxTrees(visualBasicTrees) .AddReferences(references) }); } }
public static T Run <T>(string code) { var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var tree = VisualBasicSyntaxTree.ParseText(PlaceCodeInsideBlock(code)); var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var comp = VisualBasicCompilation.Create("InMemoryAssembly") .WithOptions(options) .AddReferences(mscorlib) .AddSyntaxTrees(tree); using (var stream = new MemoryStream()) { var response = comp.Emit(stream); if (response.Success) { stream.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(stream.ToArray()); Type type = assembly.GetType("Container"); return((T)type.InvokeMember("Execute", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null)); } } return(default(T)); }
public static VisualBasicCompilation CreateVisualBasicCompilation(IEnumerable <MetadataReference> references, string rootNamespace = null) { var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithRootNamespace(rootNamespace) .WithGlobalImports(GlobalImport.Parse( "System", "System.Collections.Generic", "System.Diagnostics", "System.Globalization", "System.IO", "System.Linq", "System.Reflection", "System.Runtime.CompilerServices", "System.Security", "System.Text", "System.Threading.Tasks", "Microsoft.VisualBasic")) .WithOptionExplicit(true) .WithOptionCompareText(false) .WithOptionStrict(OptionStrict.Off) .WithOptionInfer(true); var compilation = VisualBasicCompilation.Create("Conversion", references: references) .WithOptions(compilationOptions); return(compilation); }
private static PortableExecutableReference GetInternalLibraryMetadataReference() { var syntaxTree = VisualBasicSyntaxTree.ParseText($@"Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo(""{TestProjectName}"")> Namespace ExternalNamespace Public Class InternalFoo Friend Overridable Function Bar() As Integer Return 1 End Function End Class End Namespace "); var references = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = VisualBasicCompilation.Create("Internal", new[] { syntaxTree }, references, compilationOptions); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success == false) { var errors = result.Diagnostics.Where(diag => diag.IsWarningAsError || diag.Severity == DiagnosticSeverity.Error); throw new InvalidOperationException($"Internal library compilation failed: {string.Join(",", errors)}"); } ms.Seek(0, SeekOrigin.Begin); return(MetadataReference.CreateFromStream(ms)); } }
/// <summary> /// Build script /// </summary> /// <param name="filenames">File names</param> /// <param name="references">References</param> /// <param name="releaseMode">Release mode (default=true)</param> /// <returns>Assembly</returns> public static Assembly CompileVBFile(string[] filenames, string[] references, bool releaseMode = true) { var tree = filenames.Select(u => VisualBasicSyntaxTree.ParseText(File.ReadAllText(u))).ToArray(); var op = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: releaseMode ? OptimizationLevel.Release : OptimizationLevel.Debug); return(Assembly.Create(VisualBasicCompilation.Create("SmartContract", tree, CreateReferences(references), op))); }
private static VisualBasicCompilation CreateVisualBasicCompilation() { VisualBasicCompilationOptions compilationOptions = CreateCompilationOptions(); return(VisualBasicCompilation.Create("Conversion") .WithOptions(compilationOptions)); }
public static VisualBasicCompilationOptions CreateCompilationOptions(string rootNamespace = null) { var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithGlobalImports(GlobalImport.Parse( "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Globalization", "System.IO", "System.Linq", "System.Reflection", "System.Runtime.CompilerServices", "System.Runtime.InteropServices", "System.Security", "System.Text", "System.Threading.Tasks", "System.Xml.Linq", "Microsoft.VisualBasic")) .WithOptionExplicit(true) .WithOptionCompareText(false) .WithOptionStrict(OptionStrict.Off) .WithOptionInfer(true) .WithRootNamespace(rootNamespace); return(compilationOptions); }
private static void VerifyAnalyzer(string snippit, OptionStrict optionStrict) { var project = SolutionBuilder.Create().AddProject(AnalyzerLanguage.VisualBasic).AddSnippet(snippit); var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict: optionStrict); var compilation = project.GetCompilation(null, options); DiagnosticVerifier.Verify(compilation, new OptionStrictOn(), CompilationErrorBehavior.Default); }
public void OptionExplicitOn_IsOffForProject() { var project = SolutionBuilder.Create().AddProject(AnalyzerLanguage.VisualBasic).AddSnippet("' Noncompliant ^1#0 {{Configure 'Option Explicit On' for assembly 'project0'.}}"); var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionExplicit: false); // optionExplicit is true by default => tested in other tests var compilation = project.GetCompilation(null, options); DiagnosticVerifier.Verify(compilation, new OptionExplicitOn(), CompilationErrorBehavior.Default); }
private VisualBasicCompilationFactory( string assemblyFileName, CompilationOptionsReader optionsReader, VisualBasicCompilationOptions compilationOptions ) : base(assemblyFileName, optionsReader) { CompilationOptions = compilationOptions; }
public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code) { SyntaxTree codeTree = VisualBasicSyntaxTree.ParseText(code); VisualBasicCompilationOptions options = new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, true, optimizationLevel: OptimizationLevel.Release, generalDiagnosticOption: ReportDiagnostic.Default); List <MetadataReference> references = new List <MetadataReference>(); foreach (string reference in cp.ReferencedAssemblies) { references.Add(GetReference(reference)); } AddExtraAssemblies(cp.ReferencedAssemblies, references); Compilation compilation = VisualBasicCompilation.Create( "_" + Guid.NewGuid().ToString("D"), new SyntaxTree[] { codeTree }, references: references, options: options.WithEmbedVbCoreRuntime(true) ); using (MemoryStream ms = new MemoryStream()) { EmitResult results = compilation.Emit(ms); if (results.Success) { return(new CompilerResults() { CompiledAssembly = Assembly.Load(ms.ToArray()) }); } else { CompilerResults result = new CompilerResults(); foreach (Diagnostic d in results.Diagnostics) { if (d.Severity == DiagnosticSeverity.Error) { result.Errors.Add(new CompilerError() { ErrorText = d.GetMessage(), ErrorNumber = d.Id, Line = d.Location.GetLineSpan().StartLinePosition.Line, Column = d.Location.GetLineSpan().StartLinePosition.Character }); } } return(result); } } }
public Compilation CreateLibraryCompilation(string assemblyName, bool optimizationsEnabled) { var options = new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: optimizationsEnabled ? OptimizationLevel.Release : OptimizationLevel.Debug ); return(VisualBasicCompilation.Create(assemblyName, options: options, references: _references)); }
public VisualBasicCodeVerificationOptions WithCompilationOptions(VisualBasicCompilationOptions compilationOptions) { return(new VisualBasicCodeVerificationOptions( parseOptions: ParseOptions, compilationOptions: compilationOptions, assemblyNames: AssemblyNames, allowedCompilerDiagnosticSeverity: AllowedCompilerDiagnosticSeverity, allowedCompilerDiagnosticIds: AllowedCompilerDiagnosticIds)); }
public VisualBasicCodeVerificationOptions WithCompilationOptions(VisualBasicCompilationOptions compilationOptions) { return(new VisualBasicCodeVerificationOptions( parseOptions: ParseOptions, compilationOptions: compilationOptions, allowNewCompilerDiagnostics: AllowNewCompilerDiagnostics, enableDiagnosticsDisabledByDefault: EnableDiagnosticsDisabledByDefault, maxAllowedCompilerDiagnosticSeverity: MaxAllowedCompilerDiagnosticSeverity, allowedCompilerDiagnosticIds: AllowedCompilerDiagnosticIds)); }
private static VisualBasicCompilation CreateCompilationWithMscorlib(string source, string assemblyName, IEnumerable<MetadataReference> references) { if (assemblyName == null) { assemblyName = TestBase.GetUniqueName(); } var tree = VisualBasicSyntaxTree.ParseText(source); var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimize: true); return VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, options); }
public VisualBasicCodeVerificationOptions( VisualBasicParseOptions parseOptions, VisualBasicCompilationOptions compilationOptions, IEnumerable <string> assemblyNames, DiagnosticSeverity allowedCompilerDiagnosticSeverity = DiagnosticSeverity.Info, IEnumerable <string> allowedCompilerDiagnosticIds = null) : base(assemblyNames, allowedCompilerDiagnosticSeverity, allowedCompilerDiagnosticIds) { ParseOptions = parseOptions ?? throw new ArgumentNullException(nameof(parseOptions)); CompilationOptions = compilationOptions ?? throw new ArgumentNullException(nameof(compilationOptions)); }
public Compilation CreateCompilationFromTree(SyntaxTree tree, IEnumerable <MetadataReference> references) { var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithRootNamespace("TestProject") .WithGlobalImports(GlobalImport.Parse("System", "System.Collections.Generic", "System.Linq", "Microsoft.VisualBasic")); var compilation = VisualBasicCompilation.Create("Conversion", new[] { tree }, references) .WithOptions(compilationOptions); return(compilation); }
public VisualBasicTestOptions( VisualBasicCompilationOptions compilationOptions = null, VisualBasicParseOptions parseOptions = null, IEnumerable <MetadataReference> metadataReferences = null, IEnumerable <string> allowedCompilerDiagnosticIds = null, DiagnosticSeverity allowedCompilerDiagnosticSeverity = DiagnosticSeverity.Info) : base(metadataReferences, allowedCompilerDiagnosticIds, allowedCompilerDiagnosticSeverity) { CompilationOptions = compilationOptions ?? new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); ParseOptions = parseOptions ?? VisualBasicParseOptions.Default; }
private static VisualBasicCompilation CreateCompilationWithMscorlib(string source, string assemblyName, IEnumerable <MetadataReference> references) { if (assemblyName == null) { assemblyName = TestBase.GetUniqueName(); } var tree = VisualBasicSyntaxTree.ParseText(source); var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release); return(VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, options)); }
internal static IEnumerable <ColorizedWord> ColorizeInternal(string code) { if (re.IsMatch(code)) { code = "__dummyfrom__=" + code; // because From is contextual } code = code.Replace("...", "___threedots___"); // because ... is unusually hard to parse var ref_mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); var ref_system = MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location); var ref_systemcore = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location); var ref_systemcollectionsimmutable = MetadataReference.CreateFromFile(typeof(ImmutableArray <>).GetTypeInfo().Assembly.Location); var parse_options = new VisualBasicParseOptions(kind: SourceCodeKind.Script); var compile_options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, globalImports: new[] { GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections"), GlobalImport.Parse("System.Collections.Generic") }); var compilationUnit = SyntaxFactory.ParseCompilationUnit(code, options: parse_options); var syntaxTree = compilationUnit.SyntaxTree; var compilation = VisualBasicCompilation.Create("dummyAssemblyName", new[] { syntaxTree }, new[] { ref_mscorlib, ref_system, ref_systemcore, ref_systemcollectionsimmutable }, compile_options); var semanticModel = compilation.GetSemanticModel(syntaxTree, true); var w = new VBColorizingWalker() { sm = semanticModel }; w.Visit(syntaxTree.GetRoot()); // var suppressNextEquals = false; foreach (var word in w.Words) { if (word == null) { yield return(word); } else if (word.Text == "___threedots___") { yield return new ColorizedWord { Text = "..." } } ; else if (word.Text == "__dummyfrom__") { suppressNextEquals = true; continue; } else if (word.Text == "=" && suppressNextEquals) { } else { word.Text = word.Text.Replace("___threedots___", "...").Replace("__dummyfrom__", ""); yield return(word); } } }
public VisualBasicCodeVerificationOptions( VisualBasicParseOptions parseOptions = null, VisualBasicCompilationOptions compilationOptions = null, bool allowNewCompilerDiagnostics = false, bool enableDiagnosticsDisabledByDefault = true, DiagnosticSeverity maxAllowedCompilerDiagnosticSeverity = DiagnosticSeverity.Info, IEnumerable <string> allowedCompilerDiagnosticIds = null) : base(parseOptions, compilationOptions, allowNewCompilerDiagnostics, enableDiagnosticsDisabledByDefault, maxAllowedCompilerDiagnosticSeverity, allowedCompilerDiagnosticIds) { ParseOptions = parseOptions; CompilationOptions = compilationOptions; }
private static VisualBasicTestOptions CreateDefault() { VisualBasicParseOptions parseOptions = VisualBasicParseOptions.Default; var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); return(new VisualBasicTestOptions( compilationOptions: compilationOptions, parseOptions: parseOptions, metadataReferences: RuntimeMetadataReference.DefaultMetadataReferences.Select(f => f.Value).ToImmutableArray(), allowedCompilerDiagnosticIds: null, allowedCompilerDiagnosticSeverity: DiagnosticSeverity.Info)); }
protected override EmitResult Compile(MetadataReference[] references, MemoryStream ms, List <SourceFile> sourceFiles) { VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); IEnumerable <SyntaxTree> syntaxTrees = sourceFiles.Where(x => x.FileName.EndsWith(".vb")) .Select(x => SyntaxFactory.ParseSyntaxTree(x.SourceCode)); VisualBasicCompilation compilation = VisualBasicCompilation.Create("implementation.dll") .WithOptions(options) .AddSyntaxTrees(syntaxTrees) .AddReferences(references); return(compilation.Emit(ms)); }
public ConverterTestBase(string rootNamespace = null) { _rootNamespace = rootNamespace; var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptionExplicit(true) .WithOptionCompareText(false) .WithOptionStrict(OptionStrict.Off) .WithOptionInfer(true); EmptyNamespaceOptionStrictOff = new TextConversionOptions(DefaultReferences.NetStandard2) { RootNamespaceOverride = string.Empty, TargetCompilationOptionsOverride = options, ShowCompilationErrors = true }; }
public CSToVBProjectContentsConverter(ConversionOptions conversionOptions) { var vbCompilationOptions = (VisualBasicCompilationOptions)conversionOptions.TargetCompilationOptionsOverride ?? VisualBasicCompiler.CreateCompilationOptions(conversionOptions.RootNamespaceOverride); if (conversionOptions.RootNamespaceOverride != null) { vbCompilationOptions = vbCompilationOptions.WithRootNamespace(conversionOptions.RootNamespaceOverride); } _vbCompilationOptions = vbCompilationOptions; _vbParseOptions = VisualBasicParseOptions.Default; RootNamespace = conversionOptions.RootNamespaceOverride; }
public CSToVBProjectContentsConverter(ConversionOptions conversionOptions, IProgress <ConversionProgress> progress, CancellationToken cancellationToken) { _progress = progress; _cancellationToken = cancellationToken; var vbCompilationOptions = (VisualBasicCompilationOptions)conversionOptions.TargetCompilationOptionsOverride ?? VisualBasicCompiler.CreateCompilationOptions(conversionOptions.RootNamespaceOverride); if (conversionOptions.RootNamespaceOverride != null) { vbCompilationOptions = vbCompilationOptions.WithRootNamespace(conversionOptions.RootNamespaceOverride); } _vbCompilationOptions = vbCompilationOptions; _vbParseOptions = VisualBasicCompiler.ParseOptions; RootNamespace = conversionOptions.RootNamespaceOverride; }
public static VisualBasicCompilation CreateCompilation( IEnumerable <SyntaxTree> trees, IEnumerable <MetadataReference> references = null, VisualBasicCompilationOptions compOptions = null, string assemblyName = "") { if (compOptions == null) { compOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, "a.dll"); } return(VisualBasicCompilation.Create( string.IsNullOrEmpty(assemblyName) ? GetUniqueName() : assemblyName, trees, references, compOptions)); }
internal override Compilation Compile(string className, string generatedCode, string codeBehind, PortableExecutableReference[] references) { var syntaxTrees = new List <SyntaxTree> { VisualBasicSyntaxTree.ParseText(generatedCode) }; if (!string.IsNullOrEmpty(codeBehind)) { syntaxTrees.Add(CSharpSyntaxTree.ParseText(codeBehind)); } var x = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); return(VisualBasicCompilation.Create($"{className}_{Guid.NewGuid():D}.dll", syntaxTrees, references, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, false, null, null, "Script", null, null, OptionStrict.Off, true, true, false, null, false, OptimizationLevel.Release))); }
public static VisualBasicCompilation CreateCompilationWithMscorlib( IEnumerable <SyntaxTree> source, IEnumerable <MetadataReference> references = null, VisualBasicCompilationOptions compOptions = null, string assemblyName = "") { var refs = new List <MetadataReference>(); if (references != null) { refs.AddRange(references); } refs.AddRange(DefaultMetadataReferences); return(CreateCompilation(source, refs, compOptions, assemblyName)); }
public override Project AddProject(Solution solution) { Project project = base.AddProject(solution); var compilationOptions = (VisualBasicCompilationOptions)project.CompilationOptions; VisualBasicCompilationOptions newCompilationOptions = compilationOptions .WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var parseOptions = (VisualBasicParseOptions)project.ParseOptions; VisualBasicParseOptions newParseOptions = parseOptions .WithLanguageVersion(LanguageVersion.Latest); return(project .WithCompilationOptions(newCompilationOptions) .WithParseOptions(newParseOptions)); }
/// <summary> /// Compiles a Visual Basic source code file. /// </summary> /// <param name="sourceCodeFilePath">Path to the source code file.</param> /// <param name="assemblyFilePath">Path to the destination compiled file.</param> /// <returns>Result of the compilation.</returns> static EmitResult CompileVisualBasic(string sourceCodeFilePath, string assemblyFilePath) { string assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath); MetadataReference [] references = GetAssemblyReferences(); VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); SyntaxTree [] syntaxTree; using (Stream stream = File.OpenRead(sourceCodeFilePath)) { syntaxTree = new SyntaxTree [] { VisualBasicSyntaxTree.ParseText(SourceText.From(stream)) }; } VisualBasicCompilation compilation = VisualBasicCompilation.Create(assemblyName, syntaxTree, references, options); using (Stream output = File.Create(assemblyFilePath)) { return(compilation.Emit(output)); } }
private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement) { var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace; var globalImports = new List<GlobalImport>(); var reportDiagnostic = ReportDiagnostic.Default; if (compilationOptionsElement != null) { globalImports = compilationOptionsElement.Elements(GlobalImportElementName) .Select(x => GlobalImport.Parse(x.Value)).ToList(); var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName); if (rootNamespaceAttribute != null) { rootNamespace = rootNamespaceAttribute.Value; } var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName); if (reportDiagnosticAttribute != null) { reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute); } var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName); if (outputTypeAttribute != null && outputTypeAttribute.Value == "WindowsRuntimeMetadata") { if (rootNamespaceAttribute == null) { rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace; } return language == LanguageNames.CSharp ? (CompilationOptions)new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata) : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace); } } else { // Add some common global imports by default for VB globalImports.Add(GlobalImport.Parse("System")); globalImports.Add(GlobalImport.Parse("System.Collections.Generic")); globalImports.Add(GlobalImport.Parse("System.Linq")); } // TODO: Allow these to be specified. var languageServices = workspace.Services.GetLanguageServices(language); var metadataService = workspace.Services.GetService<IMetadataService>(); var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithGeneralDiagnosticOption(reportDiagnostic) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, null))) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (language == LanguageNames.VisualBasic) { compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace) .WithGlobalImports(globalImports); } return compilationOptions; }
// Gets the semantic model and caches it // TODO: Write tests to check getting a semantic model against all the different query types - make sure the diagnostics generated are appropriate private SemanticModel GetSemanticModel() { if (!_generatedSemanticModel) { // Generate the semantic model Compilation compilation = null; if (_syntaxTree is CSharpSyntaxTree) { CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); compilation = CSharpCompilation.Create("QueryCompilation").WithOptions(options); } else if (_syntaxTree is VisualBasicSyntaxTree) { VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); compilation = VisualBasicCompilation.Create("QueryCompilation").WithOptions(options); } if (compilation != null) { // Get assembly references from the current AppDomain (which will be the domain of the currently running query) // Make sure to exclude empty locations (created by in-memory assemblies, specifically AsyncBridge) // See http://stackoverflow.com/questions/28503569/roslyn-create-metadatareference-from-in-memory-assembly AppDomain appDomain = AppDomain.CurrentDomain; compilation = compilation .AddReferences(appDomain.GetAssemblies() .Where(x => !x.IsDynamic && !string.IsNullOrEmpty(x.Location)) .Select(MetadataReference.CreateFromAssembly)) .AddSyntaxTrees(_syntaxTree); _semanticModel = compilation.GetSemanticModel(_syntaxTree); } _generatedSemanticModel = true; // Update the UI _semanticsCheckBox.Checked = true; _semanticsCheckBox.Enabled = false; } return _semanticModel; }
void VBWorkspaceSetup(out CSharpDiagnosticTestBase.TestWorkspace workspace, out Document doc, VisualBasicParseOptions parseOptions = null) { workspace = new CSharpDiagnosticTestBase.TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); if (parseOptions == null) { parseOptions = new VisualBasicParseOptions( Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14, DocumentationMode.Diagnose | DocumentationMode.Parse, SourceCodeKind.Regular ); } workspace.Options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, false); var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithRootNamespace("TestProject") .WithGlobalImports(GlobalImport.Parse("System", "System.Collections.Generic", "System.Linq", "Microsoft.VisualBasic")); workspace.Open(ProjectInfo.Create( projectId, VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.VisualBasic, null, null, compilationOptions, parseOptions, new[] { DocumentInfo.Create( documentId, "a.vb", null, SourceCodeKind.Regular ) }, null, DiagnosticTestBase.DefaultMetadataReferences ) ); doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId); }