public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
        {
            var options = new CSharpParseOptions(_languageVersion);
            trees = files.Select(x =>
            {
                var text = x.Value;
                var tree = CSharpSyntaxTree.ParseText(text, options: options);
                if (tree.GetDiagnostics().Any())
                    throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
                return tree;
            }).ToArray();

            // adding everything is going to cause issues with dynamic assemblies
            // so we would want to filter them anyway... but we don't need them really
            //var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
            // though that one is not ok either since we want our own reference
            //var refs = Enumerable.Empty<MetadataReference>();
            // so use the bare minimum
            var asms = ReferencedAssemblies;
            var a1 = typeof(Builder).Assembly;
            asms.Add(a1);
            foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
            var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(
                assemblyName,
                /*syntaxTrees:*/ trees,
                /*references:*/ refs,
                compilationOptions);

            return compilation;
        }
        private void TestWithOptions(CSharpParseOptions options, string markup, params Action<object>[] expectedResults)
        {
            using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, options))
            {
                var position = workspace.Documents.Single().CursorPosition.Value;

                var noListeners = SpecializedCollections.EmptyEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>>();

                var provider = new SemanticQuickInfoProvider(
                    workspace.GetService<ITextBufferFactoryService>(),
                    workspace.GetService<IContentTypeRegistryService>(),
                    workspace.GetService<IProjectionBufferFactoryService>(),
                    workspace.GetService<IEditorOptionsFactoryService>(),
                    workspace.GetService<ITextEditorFactoryService>(),
                    workspace.GetService<IGlyphService>(),
                    workspace.GetService<ClassificationTypeMap>());

                TestWithOptions(workspace, provider, position, expectedResults);

                // speculative semantic model
                var document = workspace.CurrentSolution.Projects.First().Documents.First();
                if (CanUseSpeculativeSemanticModel(document, position))
                {
                    var buffer = workspace.Documents.Single().TextBuffer;
                    using (var edit = buffer.CreateEdit())
                    {
                        edit.Replace(0, buffer.CurrentSnapshot.Length, buffer.CurrentSnapshot.GetText());
                        edit.Apply();
                    }

                    TestWithOptions(workspace, provider, position, expectedResults);
                }
            }
        }
예제 #3
0
        public MyScriptCompiler()
        {
            AddReferencedAssemblies(
                this.GetType().Assembly.Location,
                typeof(int).Assembly.Location,
                typeof(System.Xml.XmlEntity).Assembly.Location,
                typeof(System.Collections.Generic.HashSet<>).Assembly.Location,
                typeof(System.Uri).Assembly.Location
                );

            AddImplicitIngameNamespacesFromTypes(
                typeof(System.Object),
                typeof(System.Text.StringBuilder),
                typeof(System.Collections.IEnumerable),
                typeof(System.Collections.Generic.IEnumerable<>)
                );

            AddUnblockableIngameExceptions(typeof(ScriptOutOfRangeException));

            m_debugCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, platform: Platform.X64);
            m_runtimeCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, platform: Platform.X64);
            m_whitelist = new MyScriptWhitelist(this);
            m_ingameWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.Ingame);
            m_modApiWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.ModApi);
            m_conditionalParseOptions = new CSharpParseOptions();
        }
        private CompileResult BuildFull(CompileOptions options)
        {
            var result = new CompileResult();

            _logger.Info("BuildFull");
            _options = options;

            _referenceFileList = new FileTimeList();
            _referenceFileList.Update(options.References);

            _sourceFileList = new FileTimeList();
            _sourceFileList.Update(options.Files);

            _referenceMap = options.References.ToDictionary(
               file => file,
               file => CreateReference(file));

            var parseOption = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular, options.Defines);
            _sourceMap = options.Files.ToDictionary(
                file => file,
                file => ParseSource(file, parseOption));

            _compilation = CSharpCompilation.Create(
                options.AssemblyName,
                _sourceMap.Values,
                _referenceMap.Values,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            Emit(result);

            return result;
        }
예제 #5
0
        public void CompilationChain_SystemObject_NotEquals()
        {
            // As in VS/ETA, make a new list of references for each submission.

            var options = new CSharpParseOptions(kind: SourceCodeKind.Script, documentationMode: DocumentationMode.None);
            var corLib = AssemblyMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.mscorlib);

            var s1 = CSharpCompilation.CreateSubmission("s1.dll",
                syntaxTree: SyntaxFactory.ParseSyntaxTree("struct S { }", options),
                references: new[] { corLib.GetReference(documentation: new TestDocumentationProviderNoEquals()) },
                returnType: typeof(object));

            s1.VerifyDiagnostics();

            var s2 = CSharpCompilation.CreateSubmission("s2.dll",
                syntaxTree: SyntaxFactory.ParseSyntaxTree("System.Collections.IEnumerable Iterator() { yield return new S(); }", options),
                previousSubmission: s1,
                references: new[] { corLib.GetReference(documentation: new TestDocumentationProviderNoEquals()) },
                returnType: typeof(object));

            Assert.NotEqual(s1.GetSpecialType(SpecialType.System_Object), s2.GetSpecialType(SpecialType.System_Object));

            s2.VerifyDiagnostics(
                // (1,58): error CS0029: Cannot implicitly convert type 'S' to 'object'
                // System.Collections.IEnumerable Iterator() { yield return new S(); }
                Diagnostic(ErrorCode.ERR_NoImplicitConv, "new S()").WithArguments("S", "object"));
        }
        protected void Test(string code,
           string allCode,
           Tuple<string, string>[] expected,
           CSharpParseOptions options = null)
        {
            var start = allCode.IndexOf(code);
            var length = code.Length;
            var span = new TextSpan(start, length);

            var actual = GetClassificationSpans(allCode, span, options: options).ToList();

            actual.Sort((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start);

            var max = Math.Max(expected.Length, actual.Count);
            for (int i = 0; i < max; i++)
            {
                if (i >= expected.Length)
                {
                    AssertEx.Fail("Unexpected actual classification: {0}", GetText(actual[i]));
                }
                else if (i >= actual.Count)
                {
                    AssertEx.Fail("Missing classification for: {0}", GetText(expected[i]));
                }

                var tuple = expected[i];
                var classification = actual[i];

                var text = allCode.Substring(classification.TextSpan.Start, classification.TextSpan.Length);
                Assert.Equal(tuple.Item1, text);
                Assert.Equal(tuple.Item2, classification.ClassificationType);
            }
        }
예제 #7
0
        private CompilationVerifier CompileAndVerifyIL(
            string source,
            string methodName,
            string expectedOptimizedIL = null,
            string expectedUnoptimizedIL = null,
            MetadataReference[] references = null,
            bool allowUnsafe = false,
            [CallerFilePath]string callerPath = null,
            [CallerLineNumber]int callerLine = 0,
            CSharpParseOptions parseOptions = null)
        {
            references = references ?? new[] { SystemCoreRef, CSharpRef };

            // verify that we emit correct optimized and unoptimized IL:
            var unoptimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe));
            var optimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe));

            var unoptimizedVerifier = CompileAndVerify(unoptimizedCompilation);
            var optimizedVerifier = CompileAndVerify(optimizedCompilation);

            // check what IL we emit exactly:
            if (expectedUnoptimizedIL != null)
            {
                unoptimizedVerifier.VerifyIL(methodName, expectedUnoptimizedIL, realIL: true, sequencePoints: methodName, callerPath: callerPath, callerLine: callerLine);
            }

            if (expectedOptimizedIL != null)
            {
                optimizedVerifier.VerifyIL(methodName, expectedOptimizedIL, realIL: true, callerPath: callerPath, callerLine: callerLine);
            }

            // return null if ambiguous
            return (expectedUnoptimizedIL != null) ^ (expectedOptimizedIL != null) ? (unoptimizedVerifier ?? optimizedVerifier) : null;
        }
        public void Test_CSharp5_NameClash()
        {
            var parseOptions = new CSharpParseOptions(
                                            LanguageVersion.CSharp5,
                                            DocumentationMode.Diagnose | DocumentationMode.Parse,
                                            SourceCodeKind.Regular,
                                            ImmutableArray.Create("DEBUG", "TEST")
                                        );
            Test<CreateEventInvocatorCodeRefactoringProvider>(@"using System;
class TestClass
{
    public event EventHandler $e;
}", @"using System;
class TestClass
{
    protected virtual void OnE(EventArgs e)
    {
        var handler = this.e;
        if (handler != null)
            handler(this, e);
    }

    public event EventHandler e;
}", parseOptions: parseOptions);
        }
예제 #9
0
        public void CompilationChain_SystemObject_NotEquals()
        {
            // As in VS/ETA, make a new list of references for each submission.

            var options = new CSharpParseOptions(kind: SourceCodeKind.Interactive, documentationMode: DocumentationMode.None);
            var provider = new TestMetadataReferenceProvider() { MakeDocumentationProvider = () => new TestDocumentationProviderNoEquals() };

            var s1 = CSharpCompilation.CreateSubmission("s1.dll",
                syntaxTree: SyntaxFactory.ParseSyntaxTree("struct S { }", options),
                references: MakeReferencesViaCommandLine(provider),
                returnType: typeof(object));

            s1.VerifyDiagnostics();

            var s2 = CSharpCompilation.CreateSubmission("s2.dll",
                syntaxTree: SyntaxFactory.ParseSyntaxTree("System.Collections.IEnumerable Iterator() { yield return new S(); }", options),
                previousSubmission: s1,
                references: MakeReferencesViaCommandLine(provider),
                returnType: typeof(object));

            Assert.NotEqual(s1.GetSpecialType(SpecialType.System_Object), s2.GetSpecialType(SpecialType.System_Object));

            s2.VerifyDiagnostics(
                // (1,58): error CS0029: Cannot implicitly convert type 'S' to 'object'
                // System.Collections.IEnumerable Iterator() { yield return new S(); }
                Diagnostic(ErrorCode.ERR_NoImplicitConv, "new S()").WithArguments("S", "object"));
        }
        protected Info ProcessCode(DiagnosticAnalyzer analyzer, string sampleProgram,
                                   ImmutableArray<SyntaxKind> expected, bool allowBuildErrors = false)
        {
            var options = new CSharpParseOptions(kind: SourceCodeKind.Script); //, languageVersion: LanguageVersion.CSharp5);
            var tree = CSharpSyntaxTree.ParseText(sampleProgram, options);
            var compilation = CSharpCompilation.Create("Test", new[] { tree }, references);

            var diagnostics = compilation.GetDiagnostics();
            if (diagnostics.Count(d => d.Severity == DiagnosticSeverity.Error) > 0)
            {
                var msg = "There were Errors in the sample code\n";
                if (allowBuildErrors == false)
                    Assert.Fail(msg + string.Join("\n", diagnostics));
                else
                    Console.WriteLine(msg + string.Join("\n", diagnostics));
            }

            var semanticModel = compilation.GetSemanticModel(tree);
            var matches = GetExpectedDescendants(tree.GetRoot().ChildNodes(), expected);

            // Run the code tree through the analyzer and record the allocations it reports
            var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer));
               var allocations = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult().Distinct(DiagnosticEqualityComparer.Instance).ToList();

            return new Info
            {
                Options = options,
                Tree = tree,
                Compilation = compilation,
                Diagnostics = diagnostics,
                SemanticModel = semanticModel,
                Matches = matches,
                Allocations = allocations,
            };
        }
