private static Compilation CreateCompilation(
            string source,
            string language,
            string rootNamespace
            )
        {
            string fileName    = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb";
            string projectName = "TestProject";
            var    references  = s_references.Value;

            var syntaxTree =
                language == LanguageNames.CSharp
                    ? CSharpSyntaxTree.ParseText(source, path: fileName)
                    : VisualBasicSyntaxTree.ParseText(source, path: fileName);

            if (language == LanguageNames.CSharp)
            {
                return(CSharpCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree, },
                           references: references
                           ));
            }
            else
            {
                return(VisualBasicCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree },
                           references: references,
                           options: new VisualBasicCompilationOptions(
                               OutputKind.DynamicallyLinkedLibrary,
                               rootNamespace: rootNamespace
                               )
                           ));
            }
        }
示例#2
0
        public void Execute_ShouldWarnOnNonCSharCompilation()
        {
            Compilation compilation = VisualBasicCompilation.Create
                                      (
                "cica",
                new[]
            {
                VisualBasicSyntaxTree.ParseText
                (
                    @"
                        Imports System.Collections

                        Imports Solti.Utils.Proxy
                        Imports Solti.Utils.Proxy.Attributes
                        Imports Solti.Utils.Proxy.Generators

                        <Assembly:EmbedGeneratedType(GetType(DuckGenerator(Of IEnumerable, IEnumerable)))>
                        "
                )
            },
                Runtime
                .Assemblies
                .Select(asm => asm.Location)
                .Append(typeof(EmbedGeneratedTypeAttribute).Assembly.Location)
                .Distinct()
                .Select(location => MetadataReference.CreateFromFile(location)),
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                      );

            GeneratorDriver driver = CSharpGeneratorDriver.Create(new ProxyEmbedder());

            driver.RunGeneratorsAndUpdateCompilation(compilation, out compilation, out ImmutableArray <Diagnostic> diags);

            Assert.That(diags.Any(diag => diag.Id == "PGE00" && diag.Severity == DiagnosticSeverity.Warning && diag.GetMessage() == SGResources.LNG_NOT_SUPPORTED));
            Assert.That(diags.Length, Is.EqualTo(1));
        }
示例#3
0
        public void CanBeReferencedByName()
        {
            var vbText = @"
Public Interface I
    Property P(x As Integer)
End Interface
";
            var vbcomp = VisualBasicCompilation.Create(
                "Test",
                new[] { VisualBasicSyntaxTree.ParseText(vbText) },
                new[] { MscorlibRef_v4_0_30316_17626 },
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var ref1 = vbcomp.EmitToImageReference(embedInteropTypes: true);

            var text = @"class C : I {}";
            var tree = Parse(text);
            var comp = CreateEmptyCompilation(new[] { tree }, new[] { ref1 });

            var t = comp.GetTypeByMetadataName("I");

            Assert.Empty(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Method && !x.CanBeReferencedByName));
            Assert.False(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Property).First().CanBeReferencedByName); //there's only one.
        }
