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


C# CSharp.CSharpCompilation类代码示例

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


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

示例1: 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

示例2: NamespaceScopeBuilder

        public NamespaceScopeBuilder(CSharpCompilation compilation)
        {
            this.compilation = compilation;

            buildNamespaceScopes = BuildNamespaceScopes;
            buildNamespaceOrTypeString = BuildNamespaceOrTypeString;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:7,代码来源:NamespaceScopeBuilder.cs

示例3: SetScriptInitializerReturnType

        private static void SetScriptInitializerReturnType(
            CSharpCompilation compilation,
            SynthesizedInteractiveInitializerMethod scriptInitializer,
            ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> fieldInitializers,
            DiagnosticBag diagnostics)
        {
            bool isAsync = scriptInitializer.IsSubmissionInitializer && fieldInitializers.Any(i => i.Any(ContainsAwaitsVisitor.ContainsAwait));
            var resultType = scriptInitializer.ResultType;
            TypeSymbol returnType;

            if ((object)resultType == null)
            {
                Debug.Assert(!isAsync);
                returnType = compilation.GetSpecialType(SpecialType.System_Void);
            }
            else if (!isAsync)
            {
                returnType = resultType;
            }
            else
            {
                var taskT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T);
                var useSiteDiagnostic = taskT.GetUseSiteDiagnostic();
                if (useSiteDiagnostic != null)
                {
                    diagnostics.Add(useSiteDiagnostic, NoLocation.Singleton);
                }
                returnType = taskT.Construct(resultType);
            }

            scriptInitializer.SetReturnType(isAsync, returnType);
        }
开发者ID:daking2014,项目名称:roslyn,代码行数:32,代码来源:Binder_Initializers.cs

示例4: RoslynCompiledItem

        public RoslynCompiledItem(Project project, CSharpCompilation
            compilation)
        {
            Project = project;

            Compilation = compilation;
        }
开发者ID:pzielinski86,项目名称:RuntimeTestCoverage,代码行数:7,代码来源:RoslynCompiledItem.cs