예제 #11
0
        internal static void ParseAndRoundTripping(string text, CSharpParseOptions options, int errorCount = 0, int memberCount = 0)
        {
            var tree = SyntaxFactory.ParseSyntaxTree(SourceText.From(text), options);
            var toText = tree.GetCompilationUnitRoot().ToFullString();

            Assert.Equal(text, toText);

            // -1 mean there are errors but actual number of errors is not important.
            // it makes the test more robust in case error count changes
            if (errorCount == -1)
            {
                Assert.NotEqual(0, tree.GetCompilationUnitRoot().ErrorsAndWarnings().Length);
            }
            else
            {
                Assert.Equal(errorCount, tree.GetCompilationUnitRoot().ErrorsAndWarnings().Length);
            }

            // check member count only if > 0
            if (memberCount > 0)
            {
                Assert.Equal(memberCount, tree.GetCompilationUnitRoot().Members.Count);
            }

            ParentChecker.CheckParents(tree.GetCompilationUnitRoot(), tree);
        }
예제 #12
0
 public LexicalTests()
 {
     _options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3);
     _binaryOptions = _options.WithExperimental(MessageID.IDS_FeatureBinaryLiteral);
     _underscoreOptions = _options.WithExperimental(MessageID.IDS_FeatureDigitSeparator);
     _binaryUnderscoreOptions = _options.WithExperimental(MessageID.IDS_FeatureBinaryLiteral, MessageID.IDS_FeatureDigitSeparator);
 }
 private void TestWithOptions(CSharpParseOptions options, string markup, params Action<object>[] expectedResults)
 {
     using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, options))
     {
         TestWithOptions(workspace, expectedResults);
     }
 }
예제 #14
0
        protected async Task TestExtractMethodAsync(
            string codeWithMarker,
            string expected,
            bool temporaryFailing = false,
            bool allowMovingDeclaration = true,
            bool dontPutOutOrRefOnStruct = true,
            CSharpParseOptions parseOptions = null)
        {
            using (var workspace = await TestWorkspace.CreateCSharpAsync(codeWithMarker, parseOptions: parseOptions))
            {
                var testDocument = workspace.Documents.Single();
                var subjectBuffer = testDocument.TextBuffer;

                var tree = await ExtractMethodAsync(
                    workspace, testDocument, allowMovingDeclaration: allowMovingDeclaration,
                    dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct);

                using (var edit = subjectBuffer.CreateEdit())
                {
                    edit.Replace(0, edit.Snapshot.Length, tree.ToFullString());
                    edit.Apply();
                }

                if (temporaryFailing)
                {
                    Assert.NotEqual(expected, subjectBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText());
                }
            }
        }
예제 #15
0
        public static SyntaxTree Generate(
            string text,
            string path,
            CSharpParseOptions parseOptions)
        {
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (parseOptions == null)
            {
                throw new ArgumentNullException(nameof(parseOptions));
            }

            var sourceText = SourceText.From(text, Encoding.UTF8);
            var syntaxTree = CSharpSyntaxTree.ParseText(sourceText,
                path: path,
                options: parseOptions);

            return syntaxTree;
        }
예제 #16
0
 private async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<object>[] expectedResults)
 {
     using (var workspace = await TestWorkspace.CreateCSharpAsync(markup, options))
     {
         await TestWithOptionsAsync(workspace, expectedResults);
     }
 }
예제 #17
0
파일: Rewriter.cs 프로젝트: jthelin/Nake
        SyntaxTree CreateTree(SyntaxNode root)
        {
            var options = new CSharpParseOptions(
                documentationMode: DocumentationMode.None,
                kind: SourceCodeKind.Script);

            return CSharpSyntaxTree.Create((CompilationUnitSyntax) root, options, tree.FilePath, Encoding.UTF8);
        }
 protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options)
 {
     var commentText = string.Format(@"/// <see cref=""{0}""/>", text);
     var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single();
     var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure();
     var attr = structure.DescendantNodes().OfType<XmlTextAttributeSyntax>().Single();
     return attr;
 }
 protected Task TestAsync(
     string code,
     string allCode,
     CSharpParseOptions options,
     params Tuple<string, string>[] expected)
 {
     return TestAsync(code, allCode, expected, options);
 }
 private CSharpSerializableParseOptions(SerializationInfo info, StreamingContext context)
 {
     _options = new CSharpParseOptions(
         languageVersion: (LanguageVersion)info.GetValue("LanguageVersion", typeof(LanguageVersion)),
         documentationMode: (DocumentationMode)info.GetValue("DocumentationMode", typeof(DocumentationMode)),
         kind: (SourceCodeKind)info.GetValue("Kind", typeof(SourceCodeKind)),
         preprocessorSymbols: info.GetArray<string>("PreprocessorSymbols"));
 }