示例#4
0
        public static async Task <SyntaxNode> ConvertCompilationTree(Document document,
                                                                     VisualBasicCompilation vbViewOfCsSymbols, Project vbReferenceProject)
        {
            document = await document.WithExpandedRootAsync();

            var compilation = await document.Project.GetCompilationAsync();

            var tree = await document.GetSyntaxTreeAsync();

            var semanticModel = compilation.GetSemanticModel(tree, true);
            var root          = await document.GetSyntaxRootAsync() as CSS.CompilationUnitSyntax ??
                                throw new InvalidOperationException(NullRootError(document));

            var vbSyntaxGenerator = SyntaxGenerator.GetGenerator(vbReferenceProject);
            var numberOfLines     = tree.GetLineSpan(root.FullSpan).EndLinePosition.Line;

            var visualBasicSyntaxVisitor = new NodesVisitor(document, (CS.CSharpCompilation)compilation, semanticModel, vbViewOfCsSymbols, vbSyntaxGenerator, numberOfLines);
            var converted = root.Accept(visualBasicSyntaxVisitor.TriviaConvertingVisitor);

            var formattedConverted = (VBSyntax.CompilationUnitSyntax)Formatter.Format(converted, document.Project.Solution.Workspace);


            return(LineTriviaMapper.MapSourceTriviaToTarget(root, formattedConverted));
        }
        public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code)
        {
            CodeAnalysis.SyntaxTree       codeTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code);
            VisualBasicCompilationOptions options  = new VisualBasicCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                true,
                optimizationLevel: OptimizationLevel.Release,
                generalDiagnosticOption: ReportDiagnostic.Error);

            List <MetadataReference> references = new List <MetadataReference>();


            foreach (string reference in cp.ReferencedAssemblies)
            {
                references.Add(GetReference(reference));
            }

            if (!cp.ReferencedAssemblies.Contains("netstandard"))
            {
                references.Add(GetReference("netstandard"));
            }

            if (!cp.ReferencedAssemblies.Contains("System.Runtime"))
            {
                references.Add(GetReference("System.Runtime"));
            }

            if (!cp.ReferencedAssemblies.Contains("System.ComponentModel.Primitives"))
            {
                references.Add(GetReference("System.ComponentModel.Primitives"));
            }


            Compilation compilation = VisualBasicCompilation.Create(
                "_" + Guid.NewGuid().ToString("D"), new SyntaxTree[] { codeTree },
                references: references, options: options
                );



            using (MemoryStream ms = new MemoryStream())
            {
                CodeAnalysis.Emit.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 CreateCompilationFromTree(SyntaxTree tree, IEnumerable <MetadataReference> references)
        {
            VisualBasicCompilation withReferences = CreateVisualBasicCompilation(references, _rootNamespace);

            return(withReferences.AddSyntaxTrees(tree));
        }
示例#7
0
 public static VisualBasicCompilation VerifyVisualBasicAnalyzerDiagnostics(this VisualBasicCompilation c, DiagnosticAnalyzer[] analyzers, AnalyzerOptions options = null, Func <Exception, DiagnosticAnalyzer, bool> continueOnAnalyzerException = null, params DiagnosticDescription[] expected)
 {
     return(VerifyAnalyzerDiagnostics(c, n => n.VisualBasicKind(), analyzers, options, expected, continueOnAnalyzerException));
 }
        private void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            var completionDataList = new List <QueryCompletionData>();

            if (e.Text == ".")
            {
                //字符串不需要代码提示
                var txt = textEditor.Text.Trim();
                if ((txt.StartsWith("\"") || txt.StartsWith("“") || txt.StartsWith("”")) &&
                    (txt.EndsWith("\"") || txt.EndsWith("“") || txt.EndsWith("”")))
                {
                    return;
                }

                try
                {
                    var importsNamespace = "";//导入命名空间以实现省略命名空间的功能
                    foreach (var ns in ImportedNamespaces)
                    {
                        importsNamespace += string.Format("Imports {0}", ns);
                        importsNamespace += Environment.NewLine;
                    }
                    var startString = importsNamespace + @"
Module Module1

    Sub Main()
        Dim _tmp_ =";


                    var    endString  = @" 
    End Sub

End Module
";
                    string codeString = startString + textEditor.Text.Substring(0, textEditor.CaretOffset) + endString;

                    var tree = VisualBasicSyntaxTree.ParseText(codeString);

                    var root = tree.GetRoot();

                    //TODO WJF 动态加载组件后,此处运行是否还正常?

                    Assembly        target     = Assembly.GetExecutingAssembly();
                    List <Assembly> references = (from assemblyName in target.GetReferencedAssemblies()
                                                  select Assembly.Load(assemblyName)).ToList();

                    var CustomIntellisense = VisualBasicCompilation.Create("CustomIntellisense");

                    foreach (var assembly in references)
                    {
                        CustomIntellisense = CustomIntellisense.AddReferences(MetadataReference.CreateFromFile(assembly.Location));
                    }

                    CustomIntellisense = CustomIntellisense.AddSyntaxTrees(tree);

                    var model = CustomIntellisense.GetSemanticModel(tree);

                    var exprSyntaxNode     = root.FindToken(codeString.LastIndexOf('.') - 1).Parent;
                    var exprFullNameString = exprSyntaxNode.Parent.ToString().Trim();
                    if (exprFullNameString.EndsWith("."))
                    {
                        exprFullNameString = exprFullNameString.Substring(0, exprFullNameString.Length - 1);
                    }

                    List <ExpressionNode> rootNodes =
                        ExpressionNode.SubsetAutoCompletionList(m_namespaceNodeRoot, exprFullNameString);

                    foreach (var item in rootNodes)
                    {
                        foreach (var child_item in item.Nodes)
                        {
                            if (child_item.ItemType == "namespace")
                            {
                                completionDataList.Add(new QueryCompletionData(child_item.Name, child_item.Description, SymbolKind.Namespace));
                            }
                            else if (child_item.ItemType == "class")
                            {
                                completionDataList.Add(new QueryCompletionData(child_item.Name, child_item.Description, SymbolKind.NamedType));
                            }
                            else
                            {
                                //TODO WJF后期根据需要添加
                            }
                        }
                    }

                    var literalInfo      = model.GetTypeInfo(exprSyntaxNode);
                    var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type;

                    IList <ISymbol> symbols = new List <ISymbol>()
                    {
                    };
                    foreach (var s in (from method in stringTypeSymbol.GetMembers() where method.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Public select method).Distinct())
                    {
                        symbols.Add(s);
                    }

                    if (symbols != null && symbols.Count > 0)
                    {
                        var distinctSymbols = from s in symbols group s by s.Name into g select new { Name = g.Key, Symbols = g };
                        foreach (var g in distinctSymbols.OrderBy(s => s.Name.ToLower()))
                        {
                            completionDataList.Add(new QueryCompletionData(g.Name, g.Symbols.ToArray()));
                        }
                    }
                }
                catch { }
            }
            else
            {
                if (completionWindow == null)
                {
                    //列出本地变量列表
                    bool bShow = false;
                    if (textEditor.SelectionStart == textEditor.Text.Length)
                    {
                        if (textEditor.Text.Length == 1)
                        {
                            bShow = true;
                        }

                        if (textEditor.Text.Length >= 2)
                        {
                            var prevChar = textEditor.Text[textEditor.Text.Length - 2];
                            bShow = !char.IsLetterOrDigit(prevChar);
                        }
                    }

                    if (bShow)
                    {
                        var queryVarList = from s in variableDeclarations
                                           where !string.IsNullOrEmpty(s) && s.StartsWith(e.Text, System.StringComparison.CurrentCultureIgnoreCase)
                                           select s;

                        foreach (var name in queryVarList.OrderBy(s => s.ToLower()))
                        {
                            completionDataList.Add(new QueryCompletionData(name, string.Format("本地变量 {0}", name), SymbolKind.Local));
                        }
                    }
                }
            }

            if (completionDataList.Count > 0)
            {
                completionWindow = new CompletionWindow(textEditor.TextArea);
                IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                data.Clear();
                foreach (var item in completionDataList)
                {
                    data.Add(item);
                }

                if (e.Text != ".")
                {
                    //此处需要特殊处理下
                    completionWindow.StartOffset -= e.Text.Length;
                    completionWindow.CompletionList.SelectItem(e.Text);
                }

                completionWindow.Show();
                completionWindow.Closed += CompletionWindowClosed;
            }
        }
        public async Task CorrectOutputInOtherProjectAsync()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject = false;

            profile.ViewGeneration.XamlProjectSuffix      = string.Empty;
            profile.ViewGeneration.ViewModelProjectSuffix = ".ViewModels";

            profile.ViewGeneration.ViewModelDirectoryName = "";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Views";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = false,
                FileText           = @"Public Class TestViewModel
    Public Property OnlyProperty As String