示例5: Analyze

        public static MultiDictionary<Symbol, CSharpSyntaxNode> Analyze(CSharpCompilation compilation, MethodSymbol method, BoundNode node)
        {
            var emptyStructs = new CaptureWalkerEmptyStructTypeCache();
            var initiallyAssignedVariables = UnassignedVariablesWalker.Analyze(compilation, method, node, emptyStructs);

            var walker = new IteratorAndAsyncCaptureWalker(compilation, method, node, emptyStructs, initiallyAssignedVariables);

            bool badRegion = false;
            walker.Analyze(ref badRegion);
            Debug.Assert(!badRegion);

            var result = walker.variablesCaptured;


            if (!method.IsStatic && method.ContainingType.TypeKind == TypeKind.Struct)
            {
                // It is possible that the enclosing method only *writes* to the enclosing struct, but in that
                // case it should be considered captured anyway so that we have a proxy for it to write to.
                result.Add(method.ThisParameter, node.Syntax);
            }

            foreach (var variable in result.Keys.ToArray()) // take a snapshot, as we are modifying the underlying multidictionary
            {
                var local = variable as LocalSymbol;
                if ((object)local != null && local.RefKind != RefKind.None)
                {
                    walker.AddSpillsForRef(walker.refLocalInitializers[local], result[local]);
                }
            }

            walker.Free();
            return result;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:33,代码来源:IteratorAndAsyncCaptureWalker.cs

示例6: RegionAnalysisContext

        /// <summary>
        /// Construct context
        /// </summary>
        public RegionAnalysisContext(CSharpCompilation compilation, Symbol member, BoundNode boundNode, BoundNode firstInRegion, BoundNode lastInRegion)
        {
            this.Compilation = compilation;
            this.Member = member;
            this.BoundNode = boundNode;
            this.FirstInRegion = firstInRegion;
            this.LastInRegion = lastInRegion;
            this.Failed =
                boundNode == null ||
                firstInRegion == null ||
                lastInRegion == null ||
                firstInRegion.Syntax.SpanStart > lastInRegion.Syntax.Span.End;

            if (!this.Failed && ReferenceEquals(firstInRegion, lastInRegion))
            {
                switch (firstInRegion.Kind)
                {
                    case BoundKind.NamespaceExpression:
                    case BoundKind.TypeExpression:

                        // Some bound nodes are still considered to be invalid for flow analysis
                        this.Failed = true;
                        break;
                }
            }
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:29,代码来源:RegionAnalysisContext.cs

示例7: BindRegularCSharpFieldInitializers

        /// <summary>
        /// In regular C#, all field initializers are assignments to fields and the assigned expressions
        /// may not reference instance members.
        /// </summary>
        private static void BindRegularCSharpFieldInitializers(
            CSharpCompilation compilation,
            ImmutableArray<FieldInitializers> initializers,
            ArrayBuilder<BoundInitializer> boundInitializers,
            DiagnosticBag diagnostics,
            bool generateDebugInfo,
            out ConsList<Imports> firstDebugImports)
        {
            firstDebugImports = null;

            foreach (FieldInitializers siblingInitializers in initializers)
            {
                var infos = ArrayBuilder<FieldInitializerInfo>.GetInstance(); // Exact size is not known up front.
                var locals = GetFieldInitializerInfos(compilation, siblingInitializers, infos, generateDebugInfo, ref firstDebugImports);

                ArrayBuilder<BoundInitializer> initializersBuilder = locals.IsDefaultOrEmpty ? boundInitializers : ArrayBuilder<BoundInitializer>.GetInstance(infos.Count);

                foreach (var info in infos)
                {
                    BoundFieldInitializer boundInitializer = BindFieldInitializer(info.Binder, info.Initializer.Field, info.EqualsValue, diagnostics);
                    initializersBuilder.Add(boundInitializer);
                }

                Debug.Assert(locals.IsDefaultOrEmpty == (initializersBuilder == boundInitializers));
                if (!locals.IsDefaultOrEmpty)
                {
                    boundInitializers.Add(new BoundInitializationScope((CSharpSyntaxNode)siblingInitializers.TypeDeclarationSyntax.GetSyntax(),
                                                                       locals, initializersBuilder.ToImmutableAndFree()));
                }

                infos.Free();
            }
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:37,代码来源:Binder_Initializers.cs

示例8: CompilationContext

        public CompilationContext(CSharpCompilation compilation,
                                  CompilationProjectContext compilationContext,
                                  IEnumerable<IMetadataReference> incomingReferences,
                                  Func<IList<ResourceDescriptor>> resourcesResolver)
        {
            Project = compilationContext;
            Modules = new List<ICompileModule>();

            _resourcesResolver = resourcesResolver;

            var projectContext = new ProjectContext
            {
                Name = compilationContext.Target.Name,
                ProjectDirectory = compilationContext.ProjectDirectory,
                ProjectFilePath = compilationContext.ProjectFilePath,
                TargetFramework = compilationContext.Target.TargetFramework,
                Version = compilationContext.Version?.ToString(),
                Configuration = compilationContext.Target.Configuration
            };

            _beforeCompileContext = new BeforeCompileContext(
                compilation,
                projectContext,
                ResolveResources,
                () => new List<Diagnostic>(),
                () => new List<IMetadataReference>(incomingReferences)
             );
        }
开发者ID:rajeevkb,项目名称:dnx,代码行数:28,代码来源:CompilationContext.cs

示例9: IsNonAgileFieldAccess

        /// <remarks>
        /// Based on OutputContext::IsNonAgileField.
        /// </remarks>
        internal static bool IsNonAgileFieldAccess(BoundFieldAccess fieldAccess, CSharpCompilation compilation)
        {
            // Warn if taking the address of a non-static field with a receiver other than this (possibly cast)
            // and a type that descends from System.MarshalByRefObject.
            if (IsInstanceFieldAccessWithNonThisReceiver(fieldAccess))
            {
                // NOTE: We're only trying to produce a warning, so there's no point in producing an
                // error if the well-known type we need for the check is missing.
                NamedTypeSymbol marshalByRefType = compilation.GetWellKnownType(WellKnownType.System_MarshalByRefObject);

                TypeSymbol baseType = fieldAccess.FieldSymbol.ContainingType;
                while ((object)baseType != null)
                {
                    if (baseType == marshalByRefType)
                    {
                        return true;
                    }

                    // NOTE: We're only trying to produce a warning, so there's no point in producing a
                    // use site diagnostic if we can't walk up the base type hierarchy.
                    baseType = baseType.BaseTypeNoUseSiteDiagnostics;
                }
            }

            return false;
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:29,代码来源:DiagnosticsPass_Warnings.cs

示例10: CSharpScriptCompilationInfo

        internal CSharpScriptCompilationInfo(CSharpCompilation previousCompilationOpt, Type returnType, Type globalsType)
            : base(returnType, globalsType)
        {
            Debug.Assert(previousCompilationOpt == null || previousCompilationOpt.HostObjectType == globalsType);

            PreviousScriptCompilation = previousCompilationOpt;
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:7,代码来源:CSharpScriptCompilationInfo.cs

示例11: Compile

        /// <summary>
        /// Creates a fresh new compilation of source files.
        /// Does not load any assembly.
        /// </summary>
        /// <returns>Success if no compilation erros were encountered.</returns>
        public bool Compile()
        {
            if (SourceFiles.Count == 0 && SourceTexts.Count == 0) return false;

            SyntaxTree [] syntaxTrees = new SyntaxTree[SourceFiles.Count + SourceTexts.Count];
            int currentIndex = 0;

            try
            {
                foreach (string sourceFile in SourceFiles)
                {
                    using (StreamReader reader = new StreamReader(MyFileSystem.OpenRead(sourceFile)))
                    {
                        var text = reader.ReadToEnd();
                        syntaxTrees[currentIndex] = CSharpSyntaxTree.ParseText(text);
                        currentIndex++;
                    }
                }

                foreach (var sourceText in SourceTexts)
                    syntaxTrees[currentIndex++] = CSharpSyntaxTree.ParseText(sourceText);

                m_compilation = CSharpCompilation.Create(AssemblyName, syntaxTrees, 
                    DependencyCollector.References, m_defaultCompilationOptions);

            }
            catch (Exception e)
            {
                Debug.Fail(e.ToString());
                return false;
            }

            return true;
        }
开发者ID:2asoft,项目名称:SpaceEngineers,代码行数:39,代码来源:MyVSCompiler.cs

示例12: WriteDocumentationCommentXml

        /// <summary>
        /// Traverses the symbol table processing XML documentation comments and optionally writing them to
        /// a provided stream.
        /// </summary>
        /// <param name="compilation">Compilation that owns the symbol table.</param>
        /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param>
        /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param>
        /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param>
        /// <param name="cancellationToken">To stop traversing the symbol table early.</param>
        /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param>
        /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param>
        public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string assemblyName, Stream xmlDocStream, DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null)
        {
            StreamWriter writer = null;
            if (xmlDocStream != null && xmlDocStream.CanWrite)
            {
                writer = new StreamWriter(
                    stream: xmlDocStream,
                    encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false),
                    bufferSize: 0x400, // Default.
                    leaveOpen: true); // Don't close caller's stream.
            }

            using (writer)
            {
                var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree,
                    processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken);
                compiler.Visit(compilation.SourceAssembly.GlobalNamespace);
                Debug.Assert(compiler._indentDepth == 0);
            }

            if (filterTree != null)
            {
                // Will respect the DocumentationMode.
                UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics, cancellationToken);
            }
            else
            {
                foreach (SyntaxTree tree in compilation.SyntaxTrees)
                {
                    // Will respect the DocumentationMode.
                    UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnostics, cancellationToken);
                }
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:45,代码来源:DocumentationCommentCompiler.cs

示例13: SyntaxWalker

        public SyntaxWalker(Solution solution, string project)
        {
            if (solution == null) throw new ArgumentException("solution");
            if (project == null) throw new ArgumentException("classProject");

            var solutionTrees = solution.GetTrees();
            _solutionCompilation = CSharpCompilation.Create("SolutionCompilation")
                .AddSyntaxTrees(solutionTrees)
                .WithReferences(new List<MetadataReference>()
                {
                    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(IEnumerable).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(Task).Assembly.Location)
                });

            _allTrees = solution.GetTrees(new[] {project}).ToList();
            _projectCompilation = CSharpCompilation.Create("ProjectCompilation")
                .AddSyntaxTrees(_allTrees)
                .WithReferences(new List<MetadataReference>()
                {
                    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(IEnumerable).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(Task).Assembly.Location)
                });
        }