예제 #21
0
 private static CSharpCompilation CreateCompilation(string code, SourceReferenceResolver sourceReferenceResolver = null)
 {
     var options = new CSharpCompilationOptions(
         OutputKind.DynamicallyLinkedLibrary,
         sourceReferenceResolver: sourceReferenceResolver ?? TestSourceReferenceResolver.Default);
     var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Interactive);
     return CreateCompilationWithMscorlib(code, options: options, parseOptions: parseOptions);
 }
 protected void Test(
     string code,
     string allCode,
     CSharpParseOptions options,
     params Tuple<string, string>[] expected)
 {
     Test(code, allCode, expected, options);
 }
예제 #23
0
 public LexicalTests()
 {
     _options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3);
     _options6 = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6);
     _binaryOptions = _options.WithLanguageVersion(LanguageVersion.CSharp7);
     _underscoreOptions = _options.WithLanguageVersion(LanguageVersion.CSharp7);
     _binaryUnderscoreOptions = _binaryOptions;
 }
 public static Task<TestWorkspace> CreateWorkspaceFromFilesAsync(
     string[] files,
     CSharpParseOptions[] parseOptions = null,
     CSharpCompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null)
 {
     return CreateWorkspaceFromFilesAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider);
 }
예제 #25
0
        public static Assembly BuildAndLoad(string[] sourcePaths, string[] referencePaths, string[] defines)
        {
            var assemblyName = Path.GetRandomFileName();
            var parseOption = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular, defines);
            var syntaxTrees = sourcePaths.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOption, file)).ToArray();
            var references = referencePaths.Select(file => MetadataReference.CreateFromFile(file)).ToArray();
            var referenceMaps = referencePaths.Select(file => Assembly.LoadFile(file))
                                              .ToDictionary(a => a.FullName, a => a);

            var compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: syntaxTrees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

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

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

                    foreach (var diagnostic in failures)
                    {
                        var line = diagnostic.Location.GetLineSpan();
                        Console.Error.WriteLine("{0}({1}): {2} {3}",
                            line.Path,
                            line.StartLinePosition.Line + 1,
                            diagnostic.Id,
                            diagnostic.GetMessage());
                    }
                    return null;
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);

                    // To load referenced assemblies, set customized resolved during using this assembly.

                    var currentDomain = AppDomain.CurrentDomain;
                    var resolveHandler = new ResolveEventHandler((sender, args) =>
                    {
                        Assembly assembly;
                        return referenceMaps.TryGetValue(args.Name, out assembly) ? assembly : null;
                    });

                    if (_lastResolveHandler != null)
                        currentDomain.AssemblyResolve -= _lastResolveHandler;
                    currentDomain.AssemblyResolve += resolveHandler;
                    _lastResolveHandler = resolveHandler;

                    return Assembly.Load(ms.ToArray());
                }
            }
        }
 protected async Task CheckResultAsync(string initial, string final, bool specialCaseSystem, CSharpParseOptions options = null)
 {
     using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(initial))
     {
         var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
         var newRoot = await (await OrganizingService.OrganizeAsync(document)).GetSyntaxRootAsync();
         Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
     }
 }
        public CSharpSerializableParseOptions(CSharpParseOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _options = options;
        }
예제 #28
0
 public LexicalTests()
 {
     _options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3);
     var binaryLiterals = new[] { new KeyValuePair<string, string>("binaryLiterals", "true") };
     var digitSeparators = new[] { new KeyValuePair<string, string>("digitSeparators", "true") };
     _binaryOptions = _options.WithFeatures(binaryLiterals);
     _underscoreOptions = _options.WithFeatures(digitSeparators);
     _binaryUnderscoreOptions = _options.WithFeatures(binaryLiterals.Concat(digitSeparators));
 }
예제 #29
0
 public void WithRootAndOptions_DummyTree()
 {
     var dummy = new CSharpSyntaxTree.DummySyntaxTree();
     var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}");
     var newOptions = new CSharpParseOptions();
     var newTree = dummy.WithRootAndOptions(newRoot, newOptions);
     Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString());
     Assert.Same(newOptions, newTree.Options);
 }
예제 #30
0
 protected void Check(string initial, string final, bool specialCaseSystem, CSharpParseOptions options = null)
 {
     using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(initial))
     {
         var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
         var newRoot = OrganizeImportsService.OrganizeImportsAsync(document, specialCaseSystem).Result.GetSyntaxRootAsync().Result;
         Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
     }
 }
예제 #31
0
        public static void TestSequencePoints(string markup, CSharpCompilationOptions compilationOptions, CSharpParseOptions parseOptions = null, string methodName = "")
        {
            int?     position;
            TextSpan?expectedSpan;
            string   source;

            MarkupTestFile.GetPositionAndSpan(markup, out source, out position, out expectedSpan);

            var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: compilationOptions, parseOptions: parseOptions);

            compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();

            var  pdb           = PdbValidation.GetPdbXml(compilation, qualifiedMethodName: methodName);
            bool hasBreakpoint = CheckIfSpanWithinSequencePoints(expectedSpan.GetValueOrDefault(), source, pdb);

            Assert.True(hasBreakpoint);
        }
예제 #32
0
    /// <summary>
    /// 编译dll
    /// </summary>
    /// <param name="rootpaths"></param>
    /// <param name="output"></param>
    static public bool BuildByRoslyn(string[] dlls,
                                     string[] codefiles,
                                     string output,
                                     bool isdebug     = false,
                                     bool isUseDefine = false)
    {
        if (Application.platform == RuntimePlatform.OSXEditor)
        {
            for (int i = 0; i < dlls.Length; i++)
            {
                dlls[i] = dlls[i].Replace("\\", "/");
            }

            for (int i = 0; i < codefiles.Length; i++)
            {
                codefiles[i] = codefiles[i].Replace("\\", "/");
            }

            output = output.Replace("\\", "/");
        }

        //添加语法树
        var Symbols = defineList;

        List <Microsoft.CodeAnalysis.SyntaxTree> codes = new List <Microsoft.CodeAnalysis.SyntaxTree>();
        CSharpParseOptions opa = null;

        if (isUseDefine)
        {
            opa = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: Symbols);
        }
        else
        {
            opa = new CSharpParseOptions(LanguageVersion.Latest);
        }

        foreach (var cs in codefiles)
        {
            //判断文件是否存在
            if (!File.Exists(cs))
            {
                continue;
            }
            //
            var content    = File.ReadAllText(cs);
            var syntaxTree = CSharpSyntaxTree.ParseText(content, opa, cs, Encoding.UTF8);
            codes.Add(syntaxTree);
        }

        //添加dll
        List <MetadataReference> assemblies = new List <MetadataReference>();

        foreach (var dll in dlls)
        {
            var metaref = MetadataReference.CreateFromFile(dll);
            if (metaref != null)
            {
                assemblies.Add(metaref);
            }
        }

        //创建目录
        var dir = Path.GetDirectoryName(output);

        Directory.CreateDirectory(dir);
        //编译参数
        CSharpCompilationOptions option = null;

        if (isdebug)
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Debug, warningLevel: 4, allowUnsafe: true);
        }
        else
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Release, warningLevel: 4, allowUnsafe: true);
        }

        //创建编译器代理
        var        assemblyname = Path.GetFileNameWithoutExtension(output);
        var        compilation  = CSharpCompilation.Create(assemblyname, codes, assemblies, option);
        EmitResult result       = null;

        if (!isdebug)
        {
            result = compilation.Emit(output);
        }
        else
        {
            var pdbPath     = output + ".pdb";
            var emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb,
                                              pdbFilePath: pdbPath);
            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    result = compilation.Emit(dllStream, pdbStream, options: emitOptions);

                    File.WriteAllBytes(output, dllStream.GetBuffer());
                    File.WriteAllBytes(pdbPath, pdbStream.GetBuffer());
                }
        }

        // 编译失败,提示
        if (!result.Success)
        {
            IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                         diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

            foreach (var diagnostic in failures)
            {
                Debug.LogError(diagnostic.ToString());
            }
        }

        return(result.Success);
    }