End Class",
            };

            var synTree  = VisualBasicSyntaxTree.ParseText(fs.FileText);
            var semModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                SyntaxTree    = synTree,
                SemanticModel = semModel,
                ActiveProject = new ProjectWrapper {
                    Name = "App.ViewModels", FileName = @"C:\Test\App.ViewModels\App.ViewModels.vbproj"
                },
                NamedProject = new ProjectWrapper {
                    Name = "App", FileName = @"C:\Test\App\App.vbproj"
                },
            };

            var sut = new CreateViewCommandLogic(DefaultTestLogger.Create(), vsa, fs, profile);

            await sut.ExecuteAsync(@"C:\Test\App.ViewModels\TestViewModel.vb");

            var expectedXaml = "<Page"
                               + Environment.NewLine + "    x:Class=\"App.Views.TestPage\">"
                               + Environment.NewLine + "    <Grid>"
                               + Environment.NewLine + "        <StackPanel>"
                               + Environment.NewLine + "            <TextBlock FB=\"True\" Text=\"OnlyProperty\" />"
                               + Environment.NewLine + "        </StackPanel>"
                               + Environment.NewLine + "    </Grid>"
                               + Environment.NewLine + "</Page>"
                               + Environment.NewLine + "";

            var expectedCodeBehind = "Imports System"
                                     + Environment.NewLine + "Imports Windows.UI.Xaml.Controls"
                                     + Environment.NewLine + "Imports App.ViewModels"
                                     + Environment.NewLine + ""
                                     + Environment.NewLine + "Namespace Views"
                                     + Environment.NewLine + ""
                                     + Environment.NewLine + "    Public NotInheritable Partial Class TestPage"
                                     + Environment.NewLine + "        Inherits Page"
                                     + Environment.NewLine + ""
                                     + Environment.NewLine + "        Public Property ViewModel As TestViewModel"
                                     + Environment.NewLine + ""
                                     + Environment.NewLine + "        Public Sub New()"
                                     + Environment.NewLine + "            Me.InitializeComponent()"
                                     + Environment.NewLine + "            Me.ViewModel = New TestViewModel()"
                                     + Environment.NewLine + "        End Sub"
                                     + Environment.NewLine + "    End Class"
                                     + Environment.NewLine + "End Namespace"
                                     + Environment.NewLine + "";

            Assert.IsTrue(sut.CreateView);
            Assert.AreEqual(@"C:\Test\App\Views\TestPage.xaml", sut.XamlFileName);
            Assert.AreEqual(@"C:\Test\App\Views\TestPage.xaml.vb", sut.CodeFileName);
            StringAssert.AreEqual(expectedXaml, sut.XamlFileContents);
            StringAssert.AreEqual(expectedCodeBehind, sut.CodeFileContents);
        }
示例#10
0
        static void VBSample()
        {
            SyntaxTree hostTree = VisualBasicSyntaxTree.ParseText(@"
Namespace VBUserCode
    Class VBUserCodeContext
        Inherits DRTInterfaces.VBUserCodeContextBase
        Public Sub New(record As DRTInterfaces.IRecord)
            MyBase.New(record)
        End Sub
        Sub _Execute()
            
        End Sub
    End Class
End Namespace");

            string     usercode     = @"
For Each i In currentRecord.Rows
    Dim val = ValueReference(i, ""myValue"")
    val.Value = 4
    'val = 4
    System.Console.WriteLine(""Did a thing"")
Next
System.Console.WriteLine(""out of loop"")
Dim foo As Integer = 4
";
            SyntaxTree userCodeTree = VisualBasicSyntaxTree.ParseText(
                usercode, new VisualBasicParseOptions(kind: SourceCodeKind.Script)
                );

            var injectedSyntaxNode = new VBUserCodeInjector(userCodeTree).Visit(hostTree.GetRoot());

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.CompilerServices.NewLateBinding).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(VBUserCodeContextBase).Assembly.Location)
            };

            string assemblyName = Path.GetRandomFileName();
            VisualBasicCompilation compilation = VisualBasicCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { injectedSyntaxNode.SyntaxTree },
                references: references,
                options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            // new VBVisitor().Visit(injectedSyntaxNode);

            Assembly assembly = null;

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in result.Diagnostics)
                    {
                        Console.Error.WriteLine("{0} - {1}: {2}", diagnostic.Id, diagnostic.Location, diagnostic.GetMessage());
                    }
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }

            if (assembly != null)
            {
                var rec = new RecordStub();

                Type type = assembly.GetType("VBUserCode.VBUserCodeContext");
                var  obj  = Activator.CreateInstance(type, new object[] { rec }) as VBUserCodeContextBase;
                type.InvokeMember("_Execute",
                                  BindingFlags.Default | BindingFlags.InvokeMethod,
                                  null,
                                  obj,
                                  null);
            }
        }
        public async Task CorrectOutputInSameFolderAsync()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject       = true;
            profile.ViewGeneration.ViewModelDirectoryName = "Files";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Files";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = false,
                FileText           = @"Public Class TestViewModel
    Public Property OnlyProperty As String
End Class",
            };

            var synTree  = VisualBasicSyntaxTree.ParseText(fs.FileText);
            var semModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                SyntaxTree    = synTree,
                SemanticModel = semModel,
                ActiveProject = new ProjectWrapper()
                {
                    Name = "App", FileName = @"C:\Test\App\App.vbproj"
                },
            };

            var sut = new CreateViewCommandLogic(profile, DefaultTestLogger.Create(), vsa, fs);

            await sut.ExecuteAsync(@"C:\Test\App\Files\TestViewModel.vb");

            var expectedXaml = @"<Page
    x:Class=""App.Files.TestPage"">
    <Grid>
        <StackPanel>
            <TextBlock FB=""True"" Text=""OnlyProperty"" />
        </StackPanel>
    </Grid>
