当前位置: 首页>>代码示例>>C#>>正文


C# CSharpParseOptions类代码示例

本文整理汇总了C#中CSharpParseOptions的典型用法代码示例。如果您正苦于以下问题:C# CSharpParseOptions类的具体用法?C# CSharpParseOptions怎么用?C# CSharpParseOptions使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


CSharpParseOptions类属于命名空间,在下文中一共展示了CSharpParseOptions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Generate

        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;
        }
开发者ID:phinq19,项目名称:git_example,代码行数:27,代码来源:SyntaxTreeGenerator.cs

示例2: TestExtractMethodAsync

        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());
                }
            }
        }
开发者ID:GuilhermeSa,项目名称:roslyn,代码行数:33,代码来源:ExtractMethodBase.cs

示例3: ProcessCode

        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,
            };
        }
开发者ID:codespare,项目名称:RoslynClrHeapAllocationAnalyzer,代码行数:35,代码来源:AllocationAnalyzerTests.cs

示例4: GetCompilation

        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;
        }
开发者ID:nul800sebastiaan,项目名称:Zbu.ModelsBuilder,代码行数:33,代码来源:Compiler.cs

示例5: BuildFull

        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;
        }
开发者ID:cupsster,项目名称:Unity3D.IncrementalCompiler,代码行数:32,代码来源:Compiler.cs

示例6: TestWithOptionsAsync

 private async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<object>[] expectedResults)
 {
     using (var workspace = await TestWorkspace.CreateCSharpAsync(markup, options))
     {
         await TestWithOptionsAsync(workspace, expectedResults);
     }
 }
开发者ID:jkotas,项目名称:roslyn,代码行数:7,代码来源:SemanticQuickInfoSourceTests.cs

示例7: LexicalTests

 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);
 }
开发者ID:,项目名称:,代码行数:7,代码来源:

示例8: CompilationChain_SystemObject_NotEquals

        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"));
        }
开发者ID:JRobertGit,项目名称:roslyn,代码行数:27,代码来源:CommandLineScriptTests.cs

示例9: Test

        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);
            }
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:33,代码来源:AbstractCSharpClassifierTests.cs

示例10: CompileAndVerifyIL

        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;
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:34,代码来源:CodeGenDynamicTests.cs

示例11: ParseAndRoundTripping

        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);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:26,代码来源:RoundTrippingTests.cs

示例12: CompilationChain_SystemObject_NotEquals

        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"));
        }
开发者ID:hbarve1,项目名称:roslyn,代码行数:27,代码来源:CommandLineScriptTests.cs

示例13: TestWithOptions

 private void TestWithOptions(CSharpParseOptions options, string markup, params Action<object>[] expectedResults)
 {
     using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, options))
     {
         TestWithOptions(workspace, expectedResults);
     }
 }
开发者ID:reudismam,项目名称:roslyn,代码行数:7,代码来源:SemanticQuickInfoSourceTests.cs

示例14: TestWithOptions

        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);
                }
            }
        }
开发者ID:stephenbreen,项目名称:roslyn,代码行数:34,代码来源:SemanticQuickInfoSourceTests.cs

示例15: MyScriptCompiler

        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();
        }
开发者ID:2asoft,项目名称:SpaceEngineers,代码行数:26,代码来源:MyScriptCompiler.cs


注:本文中的CSharpParseOptions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。