예제 #33
0
 internal static SourceWithMarkedNodes MarkedSource(string markedSource, string fileName = "", CSharpParseOptions options = null)
 {
     return(new SourceWithMarkedNodes(markedSource, s => Parse(s, fileName, options), s => (int)(SyntaxKind)typeof(SyntaxKind).GetField(s).GetValue(null)));
 }
        public void Test(CodeRefactoringProvider provider, string input, string output, int action = 0, bool expectErrors = false, CSharpParseOptions parseOptions = null)
        {
            string result = HomogenizeEol(RunContextAction(provider, HomogenizeEol(input), action, expectErrors, parseOptions));

            output = HomogenizeEol(output);
            bool passed = result == output;

            if (!passed)
            {
                Console.WriteLine("-----------Expected:");
                Console.WriteLine(output);
                Console.WriteLine("-----------Got:");
                Console.WriteLine(result);
            }
            Assert.AreEqual(output, result);
        }
예제 #35
0
 public static CSharpParseOptions WithNullablePublicOnly(this CSharpParseOptions options)
 {
     return(options.WithFeature("nullablePublicOnly"));
 }
예제 #36
0
        private static (string outputFile, CSharpCompilationOptions compilationOptions, CSharpParseOptions parseOptions) ParseArguments(IEnumerable <string> args)
        {
            var arguments = new Dictionary <string, string>();

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
            string outputFile = "";

            var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>()
            {
                // Ensure that specific warnings about assembly references are always suppressed.
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            };

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

            var parseOptions = new CSharpParseOptions(LanguageVersion.Latest);

            foreach (var arg in args)
            {
                var argParts = arg.Split(':');

                var argument = argParts[0].Replace("+", "").Replace("/", "");
                var value    = "";

                if (argParts.Count() > 1)
                {
                    value = argParts[1];
                }

                switch (argument)
                {
                case "target":
                    compilationOptions = compilationOptions.WithOutputKind(ParseTarget(value));
                    break;

                case "unsafe":
                    compilationOptions = compilationOptions.WithAllowUnsafe(true);
                    break;

                case "nowarn":
                    var warnings = value.Split(',');

                    if (warnings.Count() > 0)
                    {
                        compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings.Select(s => new KeyValuePair <string, ReportDiagnostic>(!s.StartsWith("CS") ? $"CS{s}" : s, ReportDiagnostic.Suppress)));
                    }
                    break;

                case "define":
                    var defines = value.Split(';');

                    if (defines.Count() > 0)
                    {
                        parseOptions = parseOptions.WithPreprocessorSymbols(defines);
                    }
                    break;

                case "optimize":
                    compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                    break;

                case "platform":
                    compilationOptions = compilationOptions.WithPlatform(ParsePlatform(value));
                    break;

                case "out":
                    outputFile = value;
                    break;
                }
            }

            return(outputFile, compilationOptions, parseOptions);
        }
예제 #37
0
        private async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null)
        {
            using (var workspace = await TestWorkspace.CreateCSharpAsync(markup, parseOptions))
            {
                var testDocument = workspace.Documents.Single();
                var position     = testDocument.CursorPosition.Value;
                var locationInfo = await LocationInfoGetter.GetInfoAsync(
                    workspace.CurrentSolution.Projects.Single().Documents.Single(),
                    position,
                    CancellationToken.None);

                Assert.Equal(expectedName, locationInfo.Name);
                Assert.Equal(expectedLineOffset, locationInfo.LineOffset);
            }
        }
예제 #38
0
        protected async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null)
        {
            using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
            var testDocument = workspace.Documents.Single();
            var namedSpans   = testDocument.AnnotatedSpans;

            var document = workspace.CurrentSolution.GetDocument(testDocument.Id);

            Assert.NotNull(document);

            var options = (await document.GetOptionsAsync(CancellationToken.None))
                          .WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, true);

            var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);

            var validator = new CSharpSelectionValidator(semanticDocument, namedSpans["b"].Single(), options);
            var result    = await validator.GetValidSelectionAsync(CancellationToken.None);

            Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded());

            if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion())
            {
                Assert.Equal(namedSpans["r"].Single(), result.FinalSpan);
            }
        }
예제 #39
0
        protected virtual NPath CompileCSharpAssemblyWithRoslyn(CompilerOptions options)
        {
            var parseOptions       = new CSharpParseOptions(preprocessorSymbols: options.Defines);
            var compilationOptions = new CSharpCompilationOptions(
                outputKind: options.OutputPath.FileName.EndsWith(".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default
                );
            // Default debug info format for the current platform.
            DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb;
            bool emitPdb = false;

            if (options.AdditionalArguments != null)
            {
                foreach (var option in options.AdditionalArguments)
                {
                    switch (option)
                    {
                    case "/unsafe":
                        compilationOptions = compilationOptions.WithAllowUnsafe(true);
                        break;

                    case "/optimize+":
                        compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                        break;

                    case "/debug:full":
                    case "/debug:pdbonly":
                        // Use platform's default debug info. This behavior is the same as csc.
                        emitPdb = true;
                        break;

                    case "/debug:portable":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.PortablePdb;
                        break;

                    case "/debug:embedded":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.Embedded;
                        break;
                    }
                }
            }
            var emitOptions = new EmitOptions(debugInformationFormat: debugType);
            var pdbPath     = (!emitPdb || debugType == DebugInformationFormat.Embedded) ? null : options.OutputPath.ChangeExtension(".pdb").ToString();

            var syntaxTrees = options.SourceFiles.Select(p =>
                                                         CSharpSyntaxTree.ParseText(
                                                             text: p.ReadAllText(),
                                                             options: parseOptions
                                                             )
                                                         );

            var compilation = CSharpCompilation.Create(
                assemblyName: options.OutputPath.FileNameWithoutExtension,
                syntaxTrees: syntaxTrees,
                references: options.References.Select(r => MetadataReference.CreateFromFile(r)),
                options: compilationOptions
                );

            var manifestResources = options.Resources.Select(r => {
                var fullPath = r.ToString();
                return(new ResourceDescription(
                           resourceName: Path.GetFileName(fullPath),
                           dataProvider: () => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
                           isPublic: true
                           ));
            });

            EmitResult result;

            using (var outputStream = File.Create(options.OutputPath.ToString()))
                using (var pdbStream = (pdbPath == null ? null : File.Create(pdbPath))) {
                    result = compilation.Emit(
                        peStream: outputStream,
                        pdbStream: pdbStream,
                        manifestResources: manifestResources,
                        options: emitOptions
                        );
                }

            var errors = new StringBuilder();

            if (result.Success)
            {
                return(options.OutputPath);
            }

            foreach (var diagnostic in result.Diagnostics)
            {
                errors.AppendLine(diagnostic.ToString());
            }
            throw new Exception("Roslyn compilation errors: " + errors);
        }
예제 #40
0
 public static CSharpParseOptions WithPEVerifyCompatFeature(this CSharpParseOptions options)
 {
     return(options.WithFeatures(options.Features.Concat(new[] { new KeyValuePair <string, string>("peverify-compat", "true") })));
 }
예제 #41
0
 protected virtual CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) =>
 ParseTree(text, options).GetCompilationUnitRoot();
예제 #42
0
 protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
 {
     return(SyntaxFactory.ParseSyntaxTree(text, options: options));
 }
예제 #43
0
 public static CSharpParseOptions WithLocalFunctionsFeature(this CSharpParseOptions options)
 {
     return(options);
 }