</Page>
";

            var expectedCodeBehind = @"Imports System
Imports Windows.UI.Xaml.Controls
Imports App.Files

Namespace Files

    Public NotInheritable Partial Class TestPage
        Inherits Page

        Public Property ViewModel As TestViewModel

        Public Sub New()
            Me.InitializeComponent()
            Me.ViewModel = New TestViewModel()
        End Sub
    End Class
End Namespace
";

            Assert.IsTrue(sut.CreateView);
            Assert.AreEqual(@"C:\Test\App\Files\TestPage.xaml", sut.XamlFileName);
            Assert.AreEqual(@"C:\Test\App\Files\TestPage.xaml.vb", sut.CodeFileName);
            Assert.AreEqual(expectedXaml, sut.XamlFileContents);
            Assert.AreEqual(expectedCodeBehind, sut.CodeFileContents);
        }
示例#12
0
        public void TestGivesAccessTo_CrossLanguageAndCompilation()
        {
            var csharpTree = CSharpSyntaxTree.ParseText(
                @"
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB"")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")]
internal class CS
{
}
"
                );
            var csharpTree2 = CSharpSyntaxTree.ParseText(
                @"
internal class CS2
{
}
"
                );
            var vbTree = VisualBasicSyntaxTree.ParseText(
                @"
<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS"")>
<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB2"")>
Friend Class VB
End Class
"
                );
            var vbTree2 = VisualBasicSyntaxTree.ParseText(
                @"
Friend Class VB2
End Class
"
                );
            var csc = (Compilation)CSharpCompilation.Create(
                "CS",
                new[] { csharpTree },
                new MetadataReference[] { TestBase.MscorlibRef }
                );
            var CS = csc.GlobalNamespace.GetMembers("CS").First() as INamedTypeSymbol;

            var csc2 = (Compilation)CSharpCompilation.Create(
                "CS2",
                new[] { csharpTree2 },
                new MetadataReference[] { TestBase.MscorlibRef }
                );
            var CS2 = csc2.GlobalNamespace.GetMembers("CS2").First() as INamedTypeSymbol;

            var vbc = VisualBasicCompilation.Create(
                "VB",
                new[] { vbTree },
                new MetadataReference[] { TestBase.MscorlibRef }
                );
            var VB = vbc.GlobalNamespace.GetMembers("VB")[0] as INamedTypeSymbol;

            var vbc2 = VisualBasicCompilation.Create(
                "VB2",
                new[] { vbTree2 },
                new MetadataReference[] { TestBase.MscorlibRef }
                );
            var VB2 = vbc2.GlobalNamespace.GetMembers("VB2")[0] as INamedTypeSymbol;

            Assert.True(CS.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly));
            Assert.True(CS.ContainingAssembly.GivesAccessTo(VB.ContainingAssembly));
            Assert.False(CS.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly));

            Assert.True(VB.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly));
            Assert.True(VB.ContainingAssembly.GivesAccessTo(CS.ContainingAssembly));
            Assert.False(VB.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly));
        }
示例#13
0
 protected override Compilation CreateNewEmptyCompilation()
 {
     return((Compilation)(object)VisualBasicCompilation.Create("TemporaryT4Assembly", (IEnumerable <SyntaxTree>)null, (IEnumerable <MetadataReference>)null, (VisualBasicCompilationOptions)null));
 }
示例#14
0
 DbgDotNetText GetExpressionText(EvaluationContext evaluationContext, VisualBasicCompilation compilation, string expression, CancellationToken cancellationToken)
 {
     var(exprSource, exprOffset) = CreateExpressionSource(evaluationContext, expression);
     return(GetExpressionText(LanguageNames.VisualBasic, visualBasicCompilationOptions, visualBasicParseOptions, expression, exprSource, exprOffset, compilation.References, cancellationToken));
 }