开发者ID:yumapos,项目名称:Yumapos-WCF-Generator,代码行数:25,代码来源:SyntaxWalker.cs

示例14: IssueDiagnostics

        public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, DiagnosticBag diagnostics, MethodSymbol containingSymbol)
        {
            Debug.Assert(node != null);
            Debug.Assert((object)containingSymbol != null);

            var diagnosticPass = new DiagnosticsPass(compilation, diagnostics, containingSymbol);
            diagnosticPass.Visit(node);
        }
开发者ID:jerriclynsjohn,项目名称:roslyn,代码行数:8,代码来源:DiagnosticsPass_ExpressionTrees.cs

示例15: CSharpCompilationReference

 /// <summary>
 /// Create a metadata reference to a compilation.
 /// </summary>
 /// <param name="compilation">The compilation to reference.</param>
 /// <param name="aliases">Extern aliases for this reference.</param>
 /// <param name="embedInteropTypes">Should interop types be embedded in the created assembly?</param>
 public CSharpCompilationReference(
     CSharpCompilation compilation,
     ImmutableArray<string> aliases = default(ImmutableArray<string>),
     bool embedInteropTypes = false)
     : base(GetProperties(compilation, aliases, embedInteropTypes))
 {
     this.Compilation = compilation;
 }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:14,代码来源:CSharpCompilationReference.cs


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