예제 #44
0
 protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options)
 {
     return(SyntaxFactory.ParseExpression(text, options: options));
 }
        protected string RunContextAction(CodeRefactoringProvider action, string input, int actionIndex = 0, bool expectErrors = false, CSharpParseOptions parseOptions = null)
        {
            Document doc;

            CSharpDiagnosticTestBase.TestWorkspace workspace;
            var actions = GetActions(action, input, out workspace, out doc, parseOptions);

            if (actions.Count < actionIndex)
            {
                Console.WriteLine("invalid input is:" + input);
            }
            var a = actions[actionIndex];

            foreach (var op in a.GetOperationsAsync(default(CancellationToken)).Result)
            {
                op.Apply(workspace, default(CancellationToken));
            }
            var result = workspace.CurrentSolution.GetDocument(doc.Id).GetTextAsync().Result.ToString();

            if (Environment.NewLine != "\r\n")
            {
                result = result.Replace("\r\n", Environment.NewLine);
            }
            return(result);
        }
예제 #46
0
        private static void MakeChange(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null)
        {
            string oldName = GetExpressionString(oldSyntaxKind);
            string newName = GetExpressionString(newSyntaxKind);

            string topLevelStatement = "x " + oldName + " y";
            // Be warned when changing the fields here
            var code    = @"class C { void m() {
                 " + topLevelStatement + @";
                }}";
            var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options);

            // Make the change to the node
            var newTree  = oldTree.WithReplaceFirst(oldName, newName);
            var treeNode = topLevel ? GetGlobalExpressionNode(newTree) : GetExpressionNode(newTree);

            Assert.Equal(treeNode.Kind(), newSyntaxKind);
        }