示例#15
0
 public void Initialize(Compilation convertedCompilation)
 {
     _convertedCompilation = (VisualBasicCompilation)convertedCompilation;
 }
 protected override Compilation CreateScriptCompilation(string assemblyName, SyntaxTree syntaxTree,
                                                        IEnumerable <MetadataReference> references, CompilationOptions options,
                                                        Compilation previousScriptCompilation, Type returnType, Type globalsType) =>
 VisualBasicCompilation.CreateScriptCompilation(assemblyName, syntaxTree, references, (VisualBasicCompilationOptions)options, (VisualBasicCompilation)previousScriptCompilation, returnType, globalsType);
        // 進捗画面側で実行してもらう処理
        private async Task DoWorkAsync()
        {
            // ソースコードをRoslynに渡す、ソースコードをDBに入れる
            await Task.Run(async() =>
            {
                var slnParser = new SolutionParser();
                var prjParser = new ProjectParser();

                // ソリューションファイル
                var slnInfo = slnParser.Parse(SolutionFile);
                if (AppEnv.SolutionInfos.Any(x => x.SolutionFile == SolutionFile))
                {
                    return;
                }

                AppEnv.SolutionInfos.Add(slnInfo);

                foreach (var prjRefInfo in slnInfo.ProjectFiles)
                {
                    // プロジェクトファイル
                    var prjInfo = prjParser.Parse(SolutionFile, prjRefInfo.ProjectFile);
                    if (AppEnv.ProjectInfos.Any(x => x.SolutionFile == prjInfo.SolutionFile && x.ProjectFile == prjInfo.ProjectFile))
                    {
                        continue;
                    }

                    AppEnv.ProjectInfos.Add(prjInfo);

                    // Roslyn 解析に必要なデータ系
                    //Microsoft.CodeAnalysis.ProjectInfo と DotBarg.Libraries.Parsers.ProjectInfo が同じクラス名のため、こちらはフルパスで書く
                    var dllItems = new List <Microsoft.CodeAnalysis.MetadataReference>();
                    var mscorlib = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
                    dllItems.Add(mscorlib);

                    var csSrcItems = new List <Microsoft.CodeAnalysis.SyntaxTree>();
                    var vbSrcItems = new List <Microsoft.CodeAnalysis.SyntaxTree>();

                    // ソースファイル
                    var srcInfos = prjInfo.SourceFiles;
                    foreach (var srcInfo in srcInfos)
                    {
                        var contents = await Util.ReadToEndAsync(srcInfo.SourceFile);

                        switch (prjInfo.Languages)
                        {
                        case Languages.CSharp:

                            var csTree   = CSharpSyntaxTree.ParseText(text: contents, path: srcInfo.SourceFile);
                            var csWalker = new CSharpSourceSyntaxWalker();
                            csWalker.Parse(srcInfo.SourceFile, contents, prjInfo.RootNamespace);

                            if (csWalker.UserDefinitions.Any())
                            {
                                AppEnv.UserDefinitions.AddRange(csWalker.UserDefinitions.ToList());
                            }

                            csSrcItems.Add(csTree);

                            if (srcInfo.HasDesignerFile)
                            {
                                contents = await Util.ReadToEndAsync(srcInfo.DesignerFile);
                                csTree   = CSharpSyntaxTree.ParseText(text: contents, path: srcInfo.DesignerFile);
                                csWalker = new CSharpSourceSyntaxWalker();
                                csWalker.Parse(srcInfo.DesignerFile, contents, prjInfo.RootNamespace);

                                if (csWalker.UserDefinitions.Any())
                                {
                                    AppEnv.UserDefinitions.AddRange(csWalker.UserDefinitions.ToList());
                                }

                                csSrcItems.Add(csTree);
                            }

                            break;

                        case Languages.VBNet:

                            var vbTree   = VisualBasicSyntaxTree.ParseText(text: contents, path: srcInfo.SourceFile);
                            var vbWalker = new VBNetSourceSyntaxWalker();
                            vbWalker.Parse(srcInfo.SourceFile, contents, prjInfo.RootNamespace);

                            if (vbWalker.UserDefinitions.Any())
                            {
                                AppEnv.UserDefinitions.AddRange(vbWalker.UserDefinitions.ToList());
                            }

                            vbSrcItems.Add(vbTree);

                            if (srcInfo.HasDesignerFile)
                            {
                                contents = await Util.ReadToEndAsync(srcInfo.DesignerFile);
                                vbTree   = VisualBasicSyntaxTree.ParseText(text: contents, path: srcInfo.DesignerFile);
                                vbWalker = new VBNetSourceSyntaxWalker();
                                vbWalker.Parse(srcInfo.DesignerFile, contents, prjInfo.RootNamespace);

                                if (vbWalker.UserDefinitions.Any())
                                {
                                    AppEnv.UserDefinitions.AddRange(vbWalker.UserDefinitions.ToList());
                                }

                                vbSrcItems.Add(vbTree);
                            }

                            break;
                        }
                    }

                    if (csSrcItems.Any())
                    {
                        var comp = CSharpCompilation.Create(prjInfo.AssemblyName, csSrcItems, dllItems);

                        AppEnv.CSharpCompilations.Add(comp);
                        AppEnv.CSharpSyntaxTrees.AddRange(csSrcItems);
                    }

                    if (vbSrcItems.Any())
                    {
                        var kinds   = Path.GetExtension(prjInfo.AssemblyFile).ToLower() == ".exe" ? Microsoft.CodeAnalysis.OutputKind.ConsoleApplication : Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary;
                        var options = new VisualBasicCompilationOptions(outputKind: kinds, rootNamespace: prjInfo.RootNamespace);
                        var comp    = VisualBasicCompilation.Create(prjInfo.AssemblyName, vbSrcItems, dllItems, options);

                        AppEnv.VisualBasicCompilations.Add(comp);
                        AppEnv.VisualBasicSyntaxTrees.AddRange(vbSrcItems);
                    }
                }
            });

            // 上記で登録したDB内容をもとに、継承元クラス、インターフェースの定義元を名前解決する
            // ツリーノードのモデルを作成する
            await Task.Run(() =>
            {
                var containers = AppEnv.UserDefinitions.Where(x => x.BaseTypeInfos.Any());
                if (containers.Any())
                {
                    FindDefinitionInfo(containers);
                }

                var model = CreateTreeData(SolutionFile);
                Items.Add(model);
            });
        }
