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);
        }
Beispiel #2
0
        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);
        }
        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);
        }
        /// <summary>
        /// Constructs a new global binding.
        /// </summary>
        /// <param name="import">The global import of the binding.</param>
        /// <param name="field">The field the import is bound to.</param>
        public GlobalBinding(GlobalImport import, FieldInfo field)
        {
            if (import is null)
            {
                throw new ArgumentNullException(nameof(import));
            }

            if (field is null)
            {
                throw new ArgumentNullException(nameof(field));
            }

            Import = import;
            Field  = field;

            Validate();
        }
Beispiel #5
0
        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);
            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "TestProject",
                               "TestProject",
                               LanguageNames.VisualBasic,
                               null,
                               null,
                               new VisualBasicCompilationOptions(
                                   OutputKind.DynamicallyLinkedLibrary,
                                   "",
                                   "",
                                   "Script",
                                   GlobalImport.Parse("System", "Microsoft.VisualBasic")
                                   ),
                               parseOptions,
                               new[] {
                DocumentInfo.Create(
                    documentId,
                    "a.vb",
                    null,
                    SourceCodeKind.Regular
                    )
            },
                               null,
                               DiagnosticTestBase.DefaultMetadataReferences
                               )
                           );
            doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId);
        }
Beispiel #6
0
        private static GlobalBinding BindGlobal(GlobalImport import, IEnumerable <FieldInfo> fields)
        {
            var field = fields?.Where(f =>
            {
                var attribute = (ImportAttribute)f.GetCustomAttribute(typeof(ImportAttribute));
                return(attribute.Name == import.Name &&
                       ((string.IsNullOrEmpty(attribute.Module) &&
                         string.IsNullOrEmpty(import.ModuleName)) ||
                        attribute.Module == import.ModuleName));
            }
                                      ).FirstOrDefault();

            if (field is null)
            {
                throw new WasmtimeException($"Failed to bind global import '{import}': the host does not contain a global field with a matching 'Import' attribute.");
            }

            return(new GlobalBinding(import, field));
        }
        public Task MissingSystemImport_IsNotAdded_WhenIncludedInGlobalImports_VBAsync()
        {
            var test = new VerifyVB.Test
            {
                TestCode            = VBWithBody(@"Dim s = {|#0:foo & bar.Substring(1)|}"),
                FixedCode           = VBWithBody(@"Dim s = String.Concat(foo, bar.AsSpan(1))"),
                ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
                ExpectedDiagnostics = { VerifyVB.Diagnostic(Rule).WithLocation(0) }
            };

            test.SolutionTransforms.Add((s, id) =>
            {
                var project            = s.Projects.Single();
                var options            = project.CompilationOptions as VisualBasicCompilationOptions;
                var globalSystemImport = GlobalImport.Parse(nameof(System));
                options = options.WithGlobalImports(globalSystemImport);
                return(s.WithProjectCompilationOptions(project.Id, options));
            });
            return(test.RunAsync());
        }
        public Compilation CreateCompilationFromTree(SyntaxTree tree, IEnumerable <MetadataReference> references)
        {
            var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                     .WithRootNamespace("TestProject")
                                     .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"));
            var compilation = VisualBasicCompilation.Create("Conversion", new[] { tree }, references)
                              .WithOptions(compilationOptions);

            return(compilation);
        }
        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);
        }
        private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement, ParseOptions parseOptions)
        {
            var rootNamespace      = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
            var globalImports      = new List <GlobalImport>();
            var reportDiagnostic   = ReportDiagnostic.Default;
            var cryptoKeyFile      = (string)null;
            var strongNameProvider = (StrongNameProvider)null;
            var delaySign          = (bool?)null;
            var checkOverflow      = false;
            var allowUnsafe        = false;
            var outputKind         = OutputKind.DynamicallyLinkedLibrary;
            var nullable           = NullableContextOptions.Disable;

            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 outputKindAttribute = compilationOptionsElement.Attribute(OutputKindName);
                if (outputKindAttribute != null)
                {
                    outputKind = (OutputKind)Enum.Parse(typeof(OutputKind), (string)outputKindAttribute.Value);
                }

                var checkOverflowAttribute = compilationOptionsElement.Attribute(CheckOverflowAttributeName);
                if (checkOverflowAttribute != null)
                {
                    checkOverflow = (bool)checkOverflowAttribute;
                }

                var allowUnsafeAttribute = compilationOptionsElement.Attribute(AllowUnsafeAttributeName);
                if (allowUnsafeAttribute != null)
                {
                    allowUnsafe = (bool)allowUnsafeAttribute;
                }

                var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
                if (reportDiagnosticAttribute != null)
                {
                    reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
                }

                var cryptoKeyFileAttribute = compilationOptionsElement.Attribute(CryptoKeyFileAttributeName);
                if (cryptoKeyFileAttribute != null)
                {
                    cryptoKeyFile = (string)cryptoKeyFileAttribute;
                }

                var strongNameProviderAttribute = compilationOptionsElement.Attribute(StrongNameProviderAttributeName);
                if (strongNameProviderAttribute != null)
                {
                    var type = Type.GetType((string)strongNameProviderAttribute);
                    // DesktopStrongNameProvider and SigningTestHelpers.VirtualizedStrongNameProvider do
                    // not have a default constructor but constructors with optional parameters.
                    // Activator.CreateInstance does not work with this.
                    if (type == typeof(DesktopStrongNameProvider))
                    {
                        strongNameProvider = SigningTestHelpers.DefaultDesktopStrongNameProvider;
                    }
                    else
                    {
                        strongNameProvider = (StrongNameProvider)Activator.CreateInstance(type);
                    }
                }

                var delaySignAttribute = compilationOptionsElement.Attribute(DelaySignAttributeName);
                if (delaySignAttribute != null)
                {
                    delaySign = (bool)delaySignAttribute;
                }

                var nullableAttribute = compilationOptionsElement.Attribute(NullableAttributeName);
                if (nullableAttribute != null)
                {
                    nullable = (NullableContextOptions)Enum.Parse(typeof(NullableContextOptions), (string)nullableAttribute.Value);
                }

                var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
                if (outputTypeAttribute != null &&
                    outputTypeAttribute.Value == "WindowsRuntimeMetadata")
                {
                    if (rootNamespaceAttribute == null)
                    {
                        rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
                    }

                    // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                    return(language == LanguageNames.CSharp
                       ? (CompilationOptions) new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, allowUnsafe: allowUnsafe)
                       : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace)
                           .WithParseOptions((VisualBasicParseOptions)parseOptions ?? VisualBasicParseOptions.Default));
                }
            }
            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)
                                 .WithGeneralDiagnosticOption(reportDiagnostic)
                                 .WithSourceReferenceResolver(SourceFileResolver.Default)
                                 .WithXmlReferenceResolver(XmlFileResolver.Default)
                                 .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, null)))
                                 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                                 .WithCryptoKeyFile(cryptoKeyFile)
                                 .WithStrongNameProvider(strongNameProvider)
                                 .WithDelaySign(delaySign)
                                 .WithOverflowChecks(checkOverflow);

            if (language == LanguageNames.CSharp)
            {
                compilationOptions = ((CSharpCompilationOptions)compilationOptions).WithAllowUnsafe(allowUnsafe).WithNullableContextOptions(nullable);
            }

            if (language == LanguageNames.VisualBasic)
            {
                // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
                                     .WithGlobalImports(globalImports)
                                     .WithParseOptions((VisualBasicParseOptions)parseOptions ??
                                                       VisualBasicParseOptions.Default);
            }

            return(compilationOptions);
        }
        private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(
            string assemblyFileName,
            CompilationOptionsReader optionsReader
            )
        {
            var pdbOptions = optionsReader.GetMetadataCompilationOptions();

            var langVersionString = pdbOptions.GetUniqueOption(
                CompilationOptionNames.LanguageVersion
                );

            pdbOptions.TryGetUniqueOption(
                CompilationOptionNames.Optimization,
                out var optimization
                );
            pdbOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform);
            pdbOptions.TryGetUniqueOption(
                CompilationOptionNames.GlobalNamespaces,
                out var globalNamespacesString
                );

            IEnumerable <GlobalImport>?globalImports = null;

            if (!string.IsNullOrEmpty(globalNamespacesString))
            {
                globalImports = GlobalImport.Parse(globalNamespacesString.Split(';'));
            }

            VB.LanguageVersion langVersion = default;
            VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion);

            IReadOnlyDictionary <string, object>?preprocessorSymbols = null;

            if (pdbOptions.OptionToString(CompilationOptionNames.Define) is string defineString)
            {
                preprocessorSymbols =
                    VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(
                        defineString,
                        out var diagnostics
                        );
                var diagnostic = diagnostics?.FirstOrDefault(x => x.IsUnsuppressedError);
                if (diagnostic is object)
                {
                    throw new Exception($"Cannot create compilation options: {diagnostic}");
                }
            }

            var parseOptions = VisualBasicParseOptions.Default
                               .WithLanguageVersion(langVersion)
                               .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty());

            var(optimizationLevel, plus) = GetOptimizationLevel(optimization);
            var isChecked      = pdbOptions.OptionToBool(CompilationOptionNames.Checked) ?? true;
            var embedVBRuntime =
                pdbOptions.OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false;
            var rootNamespace = pdbOptions.OptionToString(CompilationOptionNames.RootNamespace);

            var compilationOptions = new VisualBasicCompilationOptions(
                pdbOptions.OptionToEnum <OutputKind>(CompilationOptionNames.OutputKind)
                ?? OutputKind.DynamicallyLinkedLibrary,
                moduleName: assemblyFileName,
                mainTypeName: optionsReader.GetMainTypeName(),
                scriptClassName: "Script",
                globalImports: globalImports,
                rootNamespace: rootNamespace,
                optionStrict: pdbOptions.OptionToEnum <OptionStrict>(
                    CompilationOptionNames.OptionStrict
                    ) ?? OptionStrict.Off,
                optionInfer: pdbOptions.OptionToBool(CompilationOptionNames.OptionInfer) ?? false,
                optionExplicit: pdbOptions.OptionToBool(CompilationOptionNames.OptionExplicit)
                ?? false,
                optionCompareText: pdbOptions.OptionToBool(CompilationOptionNames.OptionCompareText)
                ?? false,
                parseOptions: parseOptions,
                embedVbCoreRuntime: embedVBRuntime,
                optimizationLevel: optimizationLevel,
                checkOverflow: isChecked,
                cryptoKeyContainer: null,
                cryptoKeyFile: null,
                cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default,
                delaySign: null,
                platform: GetPlatform(platform),
                generalDiagnosticOption: ReportDiagnostic.Default,
                specificDiagnosticOptions: null,
                concurrentBuild: true,
                deterministic: true,
                xmlReferenceResolver: null,
                sourceReferenceResolver: null,
                metadataReferenceResolver: null,
                assemblyIdentityComparer: null,
                strongNameProvider: null,
                publicSign: false,
                reportSuppressedDiagnostics: false,
                metadataImportOptions: MetadataImportOptions.Public
                );

            compilationOptions.DebugPlusMode = plus;

            return(compilationOptions);
        }
            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);
                    }
                }
            }