예제 #47
0
파일: Tester.cs 프로젝트: srufeng/ILSpy
        public static CompilerResults CompileCSharp(string sourceFileName, CSharpCompilerOptions flags = CSharpCompilerOptions.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);

            if (flags.HasFlag(CSharpCompilerOptions.UseRoslyn))
            {
                var parseOptions = new CSharpParseOptions(preprocessorSymbols: preprocessorSymbols.ToArray(), languageVersion: Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest);
                var syntaxTrees  = sourceFileNames.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, path: f));
                var compilation  = CSharpCompilation.Create(Path.GetFileNameWithoutExtension(sourceFileName),
                                                            syntaxTrees, defaultReferences.Value,
                                                            new CSharpCompilationOptions(
                                                                flags.HasFlag(CSharpCompilerOptions.Library) ? OutputKind.DynamicallyLinkedLibrary : OutputKind.ConsoleApplication,
                                                                platform: flags.HasFlag(CSharpCompilerOptions.Force32Bit) ? Platform.X86 : Platform.AnyCpu,
                                                                optimizationLevel: flags.HasFlag(CSharpCompilerOptions.Optimize) ? OptimizationLevel.Release : OptimizationLevel.Debug,
                                                                allowUnsafe: true,
                                                                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(CSharpCompilerOptions.UseMcs))
            {
                CompilerResults results = new CompilerResults(new TempFileCollection());
                results.PathToAssembly = outputFileName ?? Path.GetTempFileName();
                string testBasePath = RoundtripAssembly.TestDir;
                if (!Directory.Exists(testBasePath))
                {
                    Assert.Ignore($"Compilation with mcs ignored: test directory '{testBasePath}' needs to be checked out separately." + Environment.NewLine +
                                  $"git clone https://github.com/icsharpcode/ILSpy-tests \"{testBasePath}\"");
                }
                string mcsPath      = Path.Combine(testBasePath, @"mcs\2.6.4\bin\gmcs.bat");
                string otherOptions = " -unsafe -o" + (flags.HasFlag(CSharpCompilerOptions.Optimize) ? "+ " : "- ");

                if (flags.HasFlag(CSharpCompilerOptions.Library))
                {
                    otherOptions += "-t:library ";
                }
                else
                {
                    otherOptions += "-t:exe ";
                }

                if (flags.HasFlag(CSharpCompilerOptions.UseDebug))
                {
                    otherOptions += "-g ";
                }

                if (flags.HasFlag(CSharpCompilerOptions.Force32Bit))
                {
                    otherOptions += "-platform:x86 ";
                }
                else
                {
                    otherOptions += "-platform:anycpu ";
                }
                if (preprocessorSymbols.Count > 0)
                {
                    otherOptions += " \"-d:" + string.Join(";", preprocessorSymbols) + "\" ";
                }

                ProcessStartInfo info = new ProcessStartInfo(mcsPath);
                info.Arguments              = $"{otherOptions}-out:\"{Path.GetFullPath(results.PathToAssembly)}\" {string.Join(" ", sourceFileNames.Select(fn => '"' + Path.GetFullPath(fn) + '"'))}";
                info.RedirectStandardError  = true;
                info.RedirectStandardOutput = true;
                info.UseShellExecute        = false;

                Console.WriteLine($"\"{info.FileName}\" {info.Arguments}");

                Process process = Process.Start(info);

                var outputTask = process.StandardOutput.ReadToEndAsync();
                var errorTask  = process.StandardError.ReadToEndAsync();

                Task.WaitAll(outputTask, errorTask);
                process.WaitForExit();

                Console.WriteLine("output: " + outputTask.Result);
                Console.WriteLine("errors: " + errorTask.Result);
                Assert.AreEqual(0, process.ExitCode, "mcs failed");
                return(results);
            }
            else
            {
                var provider = new CSharpCodeProvider(new Dictionary <string, string> {
                    { "CompilerVersion", "v4.0" }
                });
                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable = !flags.HasFlag(CSharpCompilerOptions.Library);
                options.CompilerOptions    = "/unsafe /o" + (flags.HasFlag(CSharpCompilerOptions.Optimize) ? "+" : "-");
                options.CompilerOptions   += (flags.HasFlag(CSharpCompilerOptions.UseDebug) ? " /debug" : "");
                options.CompilerOptions   += (flags.HasFlag(CSharpCompilerOptions.Force32Bit) ? " /platform:anycpu32bitpreferred" : "");
                if (preprocessorSymbols.Count > 0)
                {
                    options.CompilerOptions += " /d:" + string.Join(";", preprocessorSymbols);
                }
                if (outputFileName != null)
                {
                    options.OutputAssembly = outputFileName;
                }

                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add("Microsoft.CSharp.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);
            }
        }
        private void ProcessRoute(GeneratorExecutionContext context, SyntaxReceiver receiver, CSharpParseOptions options)
        {
            Compilation routeAttributeCompilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(routeAttributeText, Encoding.UTF8), options));

            INamedTypeSymbol routeAttributeSymbol = routeAttributeCompilation.GetTypeByMetadataName("PlatformExtensions.RouteAttribute");

            // loop over the candidate fields, and keep the ones that are actually annotated
            List<(IMethodSymbol symbol, MethodDeclarationSyntax method)> routeAttributeSymbols = new ();
            bool isAsync = false;
            foreach (MethodDeclarationSyntax method in receiver.CandidateMethods)
            {
                SemanticModel routeModel = routeAttributeCompilation.GetSemanticModel(method.SyntaxTree);

                // Get the symbol being decleared by the field, and keep it if its annotated
                IMethodSymbol methodSymbol = routeModel.GetDeclaredSymbol(method);
                if (methodSymbol.GetAttributes().Any(ad => ad.AttributeClass.Equals(routeAttributeSymbol, SymbolEqualityComparer.Default)))
                {
                    routeAttributeSymbols.Add((methodSymbol, method));
                    if (!isAsync && method.ReturnType is GenericNameSyntax rt)
                    {
                        isAsync = rt.Identifier.ValueText == "Task";
                    }
                }
            }

            IEnumerable<IGrouping<INamedTypeSymbol, (IMethodSymbol symbol, MethodDeclarationSyntax method)>> classes = routeAttributeSymbols.GroupBy(f => f.symbol.ContainingType);
            if (classes.Count() != 1)
            {
                throw new Exception("One and only one application class should be defined");
            }

            var item = classes.FirstOrDefault();
            INamedTypeSymbol classSymbol = item.Key;
            string namespaceName = classSymbol.ContainingNamespace.ToDisplayString();

            var assembly = Assembly.GetExecutingAssembly();

            var fileName = "Ben.AspNetCore.PlatformExtensions.Application.cs";
            var stream = assembly.GetManifestResourceStream(fileName);
            if (stream == null) throw new FileNotFoundException("Cannot find mappings file.", fileName);

            // begin building the generated source
            StringBuilder source = new StringBuilder($@"
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using PlatformExtensions;

namespace {namespaceName}
{{
    public partial class {classSymbol.Name} : IHttpConnection
    {{
");
            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                source.Append(reader.ReadToEnd());
            }

            var snippetFileName = $"Ben.AspNetCore.PlatformExtensions.Application.{(isAsync? "Async" : "Sync")}.cs";
            stream = assembly.GetManifestResourceStream(snippetFileName);
            if (stream == null) throw new FileNotFoundException("Cannot find mappings file.", snippetFileName);

            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                source.Append(reader.ReadToEnd());
            }

            if (!isAsync)
            {
                source.Append(@"
        private void ProcessRequest(ref BufferWriter<WriterAdapter> writer)
        {
            var requestType = _requestType;
");
                foreach (var group in classes)
                {
                    var isFirst = true;
                    foreach (var methodData in group)
                    {
                        source.Append(@$"
            {(!isFirst ? "else " : "")}if (requestType == RequestType.{methodData.symbol.Name})
            {{
                {methodData.symbol.Name}_Routed(ref writer{(methodData.symbol.ReturnType.SpecialType == SpecialType.System_String ? "" : ", Writer")}{(methodData.method.ParameterList.Parameters.Count > 0 ? ", _queries" : "")});
        public void Initalize()
        {
            var context = new AspNet5Context();

            context.RuntimePath = GetRuntimePath();

            if (!ScanForProjects(context))
            {
                // No ASP.NET 5 projects found so do nothing
                _logger.WriteInformation("No ASP.NET 5 projects found");
                return;
            }

            var wh = new ManualResetEventSlim();

            _designTimeHostManager.Start(context.RuntimePath, context.HostId, port =>
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(new IPEndPoint(IPAddress.Loopback, port));

                var networkStream = new NetworkStream(socket);

                _logger.WriteInformation("Connected");

                context.Connection = new ProcessingQueue(networkStream, _logger);

                context.Connection.OnReceive += m =>
                {
                    var project = context.Projects[m.ContextId];

                    if (m.MessageType == "ProjectInformation")
                    {
                        var val = m.Payload.ToObject <ProjectMessage>();

                        project.Name               = val.Name;
                        project.GlobalJsonPath     = val.GlobalJsonPath;
                        project.Configurations     = val.Configurations;
                        project.Commands           = val.Commands;
                        project.ProjectSearchPaths = val.ProjectSearchPaths;

                        var unprocessed = project.ProjectsByFramework.Keys.ToList();

                        foreach (var frameworkData in val.Frameworks)
                        {
                            unprocessed.Remove(frameworkData.FrameworkName);

                            var frameworkProject = project.ProjectsByFramework.GetOrAdd(frameworkData.FrameworkName, framework =>
                            {
                                return(new FrameworkProject(project, framework));
                            });

                            var id = frameworkProject.ProjectId;

                            if (_workspace.CurrentSolution.ContainsProject(id))
                            {
                                continue;
                            }
                            else
                            {
                                var projectInfo = ProjectInfo.Create(
                                    id,
                                    VersionStamp.Create(),
                                    val.Name + "+" + frameworkData.ShortName,
                                    val.Name,
                                    LanguageNames.CSharp);

                                _workspace.AddProject(projectInfo);
                                context.WorkspaceMapping[id] = frameworkProject;
                            }

                            lock (frameworkProject.PendingProjectReferences)
                            {
                                var reference = new Microsoft.CodeAnalysis.ProjectReference(id);

                                foreach (var referenceId in frameworkProject.PendingProjectReferences)
                                {
                                    _workspace.AddProjectReference(referenceId, reference);
                                }

                                frameworkProject.PendingProjectReferences.Clear();
                            }
                        }

                        // Remove old projects
                        foreach (var frameworkName in unprocessed)
                        {
                            FrameworkProject frameworkProject;
                            project.ProjectsByFramework.TryRemove(frameworkName, out frameworkProject);
                            _workspace.RemoveProject(frameworkProject.ProjectId);
                        }
                    }
                    // This is where we can handle messages and update the
                    // language service
                    else if (m.MessageType == "References")
                    {
                        // References as well as the dependency graph information
                        var val = m.Payload.ToObject <ReferencesMessage>();

                        var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
                        var projectId        = frameworkProject.ProjectId;

                        var metadataReferences = new List <MetadataReference>();
                        var projectReferences  = new List <Microsoft.CodeAnalysis.ProjectReference>();

                        var removedFileReferences    = frameworkProject.FileReferences.ToDictionary(p => p.Key, p => p.Value);
                        var removedRawReferences     = frameworkProject.RawReferences.ToDictionary(p => p.Key, p => p.Value);
                        var removedProjectReferences = frameworkProject.ProjectReferences.ToDictionary(p => p.Key, p => p.Value);

                        foreach (var file in val.FileReferences)
                        {
                            if (removedFileReferences.Remove(file))
                            {
                                continue;
                            }

                            var metadataReference = _metadataFileReferenceCache.GetMetadataReference(file);
                            frameworkProject.FileReferences[file] = metadataReference;
                            metadataReferences.Add(metadataReference);
                        }

                        foreach (var rawReference in val.RawReferences)
                        {
                            if (removedRawReferences.Remove(rawReference.Key))
                            {
                                continue;
                            }

                            var metadataReference = MetadataReference.CreateFromImage(rawReference.Value);
                            frameworkProject.RawReferences[rawReference.Key] = metadataReference;
                            metadataReferences.Add(metadataReference);
                        }

                        foreach (var projectReference in val.ProjectReferences)
                        {
                            if (removedProjectReferences.Remove(projectReference.Path))
                            {
                                continue;
                            }

                            var projectReferenceContextId = context.ProjectContextMapping[projectReference.Path];

                            var referencedProject = context.Projects[projectReferenceContextId];

                            var referencedFrameworkProject = referencedProject.ProjectsByFramework.GetOrAdd(projectReference.Framework.FrameworkName,
                                                                                                            framework =>
                            {
                                return(new FrameworkProject(referencedProject, framework));
                            });

                            var projectReferenceId = referencedFrameworkProject.ProjectId;

                            if (_workspace.CurrentSolution.ContainsProject(projectReferenceId))
                            {
                                projectReferences.Add(new Microsoft.CodeAnalysis.ProjectReference(projectReferenceId));
                            }
                            else
                            {
                                lock (referencedFrameworkProject.PendingProjectReferences)
                                {
                                    referencedFrameworkProject.PendingProjectReferences.Add(projectId);
                                }
                            }

                            referencedFrameworkProject.ProjectDependeees[project.Path] = projectId;

                            frameworkProject.ProjectReferences[projectReference.Path] = projectReferenceId;
                        }

                        foreach (var reference in metadataReferences)
                        {
                            _workspace.AddMetadataReference(projectId, reference);
                        }

                        foreach (var projectReference in projectReferences)
                        {
                            _workspace.AddProjectReference(projectId, projectReference);
                        }

                        foreach (var pair in removedProjectReferences)
                        {
                            _workspace.RemoveProjectReference(projectId, new Microsoft.CodeAnalysis.ProjectReference(pair.Value));
                            frameworkProject.ProjectReferences.Remove(pair.Key);

                            // TODO: Update the dependee's list
                        }

                        foreach (var pair in removedFileReferences)
                        {
                            _workspace.RemoveMetadataReference(projectId, pair.Value);
                            frameworkProject.FileReferences.Remove(pair.Key);
                        }

                        foreach (var pair in removedRawReferences)
                        {
                            _workspace.RemoveMetadataReference(projectId, pair.Value);
                            frameworkProject.RawReferences.Remove(pair.Key);
                        }
                    }
                    else if (m.MessageType == "CompilerOptions")
                    {
                        // Configuration and compiler options
                        var val = m.Payload.ToObject <CompilationOptionsMessage>();

                        var projectId = project.ProjectsByFramework[val.Framework.FrameworkName].ProjectId;

                        var options = val.CompilationOptions.CompilationOptions;

                        var specificDiagnosticOptions = options.SpecificDiagnosticOptions
                                                        .ToDictionary(p => p.Key, p => (ReportDiagnostic)p.Value);

                        var csharpOptions = new CSharpCompilationOptions(
                            outputKind: (OutputKind)options.OutputKind,
                            optimizationLevel: (OptimizationLevel)options.OptimizationLevel,
                            platform: (Platform)options.Platform,
                            generalDiagnosticOption: (ReportDiagnostic)options.GeneralDiagnosticOption,
                            warningLevel: options.WarningLevel,
                            allowUnsafe: options.AllowUnsafe,
                            concurrentBuild: options.ConcurrentBuild,
                            specificDiagnosticOptions: specificDiagnosticOptions
                            );

                        var parseOptions = new CSharpParseOptions(val.CompilationOptions.LanguageVersion,
                                                                  preprocessorSymbols: val.CompilationOptions.Defines);

                        _workspace.SetCompilationOptions(projectId, csharpOptions);
                        _workspace.SetParseOptions(projectId, parseOptions);
                    }
                    else if (m.MessageType == "Sources")
                    {
                        // The sources to feed to the language service
                        var val = m.Payload.ToObject <SourcesMessage>();

                        var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
                        var projectId        = frameworkProject.ProjectId;

                        var unprocessed = new HashSet <string>(frameworkProject.Documents.Keys);

                        foreach (var file in val.Files)
                        {
                            if (unprocessed.Remove(file))
                            {
                                continue;
                            }

                            using (var stream = File.OpenRead(file))
                            {
                                var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                                var id         = DocumentId.CreateNewId(projectId);
                                var version    = VersionStamp.Create();

                                frameworkProject.Documents[file] = id;

                                var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));
                                _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                            }
                        }

                        foreach (var file in unprocessed)
                        {
                            var docId = frameworkProject.Documents[file];
                            frameworkProject.Documents.Remove(file);
                            _workspace.RemoveDocument(docId);
                        }

                        frameworkProject.Loaded = true;
                    }

                    if (project.ProjectsByFramework.Values.All(p => p.Loaded))
                    {
                        wh.Set();
                    }
                };

                // Start the message channel
                context.Connection.Start();

                // Initialize the ASP.NET 5 projects
                Initialize(context);
            });

            wh.Wait();

            // TODO: Subscribe to _workspace changes and update DTH
            //Thread.Sleep(5000);

            //_workspace._workspaceChanged += (sender, e) =>
            //{
            //    var arg = e;
            //    var kind = e.Kind;

            //    if (e.Kind == _workspaceChangeKind.DocumentChanged ||
            //        e.Kind == _workspaceChangeKind.DocumentAdded ||
            //        e.Kind == _workspaceChangeKind.DocumentRemoved)
            //    {
            //        var frameworkProject = context._workspaceMapping[e.ProjectId];

            //        TriggerDependeees(context, frameworkProject.ProjectState.Path);
            //    }
            //};
        }
예제 #50
0
        CSharpCompilation IResolveReference.GetReferenceResolvedCompilation(CodeGenConfig config)
        {
            string path         = Path.GetDirectoryName(config.Project);
            string projFilePath = config.Project;
            string name         = Path.GetFileNameWithoutExtension(projFilePath);

            string systemDllPath = config.SystemDllPath;

            List <string> preprocessors = new List <string>();

            preprocessors.Add("__LUA__");

            //存储引用refs
            List <MetadataReference> refs = new List <MetadataReference>();

            List <string> files = new List <string>();
            Dictionary <string, string> refByNames = new Dictionary <string, string>();
            Dictionary <string, string> refByPaths = new Dictionary <string, string>();

            //从csproj文件中解析XML获取引用
            if (projFilePath.EndsWith(".csproj"))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(projFilePath);

                //查找ItemGroup下的Reference节点
                var nodes = SelectNodes(xmlDoc, "ItemGroup", "Reference");
                foreach (XmlElement node in nodes)
                {
                    var aliasesNode = SelectSingleNode(node, "Aliases");
                    var pathNode    = SelectSingleNode(node, "HintPath");
                    if (null != pathNode && !refByPaths.ContainsKey(pathNode.InnerText))
                    {
                        if (null != aliasesNode)
                        {
                            refByPaths.Add(pathNode.InnerText, aliasesNode.InnerText);
                        }
                        else
                        {
                            refByPaths.Add(pathNode.InnerText, "global");
                        }
                    }
                    else
                    {
                        string val = node.GetAttribute("Include");
                        if (!string.IsNullOrEmpty(val) && !refByNames.ContainsKey(val))
                        {
                            if (null != aliasesNode)
                            {
                                refByNames.Add(val, aliasesNode.InnerText);
                            }
                            else
                            {
                                refByNames.Add(val, "global");
                            }
                        }
                    }
                }

                string prjOutputDir = "bin/Debug/";
                nodes = SelectNodes(xmlDoc, "PropertyGroup");
                foreach (XmlElement node in nodes)
                {
                    string condition = node.GetAttribute("Condition");
                    var    defNode   = SelectSingleNode(node, "DefineConstants");
                    var    pathNode  = SelectSingleNode(node, "OutputPath");
                    if (null != defNode && null != pathNode)
                    {
                        string text = defNode.InnerText.Trim();
                        if (condition.IndexOf("Debug") > 0 || condition.IndexOf("Release") < 0 && (text == "DEBUG" || text.IndexOf(";DEBUG;") > 0 || text.StartsWith("DEBUG;") || text.EndsWith(";DEBUG")))
                        {
                            preprocessors.AddRange(text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                            prjOutputDir = pathNode.InnerText.Trim();
                            break;
                        }
                    }
                }

                //查找ItemGroup下的ProjectReference节点
                nodes = SelectNodes(xmlDoc, "ItemGroup", "ProjectReference");
                foreach (XmlElement node in nodes)
                {
                    string val      = node.GetAttribute("Include");
                    string prjFile  = Path.Combine(path, val.Trim());
                    var    nameNode = SelectSingleNode(node, "Name");
                    if (null != prjFile && null != nameNode)
                    {
                        string prjName       = nameNode.InnerText.Trim();
                        string prjOutputFile = ParseProjectOutputFile(prjFile, prjName);
                        string fileName      = Path.Combine(prjOutputDir, prjOutputFile);
                        if (!refByPaths.ContainsKey(fileName))
                        {
                            refByPaths.Add(fileName, "global");
                        }
                    }
                }
                nodes = SelectNodes(xmlDoc, "ItemGroup", "Compile");
                foreach (XmlElement node in nodes)
                {
                    string val = node.GetAttribute("Include");
                    if (!string.IsNullOrEmpty(val) && val.EndsWith(".cs") && !files.Contains(val))
                    {
                        files.Add(val);
                    }
                }

                //确保常用的Assembly被引用
                if (!refByNames.ContainsKey("mscorlib"))
                {
                    refByNames.Add("mscorlib", "global");
                }
                if (!refByNames.ContainsKey("System"))
                {
                    refByNames.Add("System", "global");
                }
                if (!refByNames.ContainsKey("System.Core"))
                {
                    refByNames.Add("System.Core", "global");
                }

                if (string.IsNullOrEmpty(systemDllPath))//默认
                {
                    //用反射添加具体的类名引用
                    foreach (var pair in refByNames)
                    {
#pragma warning disable 618
                        Assembly assembly = Assembly.LoadWithPartialName(pair.Key);
#pragma warning restore 618
                        if (null != assembly)
                        {
                            var arr = System.Collections.Immutable.ImmutableArray.Create(pair.Value);
                            Console.WriteLine(pair.Key);
                            refs.Add(MetadataReference.CreateFromFile(assembly.Location, new MetadataReferenceProperties(MetadataImageKind.Assembly, arr)));
                        }
                    }
                }
                //需配置SystemDLLPath
                else
                {
                    foreach (var pair in refByNames)
                    {
                        string file = Path.Combine(systemDllPath, pair.Key) + ".dll";
                        var    arr  = System.Collections.Immutable.ImmutableArray.Create(pair.Value);
                        refs.Add(MetadataReference.CreateFromFile(file, new MetadataReferenceProperties(MetadataImageKind.Assembly, arr)));
                    }
                }

                //从文件路径添加DLL引用
                foreach (var pair in refByPaths)
                {
                    string fullPath = Path.Combine(path, pair.Key);
                    var    arr      = System.Collections.Immutable.ImmutableArray.Create(pair.Value);
                    Console.WriteLine(fullPath);


                    if (!File.Exists(fullPath))
                    {
                        Console.WriteLine(fullPath + "is not exsit!");
                        continue;
                    }

                    refs.Add(MetadataReference.CreateFromFile(fullPath, new MetadataReferenceProperties(MetadataImageKind.Assembly, arr)));
                }

                //手动构造Complation对象
                CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
                compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
                CSharpCompilation compilation = CSharpCompilation.Create(name);
                compilation = compilation.WithOptions(compilationOptions);

                //手动添加Reference
                compilation = compilation.AddReferences(refs.ToArray());

                //手动添加SyntaxTree
                foreach (string itemFile in files)
                {
                    string filePath = Path.Combine(path, itemFile);
                    string fileName = Path.GetFileNameWithoutExtension(filePath);

                    if (!File.Exists(filePath))
                    {
                        Console.WriteLine(filePath + "is not exsit!");
                        continue;
                    }

                    CSharpParseOptions options = new CSharpParseOptions();
                    options = options.WithPreprocessorSymbols(preprocessors);
                    options = options.WithFeatures(new Dictionary <string, string> {
                        { "IOperation", "true" }
                    });
                    SyntaxTree tree = CSharpSyntaxTree.ParseText(File.ReadAllText(filePath), options, filePath);
                    compilation = compilation.AddSyntaxTrees(tree);
                }
                return(compilation);
            }
            return(null);
        }
예제 #51
0
 public CompilationUnitSyntax ParseFile(string text, CSharpParseOptions parseOptions = null) =>
 SyntaxFactory.ParseCompilationUnit(text, options: parseOptions);
        static List <CodeAction> GetActions(CodeRefactoringProvider action, string input, out CSharpDiagnosticTestBase.TestWorkspace workspace, out Document doc, CSharpParseOptions parseOptions = null)
        {
            TextSpan selectedSpan;
            TextSpan markedSpan;
            string   text = ParseText(input, out selectedSpan, out markedSpan);

            workspace = new CSharpDiagnosticTestBase.TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            if (parseOptions == null)
            {
                parseOptions = new CSharpParseOptions(
                    LanguageVersion.CSharp6,
                    DocumentationMode.Diagnose | DocumentationMode.Parse,
                    SourceCodeKind.Regular,
                    ImmutableArray.Create("DEBUG", "TEST")
                    );
            }
            workspace.Options = workspace.Options
                                .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, true)
                                .WithChangedOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.CSharp, true)
                                .WithChangedOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.CSharp, true);
            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "TestProject",
                               "TestProject",
                               LanguageNames.CSharp,
                               null,
                               null,
                               new CSharpCompilationOptions(
                                   OutputKind.DynamicallyLinkedLibrary,
                                   false,
                                   "",
                                   "",
                                   "Script",
                                   null,
                                   OptimizationLevel.Debug,
                                   false,
                                   true
                                   ),
                               parseOptions,
                               new[] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create()))
                    )
            },
                               null,
                               DiagnosticTestBase.DefaultMetadataReferences
                               )
                           );
            doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId);
            var actions = new List <CodeAction>();
            var context = new CodeRefactoringContext(doc, selectedSpan, actions.Add, default(CancellationToken));

            action.ComputeRefactoringsAsync(context).Wait();
            if (markedSpan.Start > 0)
            {
                foreach (var nra in actions.OfType <NRefactoryCodeAction>())
                {
                    Assert.AreEqual(markedSpan, nra.TextSpan, "Activation span does not match.");
                }
            }
            return(actions);
        }