示例#18
0
        private void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                try
                {
                    string startString = @"
Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace SomeNamespace

Public Class NotAProgram 
Private Sub SomeMethod()
"
                                         + "var blah = ";

                    string endString  = @" 

        End Sub
    End Class
End Namespace                       
";
                    string codeString = startString + this.Text.Substring(0, this.CaretOffset) + endString;

                    var tree = VisualBasicSyntaxTree.ParseText(codeString);

                    var root = (Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax)tree.GetRoot();

                    var compilation = VisualBasicCompilation.Create("CustomIntellisense")
                                      .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                      .AddSyntaxTrees(tree);

                    var model = compilation.GetSemanticModel(tree);

                    var exprString = root.FindToken(codeString.LastIndexOf('.') - 1).Parent;

                    var literalInfo = model.GetTypeInfo(exprString);

                    var             stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type;
                    IList <ISymbol> symbols          = new List <ISymbol>()
                    {
                    };
                    foreach (var s in (from method in stringTypeSymbol.GetMembers() where method.DeclaredAccessibility == Accessibility.Public select method).Distinct())
                    {
                        symbols.Add(s);
                    }

                    if (symbols != null && symbols.Count > 0)
                    {
                        completionWindow = new CompletionWindow(this.TextArea);
                        IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                        data.Clear();
                        var distinctSymbols = from s in symbols group s by s.Name into g select new { Name = g.Key, Symbols = g };
                        foreach (var g in distinctSymbols.OrderBy(s => s.Name))
                        {
                            data.Add(new QueryCompletionData(g.Name, g.Symbols.ToArray()));
                        }

                        completionWindow.Show();
                        completionWindow.Closed += delegate
                        {
                            completionWindow = null;
                        };
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
 protected override Compilation CreateCompilation(IEnumerable <SyntaxTree> code, string dllName, IEnumerable <MetadataReference> refs, CompilationOptions opts)
 => VisualBasicCompilation.Create(dllName, code, refs, (VisualBasicCompilationOptions)opts);
示例#20
0
 private static Compilation CompileAssembly(SyntaxTree syntaxTree, string assemblyName)
 {
     return(VisualBasicCompilation.Create(assemblyName, new SyntaxTree[] { syntaxTree }, ReferenceResolver.GetDefaultReferences(), DefaultCompilationOptions));
 }
        private static ITypeSymbol GetTypeSymbol(SemanticModel semModel, SyntaxNode prop, PropertyDetails propDetails)
        {
            ITypeSymbol typeSymbol = null;

            if (propDetails.PropertyType.IsGenericTypeName())
            {
                Logger?.RecordInfo(StringRes.Info_GettingGenericType);
                TypeSyntax typeSyntax = null;

                if (prop is PropertyStatementSyntax pss)
                {
                    if (pss.AsClause is SimpleAsClauseSyntax sacs)
                    {
                        if (sacs.Type is GenericNameSyntax gns)
                        {
                            typeSyntax = gns.TypeArgumentList.Arguments.First();
                        }
                        else if (sacs.Type is QualifiedNameSyntax qns)
                        {
                            typeSyntax = ((GenericNameSyntax)qns.Right).TypeArgumentList.Arguments.First();
                        }
                    }

                    if (typeSyntax == null)
                    {
                        Logger?.RecordInfo(StringRes.Info_PropertyTypeNotRecognizedAsGeneric.WithParams(propDetails.PropertyType));
                    }
                }

                if (prop is PropertyBlockSyntax pbs)
                {
                    typeSyntax = ((GenericNameSyntax)((SimpleAsClauseSyntax)pbs.PropertyStatement.AsClause).Type).TypeArgumentList.Arguments.First();
                }

                try
                {
                    typeSymbol = semModel.GetTypeInfo(typeSyntax).Type;
                }
                catch (Exception)
                {
                    // The semanticmodel passed into this method is the one for the active document.
                    // If the type is in another file, generate a new model to use to look up the typeinfo. Don't do this by default as it's expensive.
                    var localSemModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(prop.SyntaxTree).GetSemanticModel(prop.SyntaxTree, ignoreAccessibility: true);

                    typeSymbol = localSemModel.GetTypeInfo(typeSyntax).Type;
                }
            }
            else
            {
                if (prop is PropertyStatementSyntax pss)
                {
                    if (pss.AsClause != null)
                    {
                        try
                        {
                            typeSymbol = semModel.GetTypeInfo(((SimpleAsClauseSyntax)pss.AsClause).Type).Type;
                        }
                        catch (Exception)
                        {
                            // The semanticmodel passed into this method is the one for the active document.
                            // If the type is in another file, generate a new model to use to look up the typeinfo. Don't do this by default as it's expensive.
                            var localSemModel = VisualBasicCompilation.Create(string.Empty)
                                                                      .AddSyntaxTrees(prop.SyntaxTree)
                                                                      .GetSemanticModel(prop.SyntaxTree, ignoreAccessibility: true);

                            typeSymbol = localSemModel.GetTypeInfo(((SimpleAsClauseSyntax)pss.AsClause).Type).Type;
                        }
                    }
                    else
                    {
                        try
                        {
                            if (pss.Identifier.TrailingTrivia.ToString().StartsWith("?"))
                            {
                                var propSyn = VisualBasicSyntaxTree.ParseText(prop.ToFullString().Replace("?", string.Empty).Trim() + "?");

                                var propType = ((SimpleAsClauseSyntax)((CompilationUnitSyntax)propSyn.GetRoot()).Members.OfType<PropertyStatementSyntax>().FirstOrDefault()?.AsClause)?.Type;
                                var propSemModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(propSyn).GetSemanticModel(propSyn, true);

                                typeSymbol = propSemModel.GetTypeInfo(propType).Type;
                            }
                        }
                        catch (Exception)
                        {
                            Logger?.RecordInfo(StringRes.Info_FailedToGetNullableType.WithParams(propDetails.Name));
                        }
                    }
                }
                else if (prop is PropertyBlockSyntax pbs)
                {
                    try
                    {
                        typeSymbol = semModel.GetTypeInfo(((SimpleAsClauseSyntax)pbs.PropertyStatement.AsClause).Type).Type;
                    }
                    catch (Exception)
                    {
                        // The semanticmodel passed into this method is the one for the active document.
                        // If the type is in another file, generate a new model to use to look up the typeinfo. Don't do this by default as it's expensive.
                        var localSemModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(prop.SyntaxTree).GetSemanticModel(prop.SyntaxTree, ignoreAccessibility: true);

                        typeSymbol = localSemModel.GetTypeInfo(((SimpleAsClauseSyntax)pbs.PropertyStatement.AsClause).Type).Type;
                    }
                }
            }

            return typeSymbol;
        }
示例#22
0
        private bool TryAnalyzeCsConversion(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ITypeSymbol csType,
                                            ITypeSymbol csConvertedType, Conversion vbConversion, ITypeSymbol vbConvertedType, ITypeSymbol vbType,
                                            VisualBasicCompilation vbCompilation, bool isConst, out TypeConversionKind typeConversionKind)
        {
            var csConversion = _csCompilation.ClassifyConversion(csType, csConvertedType);

            bool isConvertToString =
                (vbConversion.IsString || vbConversion.IsReference && vbConversion.IsNarrowing) && vbConvertedType.SpecialType == SpecialType.System_String;
            bool isArithmetic = vbNode.IsKind(Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.AddExpression,
                                              Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.SubtractExpression,
                                              Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.MultiplyExpression,
                                              Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.DivideExpression,
                                              Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.IntegerDivideExpression);

            if (!csConversion.Exists || csConversion.IsUnboxing)
            {
                if (ConvertStringToCharLiteral(vbNode, vbConvertedType, out _))
                {
                    typeConversionKind =
                        TypeConversionKind.Identity; // Already handled elsewhere by other usage of method
                    return(true);
                }

                if (vbType.SpecialType == SpecialType.System_String && vbConvertedType.IsArrayOf(SpecialType.System_Char))
                {
                    typeConversionKind = TypeConversionKind.StringToCharArray;
                    return(true);
                }
                if (isConvertToString || vbConversion.IsNarrowing)
                {
                    typeConversionKind = isConst ? TypeConversionKind.ConstConversion : TypeConversionKind.Conversion;
                    return(true);
                }
            }
            else if (vbConversion.IsWidening && vbConversion.IsNumeric && csConversion.IsImplicit &&
                     csConversion.IsNumeric)
            {
                // Safe overapproximation: A cast is really only needed to help resolve the overload for the operator/method used.
                // e.g. When VB "&" changes to C# "+", there are lots more overloads available that implicit casts could match.
                // e.g. sbyte * ulong uses the decimal * operator in VB. In C# it's ambiguous - see ExpressionTests.vb "TestMul".
                typeConversionKind = TypeConversionKind.NonDestructiveCast;
                return(true);
            }
            else if (csConversion.IsExplicit && csConversion.IsEnumeration)
            {
                typeConversionKind = TypeConversionKind.NonDestructiveCast;
                return(true);
            }
            else if (isArithmetic)
            {
                var arithmeticConversion =
                    vbCompilation.ClassifyConversion(vbConvertedType,
                                                     vbCompilation.GetTypeByMetadataName("System.Int32"));
                if (arithmeticConversion.IsWidening && !arithmeticConversion.IsIdentity)
                {
                    typeConversionKind = isConst ? TypeConversionKind.ConstConversion : TypeConversionKind.Conversion;
                    return(true);
                }
            }
            else if (csConversion.IsExplicit && csConversion.IsNumeric && vbConversion.IsNarrowing && isConst)
            {
                typeConversionKind = IsImplicitConstantConversion(vbNode) ? TypeConversionKind.Identity : TypeConversionKind.NonDestructiveCast;
                return(true);
            }
            else if (csConversion.IsExplicit && vbConversion.IsNumeric && vbType.TypeKind != TypeKind.Enum)
            {
                typeConversionKind = IsImplicitConstantConversion(vbNode) ? TypeConversionKind.Identity :
                                     isConst ? TypeConversionKind.ConstConversion : TypeConversionKind.Conversion;
                return(true);
            }
            else if (csConversion.IsExplicit && vbConversion.IsIdentity && csConversion.IsNumeric && vbType.TypeKind != TypeKind.Enum)
            {
                typeConversionKind = isConst ? TypeConversionKind.ConstConversion : TypeConversionKind.Conversion;
                return(true);
            }
            else if (isConvertToString && vbType.SpecialType == SpecialType.System_Object)
            {
                typeConversionKind = isConst ? TypeConversionKind.ConstConversion : TypeConversionKind.Conversion;
                return(true);
            }
            else if (csConversion.IsNullable && csConvertedType.SpecialType == SpecialType.System_Boolean)
            {
                typeConversionKind = TypeConversionKind.NullableBool;
                return(true);
            }
            else if (csConversion.IsExplicit)
            {
                typeConversionKind = TypeConversionKind.DestructiveCast;
                return(true);
            }

            typeConversionKind = csConversion.IsIdentity ? TypeConversionKind.Identity : TypeConversionKind.Unknown;
            return(false);
        }
 public override Compilation CreatCompilation(string compilationName, SyntaxTree syntaxTree, IEnumerable <MetadataReference> references, OutputKind outputKind)
 => VisualBasicCompilation.Create(compilationName, new SyntaxTree[] { syntaxTree }, references, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
示例#24
0
        public static CompilerResults CompileVB(string sourceFileName, CompilerOptions flags = CompilerOptions.UseDebug, string outputFileName = null)
        {
            List <string> sourceFileNames = new List <string> {
                sourceFileName
            };

            foreach (Match match in Regex.Matches(File.ReadAllText(sourceFileName), @"#include ""([\w\d./]+)"""))
            {
                sourceFileNames.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(sourceFileName), match.Groups[1].Value)));
            }

            var preprocessorSymbols = GetPreprocessorSymbols(flags).Select(symbol => new KeyValuePair <string, object>(symbol, 1)).ToList();

            if (flags.HasFlag(CompilerOptions.UseRoslyn))
            {
                var parseOptions = new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbols, languageVersion: LanguageVersion.Latest);
                var syntaxTrees  = sourceFileNames.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, path: f));
                var references   = defaultReferences.Value;
                if (flags.HasFlag(CompilerOptions.ReferenceVisualBasic))
                {
                    references = references.Concat(visualBasic.Value);
                }
                var compilation = VisualBasicCompilation.Create(Path.GetFileNameWithoutExtension(sourceFileName),
                                                                syntaxTrees, references,
                                                                new VisualBasicCompilationOptions(
                                                                    flags.HasFlag(CompilerOptions.Library) ? OutputKind.DynamicallyLinkedLibrary : OutputKind.ConsoleApplication,
                                                                    platform: flags.HasFlag(CompilerOptions.Force32Bit) ? Platform.X86 : Platform.AnyCpu,
                                                                    optimizationLevel: flags.HasFlag(CompilerOptions.Optimize) ? OptimizationLevel.Release : OptimizationLevel.Debug,
                                                                    deterministic: true
                                                                    ));
                CompilerResults results = new CompilerResults(new TempFileCollection());
                results.PathToAssembly = outputFileName ?? Path.GetTempFileName();
                var emitResult = compilation.Emit(results.PathToAssembly);
                if (!emitResult.Success)
                {
                    StringBuilder b = new StringBuilder("Compiler error:");
                    foreach (var diag in emitResult.Diagnostics)
                    {
                        b.AppendLine(diag.ToString());
                    }
                    throw new Exception(b.ToString());
                }
                return(results);
            }
            else if (flags.HasFlag(CompilerOptions.UseMcs))
            {
                throw new NotSupportedException("Cannot use mcs for VB");
            }
            else
            {
                var provider = new VBCodeProvider(new Dictionary <string, string> {
                    { "CompilerVersion", "v4.0" }
                });
                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable = !flags.HasFlag(CompilerOptions.Library);
                options.CompilerOptions    = "/optimize" + (flags.HasFlag(CompilerOptions.Optimize) ? "+" : "-");
                options.CompilerOptions   += (flags.HasFlag(CompilerOptions.UseDebug) ? " /debug" : "");
                options.CompilerOptions   += (flags.HasFlag(CompilerOptions.Force32Bit) ? " /platform:anycpu32bitpreferred" : "");
                options.CompilerOptions   += " /optioninfer+ /optionexplicit+";
                if (preprocessorSymbols.Count > 0)
                {
                    options.CompilerOptions += " /d:" + string.Join(",", preprocessorSymbols.Select(p => $"{p.Key}={p.Value}"));
                }
                if (outputFileName != null)
                {
                    options.OutputAssembly = outputFileName;
                }

                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                if (flags.HasFlag(CompilerOptions.ReferenceVisualBasic))
                {
                    options.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
                }
                CompilerResults results = provider.CompileAssemblyFromFile(options, sourceFileNames.ToArray());
                if (results.Errors.Cast <CompilerError>().Any(e => !e.IsWarning))
                {
                    StringBuilder b = new StringBuilder("Compiler error:");
                    foreach (var error in results.Errors)
                    {
                        b.AppendLine(error.ToString());
                    }
                    throw new Exception(b.ToString());
                }
                return(results);
            }
        }
示例#25
0
        private static object CalculateSum(double a, double b)
        {
            const string code         = @"Option strict off
Imports System
Imports Microsoft.VisualBasic
Imports LibraryProject

Namespace DummyNamespace

    Public Class Helper
             Inherits CustomType

Function Sum(d1 As Double, d2 As Double) As Double
    Return d1+d2
End Function

    End Class
End Namespace";
            var          tree         = VisualBasicSyntaxTree.ParseText(code, VisualBasicParseOptions.Default);
            var          binDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
            var          vbAssembly   = typeof(Conversions).Assembly;
            var          vb           = MetadataReference.CreateFromFile(vbAssembly.Location);
            var          fileName     = "myLib";
            var          compilation  = VisualBasicCompilation.Create(fileName)
                                        .WithOptions(new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                        .AddReferences(MetadataReference.CreateFromFile(typeof(CustomType).Assembly.Location))
                                        .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                        .AddReferences(vb)
                                        .AddReferences(GetReferencedAssembliesRecursively(vbAssembly).Select(a => MetadataReference.CreateFromFile(a)))
                                        .AddSyntaxTrees(tree);
            var newpath = Path.Combine(Path.GetTempPath(), $"MyLibrary_{DateTime.Now:yyMMdd}");

            Directory.CreateDirectory(newpath);
            var path = Path.Combine(newpath, "MyLibrary.dll");
            var compilationResult = compilation.Emit(path);

            if (compilationResult.Success)
            {
                // below code works since our reference to LibraryProject.dll is already loaded in thi ALC

                /* var nunitCustomAssemblyLoadContext = AssemblyLoadContext.All.Single(c => c.ToString().Contains("NUnit.Engine.Internal.CustomAssemblyLoadContext"));
                 * var asm = nunitCustomAssemblyLoadContext.LoadFromAssemblyPath(path);*/

                //This code works as well using NUnit.Console 3.13.0: https://github.com/nunit/nunit-console/pull/942
                var asm = (AssemblyLoadContext.CurrentContextualReflectionContext ?? AssemblyLoadContext.Default).LoadFromAssemblyPath(path);

                // this doesn't work
                //var asm = Assembly.LoadFrom(path);
                var classFullName = "DummyNamespace.Helper";
                var type          = asm.GetType(classFullName);
                if (type == null)
                {
                    throw new Exception($"Type '{classFullName}' could not be found");
                }
                var instance = asm.CreateInstance(classFullName);
                if (instance == null)
                {
                    throw new Exception($"'{classFullName}' deosn't have a valid default constructor");
                }
                var methodInfo = type.GetMethod("Sum");
                if (methodInfo == null)
                {
                    throw new Exception($"Method 'Sum' could not be found in type {type.FullName}");
                }
                return(methodInfo.Invoke(instance, new object[] { a, b }));
            }
            foreach (var codeIssue in compilationResult.Diagnostics)
            {
                Console.WriteLine($"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()}, Location: {codeIssue.Location.GetLineSpan()}, Severity: {codeIssue.Severity}");
            }
            return(null);
        }