예제 #53
0
        private static void ParseAndValidate(string text, Action <SyntaxTree> validator, CSharpParseOptions options = null)
        {
            var oldTree = SyntaxFactory.ParseSyntaxTree(text);

            validator(oldTree);
        }
예제 #54
0
 protected virtual SyntaxTree ParseTree(string text, CSharpParseOptions options) => SyntaxFactory.ParseSyntaxTree(text, options);
예제 #55
0
 public static CSharpParseOptions WithStrictFeature(this CSharpParseOptions options)
 {
     return(options.WithFeatures(options.Features.Concat(new[] { new KeyValuePair <string, string>("strict", "true") })));
 }
 public void Test <T>(string input, string output, int action = 0, bool expectErrors = false, CSharpParseOptions parseOptions = null)
     where T : CodeRefactoringProvider, new()
 {
     Test(new T(), input, output, action, expectErrors, parseOptions);
 }
        private static void AssertExtent(string code, int pos, bool isSignificant, int start, int length, CSharpParseOptions options)
        {
            using var workspace = TestWorkspace.CreateCSharp(code, options);
            var buffer = workspace.Documents.First().GetTextBuffer();

            var provider = Assert.IsType <TextStructureNavigatorProvider>(
                workspace.GetService <ITextStructureNavigatorProvider>(ContentTypeNames.CSharpContentType));

            var navigator = provider.CreateTextStructureNavigator(buffer);

            var extent = navigator.GetExtentOfWord(new SnapshotPoint(buffer.CurrentSnapshot, pos));

            Assert.Equal(isSignificant, extent.IsSignificant);

            var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, start, length);

            Assert.Equal(expectedSpan, extent.Span);
        }
예제 #58
0
 public static CSharpParseOptions WithFeature(this CSharpParseOptions options, string feature, string value = "true")
 {
     return(options.WithFeatures(options.Features.Concat(new[] { new KeyValuePair <string, string>(feature, value) })));
 }
예제 #59
0
        public void PortablePdb_DeterministicCompilation(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
        {
            var sourceOne = Parse(@"
using System;

class MainType
{
    public static void Main()
    {
        Console.WriteLine();
    }
}
", options: parseOptions, encoding: Encoding.UTF8);

            var sourceTwo = Parse(@"
class TypeTwo
{
}", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));

            var sourceThree = Parse(@"
class TypeThree
{
}", options: parseOptions, encoding: Encoding.UTF7);

            var referenceOneCompilation = CreateCompilation(
                @"public struct StructWithReference
{
    string PrivateData;
}
public struct StructWithValue
{
    int PrivateData;
}", options: TestOptions.DebugDll);

            var referenceTwoCompilation = CreateCompilation(
                @"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);

            using var referenceOne = TestMetadataReferenceInfo.Create(
                      referenceOneCompilation,
                      fullPath: "abcd.dll",
                      emitOptions: emitOptions);

            using var referenceTwo = TestMetadataReferenceInfo.Create(
                      referenceTwoCompilation,
                      fullPath: "efgh.dll",
                      emitOptions: emitOptions);

            var testSource = new[] { sourceOne, sourceTwo, sourceThree };

            TestDeterministicCompilationCSharp(parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), testSource, compilationOptions, emitOptions, referenceOne, referenceTwo);
        }
예제 #60
0
 public static CSharpParseOptions WithTuplesFeature(this CSharpParseOptions options)
 {
     return(options);
 }