Example #1
0
        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);
        }
        public void AddReference(string referenceAssembly)
        {
            if (string.IsNullOrEmpty(referenceAssembly) || !referenceAssembly.Contains("dll"))
                return;

            string filePath = null;
            if (File.Exists(referenceAssembly))
                filePath = Path.GetFullPath(referenceAssembly);
            else
            {
                var referencedAssemblyInAppDomain =
                    AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == Path.GetFileNameWithoutExtension(referenceAssembly));

                if (referencedAssemblyInAppDomain != null)
                {
                    filePath = referencedAssemblyInAppDomain.Location;
                }
                else
                {
                    throw new ArgumentException(
                        string.Format("Thre was a problem trying to find {0} either in the current folder or in the AppDomain, the solution is to try to load the missing assembly into the appdomain somehow",referenceAssembly));
                }
            }
            var executableReference = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(filePath)).GetReference();
            _compilation = _compilation.AddReferences(new MetadataReference[]{ executableReference});
        }
        private void Init()
        {
            // touch assembly
            SyntaxFactory.Token(SyntaxKind.NullKeyword);

            InitOptions();
            if (Options.FullCompile)
                if (!Directory.Exists(Options.OutputPath)) Directory.CreateDirectory(Options.OutputPath);
            var wsa = assemblyDictionary.GetOrAdd(Options.WebSiteAssembly, _ => Assembly.LoadFrom(Options.WebSiteAssembly));
            configuration = GetCachedConfiguration(wsa, Options.WebSitePath);
            bindingCompiler = new AssemblyBindingCompiler(Options.BindingsAssemblyName, Options.BindingClassName, Path.Combine(Options.OutputPath, Options.BindingsAssemblyName + ".dll"), configuration);
            configuration.ServiceLocator.RegisterSingleton<IBindingCompiler>(() => bindingCompiler);
            configuration.ServiceLocator.RegisterSingleton<IControlResolver>(() => new OfflineCompilationControlResolver(configuration, this));
            if (Options.DothtmlFiles == null) Options.DothtmlFiles = configuration.RouteTable.Select(r => r.VirtualPath).ToArray();
            controlTreeResolver = configuration.ServiceLocator.GetService<IControlTreeResolver>();
            fileLoader = configuration.ServiceLocator.GetService<IMarkupFileLoader>();
            if (Options.FullCompile)
            {
                compiler = configuration.ServiceLocator.GetService<IViewCompiler>();
                compilation = compiler.CreateCompilation(Options.AssemblyName);
            }

            if (Options.SerializeConfig)
            {
                result.Configuration = configuration;
            }

            // touch assemblies
        }
Example #4
0
        public static bool CompileCSharp(
            IEnumerable <string> sourceFiles,
            string outputPath,
            IEnumerable <string> references,
            IEnumerable <string> defines,
            out List <string> messages
            )
        {
            CS.CSharpCompilation compilation =
                CreateCSharpCompilation(
                    sourceFiles,
                    Path.GetFileName(outputPath),
                    references,
                    defines,
                    out messages
                    );

            // compile and write results
            var result = compilation.Emit(outputPath);

            foreach (var diag in result.Diagnostics)
            {
                messages.Add(diag.ToString());
            }

            return(result.Success);
        }
Example #5
0
        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)
             );
        }
Example #6
0
        /// <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;
        }
Example #7
0
        /// <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();
            }
        }
        /// <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;
        }
        internal CSharpScriptCompilationInfo(CSharpCompilation previousCompilationOpt, Type returnType, Type globalsType)
            : base(returnType, globalsType)
        {
            Debug.Assert(previousCompilationOpt == null || previousCompilationOpt.HostObjectType == globalsType);

            PreviousScriptCompilation = previousCompilationOpt;
        }
        /// <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);
                }
            }
        }
Example #11
0
        internal static void Analyze(
            CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes,
            out IEnumerable<Symbol> readInside,
            out IEnumerable<Symbol> writtenInside,
            out IEnumerable<Symbol> readOutside,
            out IEnumerable<Symbol> writtenOutside,
            out IEnumerable<Symbol> captured,
            out IEnumerable<Symbol> unsafeAddressTaken)
        {
            var walker = new ReadWriteWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariableAddressOfSyntaxes);
            try
            {
                bool badRegion = false;
                walker.Analyze(ref badRegion);
                if (badRegion)
                {
                    readInside = writtenInside = readOutside = writtenOutside = captured = unsafeAddressTaken = Enumerable.Empty<Symbol>();
                }
                else
                {
                    readInside = walker._readInside;
                    writtenInside = walker._writtenInside;
                    readOutside = walker._readOutside;
                    writtenOutside = walker._writtenOutside;

                    captured = walker.GetCaptured();
                    unsafeAddressTaken = walker.GetUnsafeAddressTaken();
                }
            }
            finally
            {
                walker.Free();
            }
        }
        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)
                });
        }
        public RoslynCompiledItem(Project project, CSharpCompilation
            compilation)
        {
            Project = project;

            Compilation = compilation;
        }
Example #14
0
 internal Binder(Binder next)
 {
     Debug.Assert(next != null);
     _next = next;
     this.Flags = next.Flags;
     this.Compilation = next.Compilation;
 }
        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;
        }
        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;
        }
Example #17
0
        /// <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;
                }
            }
        }
Example #18
0
        public NamespaceScopeBuilder(CSharpCompilation compilation)
        {
            this.compilation = compilation;

            buildNamespaceScopes = BuildNamespaceScopes;
            buildNamespaceOrTypeString = BuildNamespaceOrTypeString;
        }
 private MethodBodySemanticModel(CSharpCompilation compilation, Symbol owner, Binder rootBinder, CSharpSyntaxNode syntax, SyntaxTreeSemanticModel parentSemanticModelOpt = null, int speculatedPosition = 0)
     : base(compilation, syntax, owner, rootBinder, parentSemanticModelOpt, speculatedPosition)
 {
     Debug.Assert((object)owner != null);
     Debug.Assert(owner.Kind == SymbolKind.Method);
     Debug.Assert(syntax != null);
     Debug.Assert(owner.ContainingType.IsScriptClass || syntax.Kind != SyntaxKind.CompilationUnit);
 }
 /// <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;
 }
        public SynthesizedSubmissionFields(CSharpCompilation compilation, NamedTypeSymbol submissionClass)
        {
            Debug.Assert(compilation != null);
            Debug.Assert(submissionClass.IsSubmissionClass);

            _declaringSubmissionClass = submissionClass;
            _compilation = compilation;
        }
        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);
        }
Example #23
0
        public Rewriter(CSharpCompilation compilation, AnalyzerResult result)
        {
            tree = (CSharpSyntaxTree) compilation.SyntaxTrees.Single();
            model = compilation.GetSemanticModel(tree);

            this.compilation = compilation;
            this.result = result;
        }
        public CSharpScriptCompiler()
        {
            _compilation = CSharpCompilation.Create("ScriptingAssembly")
                .AddReferences(new MetadataReference[]{ new MetadataImageReference(File.ReadAllBytes(typeof(object).Assembly.Location))})
                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            if (Directory.Exists(FileConstants.AssembliesDirectory) == false)
                Directory.CreateDirectory(FileConstants.AssembliesDirectory);
        }
Example #25
0
 protected CppWalker(CSharpCompilation compilation, SemanticModel model, ConversionSettings settings)
 {
   if (compilation == null) throw new ArgumentNullException("compilation");
   if (model == null) throw new ArgumentNullException("model");
   if (settings == null) throw new ArgumentNullException("settings");
   this.compilation = compilation;
   this.model = model;
   this.settings = settings;
 }
 private IteratorAndAsyncCaptureWalker(CSharpCompilation compilation, MethodSymbol method, BoundNode node, CaptureWalkerEmptyStructTypeCache emptyStructCache, HashSet<Symbol> initiallyAssignedVariables)
     : base(compilation, 
           method, 
           node, 
           emptyStructCache, 
           trackUnassignments: true, 
           initiallyAssignedVariables: initiallyAssignedVariables)
 {
 }
        private DiagnosticsPass(CSharpCompilation compilation, DiagnosticBag diagnostics, MethodSymbol containingSymbol)
        {
            Debug.Assert(diagnostics != null);
            Debug.Assert((object)containingSymbol != null);

            _compilation = compilation;
            _diagnostics = diagnostics;
            _containingSymbol = containingSymbol;
        }
 internal AbstractRegionControlFlowPass(
     CSharpCompilation compilation,
     Symbol member,
     BoundNode node,
     BoundNode firstInRegion,
     BoundNode lastInRegion)
     : base(compilation, member, node, firstInRegion, lastInRegion)
 {
 }
 // create a SemanticModel for:
 // (a) A true field initializer (field = value) of a named type (incl. Enums) OR
 // (b) A constructor initializer (": this(...)" or ": base(...)") OR
 // (c) A parameter default value
 private InitializerSemanticModel(CSharpCompilation compilation,
                              CSharpSyntaxNode syntax,
                              Symbol symbol,
                              Binder rootBinder,
                              SyntaxTreeSemanticModel parentSemanticModelOpt = null,
                              int speculatedPosition = 0) :
     base(compilation, syntax, symbol, rootBinder, parentSemanticModelOpt, speculatedPosition)
 {
 }
        public static CompiledAssemblyResult GetAssemblyFromCompilation(
            CSharpCompilation compilation)
        {
            EmitResult result;
            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    if (_isMono.Value)
                    {
                        result = compilation.Emit(ms, pdbStream: null);
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();
                        var errorMessages = result.Diagnostics
                            .Where(IsError)
                            .Select(d => formatter.Format(d));

                        return CompiledAssemblyResult.FromErrorMessages(errorMessages);
                    }

                    Assembly assembly;
                    if (_isMono.Value)
                    {
                        var assemblyLoadMethod = typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load")
                            .First(
                                m =>
                                    {
                                        var parameters = m.GetParameters();
                                        return parameters.Length == 1 && parameters[0].ParameterType == typeof(byte[]);
                                    });
                        assembly = (Assembly)assemblyLoadMethod.Invoke(null, new[] { ms.ToArray() });
                    }
                    else
                    {
                        var assemblyLoadMethod = typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load")
                            .First(
                                m =>
                                    {
                                        var parameters = m.GetParameters();
                                        return parameters.Length == 2
                                               && parameters[0].ParameterType == typeof(byte[])
                                               && parameters[1].ParameterType == typeof(byte[]);
                                    });
                        assembly = (Assembly)assemblyLoadMethod.Invoke(null, new[] { ms.ToArray(), pdb.ToArray() });
                    }

                    return CompiledAssemblyResult.FromAssembly(assembly);
                }
            }
        }
        /// <summary>
        /// Constructs a new instance of the <see cref="RoslynCompilationContext"/> type.
        /// </summary>
        /// <param name="compilation"><see cref="CSharpCompilation"/> to be set to <see cref="Compilation"/> property.</param>
        public RoslynCompilationContext(CSharpCompilation compilation)
        {
            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

            Compilation = compilation;
        }
Example #32
0
        internal static IEnumerable <ISymbol> GetSourceSymbols(
            Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation,
            SymbolCategory category
            )
        {
            // NYI for local symbols
            var list = GetSourceSymbols(compilation, includeLocal: false);

            var kinds = new List <SymbolKind>();

            if ((category & SymbolCategory.DeclaredNamespace) != 0)
            {
                kinds.Add(SymbolKind.Namespace);
            }

            if ((category & SymbolCategory.DeclaredType) != 0)
            {
                kinds.Add(SymbolKind.NamedType);
                kinds.Add(SymbolKind.TypeParameter);
            }

            if ((category & SymbolCategory.NonTypeMember) != 0)
            {
                kinds.Add(SymbolKind.Field);
                kinds.Add(SymbolKind.Event);
                kinds.Add(SymbolKind.Property);
                kinds.Add(SymbolKind.Method);
            }

            if ((category & SymbolCategory.Parameter) != 0)
            {
                kinds.Add(SymbolKind.Parameter);
            }

            return(list.Where(
                       s =>
            {
                if (s.IsImplicitlyDeclared)
                {
                    return false;
                }

                foreach (var k in kinds)
                {
                    if (s.Kind == k)
                    {
                        return true;
                    }
                }

                return false;
            }
                       ));
        }
Example #33
0
        public static bool CompileCSharp(
            IEnumerable <string> sourceFiles,
            string outputPath,
            IEnumerable <string> references,
            IEnumerable <string> defines,
            bool debug,
            out List <string> messages
            )
        {
            CS.CSharpCompilation compilation =
                CreateCSharpCompilation(
                    sourceFiles,
                    Path.GetFileName(outputPath),
                    references,
                    defines,
                    debug,
                    out messages
                    );

            // compile and write results
            EmitResult result;

            if (debug)
            {
                string pdbName = Path.Combine(
                    Path.GetDirectoryName(outputPath),
                    Path.GetFileNameWithoutExtension(outputPath) + ".pdb"
                    );
                result = compilation.Emit(outputPath, pdbName);
            }
            else
            {
                result = compilation.Emit(outputPath);
            }

            foreach (var diag in result.Diagnostics)
            {
                messages.Add(diag.ToString());
            }

            return(result.Success);
        }
Example #34
0
        public void Parse(Definition.Definitions definitions, List <SyntaxTree> syntaxTrees, Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation)
        {
            this.definitions = definitions;
            this.compilation = compilation;

            foreach (var enumDef in definitions.Enums)
            {
                ParseEnum(enumDef);
            }

            foreach (var classDef in definitions.Classes)
            {
                ParseClass(classDef);
            }

            foreach (var def in definitions.Structs)
            {
                ParseStruct(def);
            }
        }
Example #35
0
        /// <summary>
        /// Compile source files to assembly<br/>
        /// 编译源代码到程序集<br/>
        /// </summary>
        public void Compile(IList <string> sourceFiles,
                            string assemblyName, string assemblyPath)
        {
            // Parse source files into syntax trees
            // Also define NETCORE for .Net Core
            var parseOptions = CSharpParseOptions.Default;

            parseOptions = parseOptions.WithPreprocessorSymbols("NETCORE");
            var syntaxTrees = sourceFiles
                              .Select(path => CSharpSyntaxTree.ParseText(
                                          File.ReadAllText(path), parseOptions, path, Encoding.UTF8))
                              .ToList();

            LoadAssembliesFromUsings(syntaxTrees);
            // Add loaded assemblies to compile references
            var assemblyLoader = new NetAssemblyLoader();
            var references     = assemblyLoader.GetLoadedAssemblies()
                                 .Select(assembly => assembly.Location)
                                 .Select(path => MetadataReference.CreateFromFile(path))
                                 .ToList();

            var optimizationLevel  = OptimizationLevel.Release;
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: optimizationLevel);

            // Compile to assembly, throw exception if error occurred
            Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation = CSharpCompilation.Create(assemblyName)
                                                                          .WithOptions(compilationOptions)
                                                                          .AddReferences(references)
                                                                          .AddSyntaxTrees(syntaxTrees);
            Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(assemblyPath);
            if (!emitResult.Success)
            {
                throw new Exception(string.Join("\r\n",
                                                emitResult.Diagnostics.Where(d => d.WarningLevel == 0)));
            }
        }
Example #36
0
 internal static CSDiagnosticInfo GetFeatureAvailabilityDiagnosticInfoOpt(this MessageID feature, CSharpCompilation compilation)
 => compilation.IsFeatureEnabled(feature) ? null : GetDisabledFeatureDiagnosticInfo(feature, compilation.LanguageVersion);
 public TypeCompilationState(NamedTypeSymbol typeOpt, CSharpCompilation compilation, PEModuleBuilder moduleBuilderOpt)
 {
     this.Compilation      = compilation;
     _typeOpt              = typeOpt;
     this.ModuleBuilderOpt = moduleBuilderOpt;
 }
 /// <summary>
 /// Creates a SemanticModel for a true field initializer (field = value) of a named type (incl. Enums).
 /// </summary>
 internal static InitializerSemanticModel Create(CSharpCompilation compilation, CSharpSyntaxNode syntax, FieldSymbol fieldSymbol, Binder rootBinder)
 {
     Debug.Assert(syntax.IsKind(SyntaxKind.VariableDeclarator) || syntax.IsKind(SyntaxKind.EnumMemberDeclaration));
     return(new InitializerSemanticModel(compilation, syntax, fieldSymbol, rootBinder));
 }
Example #39
0
 internal BuiltInOperators(CSharpCompilation compilation)
 {
     _compilation = compilation;
 }
 private RegionReachableWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
     : base(compilation, member, node, firstInRegion, lastInRegion)
 {
 }
Example #41
0
 private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, DiagnosticBag diagnostics, out MethodSymbol method)
 {
     return(Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method));
 }
 /// <summary>
 /// Creates a SemanticModel for a parameter default value.
 /// </summary>
 internal static InitializerSemanticModel Create(CSharpCompilation compilation, ParameterSyntax syntax, ParameterSymbol parameterSymbol, Binder rootBinder)
 {
     return(new InitializerSemanticModel(compilation, syntax, parameterSymbol, rootBinder));
 }
        public static VisualBasicSyntaxNode ConvertCompilationTree(CS.CSharpCompilation compilation, CS.CSharpSyntaxTree tree)
        {
            var visualBasicSyntaxVisitor = new NodesVisitor(compilation.GetSemanticModel(tree, true));

            return(tree.GetRoot().Accept(visualBasicSyntaxVisitor.TriviaConvertingVisitor));
        }
Example #44
0
        /// <summary>
        /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
        /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, DiagnosticBag, out MethodSymbol)"/> instead!
        /// If used, a unit-test with a missing member is absolutely a must have.
        /// </summary>
        private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, DiagnosticBag diagnostics)
        {
            MethodSymbol method;

            if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method))
            {
                return(method);
            }
            else
            {
                MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember);
                SpecialType      type       = (SpecialType)descriptor.DeclaringTypeId;
                TypeSymbol       container  = compilation.Assembly.GetSpecialType(type);
                TypeSymbol       returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity);
                return(new ErrorMethodSymbol(container, returnType, "Missing"));
            }
        }
 /// <summary>
 /// Creates a SemanticModel for an autoprop initializer of a named type
 /// </summary>
 internal static InitializerSemanticModel Create(CSharpCompilation compilation, CSharpSyntaxNode syntax, PropertySymbol propertySymbol, Binder rootBinder)
 {
     Debug.Assert(syntax.IsKind(SyntaxKind.PropertyDeclaration));
     return(new InitializerSemanticModel(compilation, syntax, propertySymbol, rootBinder));
 }
        /// <summary>
        /// Creates a SemanticModel that creates and owns the ExecutableCodeBinder for the method of which it is a model.
        /// </summary>
        internal static MethodBodySemanticModel Create(CSharpCompilation compilation, MethodSymbol owner, Binder rootBinder, CSharpSyntaxNode syntax)
        {
            var executableCodeBinder = new ExecutableCodeBinder(syntax, owner, rootBinder);

            return(new MethodBodySemanticModel(compilation, owner, executableCodeBinder, syntax));
        }
Example #47
0
 private static MethodSymbol GetCreatePayloadOverload(CSharpCompilation compilation, WellKnownMember overload, SyntaxNode syntax, DiagnosticBag diagnostics)
 {
     return((MethodSymbol)Binder.GetWellKnownTypeMember(compilation, overload, diagnostics, syntax: syntax));
 }
 private static MethodSymbol GetCreatePayload(CSharpCompilation compilation, SyntaxNode syntax, DiagnosticBag diagnostics)
 {
     return((MethodSymbol)Binder.GetWellKnownTypeMember(compilation, WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayload, diagnostics, syntax: syntax));
 }
 public WellKnownMembersSignatureComparer(CSharpCompilation compilation)
 {
     _compilation = compilation;
 }
Example #50
0
 internal bool IsFromCompilation(CSharpCompilation compilation)
 {
     Debug.Assert(compilation != null);
     return(compilation == this.DeclaringCompilation);
 }
Example #51
0
        public static Imports FromGlobalUsings(CSharpCompilation compilation)
        {
            var usings = compilation.Options.Usings;

            if (usings.Length == 0 && compilation.PreviousSubmission == null)
            {
                return(Empty);
            }

            var diagnostics  = new DiagnosticBag();
            var usingsBinder = new InContainerBinder(compilation.GlobalNamespace, new BuckStopsHereBinder(compilation));
            var boundUsings  = ArrayBuilder <NamespaceOrTypeAndUsingDirective> .GetInstance();

            var uniqueUsings = PooledHashSet <NamespaceOrTypeSymbol> .GetInstance();

            foreach (string @using in usings)
            {
                if ([email protected]())
                {
                    continue;
                }

                string[]   identifiers   = @using.Split('.');
                NameSyntax qualifiedName = SyntaxFactory.IdentifierName(identifiers[0]);

                for (int j = 1; j < identifiers.Length; j++)
                {
                    qualifiedName = SyntaxFactory.QualifiedName(left: qualifiedName, right: SyntaxFactory.IdentifierName(identifiers[j]));
                }

                var imported = usingsBinder.BindNamespaceOrTypeSymbol(qualifiedName, diagnostics).NamespaceOrTypeSymbol;
                if (uniqueUsings.Add(imported))
                {
                    boundUsings.Add(new NamespaceOrTypeAndUsingDirective(imported, null));
                }
            }

            if (diagnostics.IsEmptyWithoutResolution)
            {
                diagnostics = null;
            }

            var previousSubmissionImports = compilation.PreviousSubmission?.GlobalImports;

            if (previousSubmissionImports != null)
            {
                // Currently, only usings are supported.
                Debug.Assert(previousSubmissionImports.UsingAliases.IsEmpty);
                Debug.Assert(previousSubmissionImports.ExternAliases.IsEmpty);

                var expandedImports = ExpandPreviousSubmissionImports(previousSubmissionImports, compilation);

                foreach (var previousUsing in expandedImports.Usings)
                {
                    if (uniqueUsings.Add(previousUsing.NamespaceOrType))
                    {
                        boundUsings.Add(previousUsing);
                    }
                }
            }

            uniqueUsings.Free();

            if (boundUsings.Count == 0)
            {
                boundUsings.Free();
                return(Empty);
            }

            return(new Imports(compilation, ImmutableDictionary <string, AliasAndUsingDirective> .Empty, boundUsings.ToImmutableAndFree(), ImmutableArray <AliasAndExternAliasDirective> .Empty, diagnostics));
        }
Example #52
0
        public override Compilation?CreateCompilation(
            TextWriter consoleOutput,
            TouchedFileLogger?touchedFilesLogger,
            ErrorLogger?errorLogger,
            ImmutableArray <AnalyzerConfigOptionsResult> analyzerConfigOptions,
            AnalyzerConfigOptionsResult globalConfigOptions
            )
        {
            var parseOptions = Arguments.ParseOptions;

            // We compute script parse options once so we don't have to do it repeatedly in
            // case there are many script files.
            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            bool hadErrors = false;

            var sourceFiles         = Arguments.SourceFiles;
            var trees               = new SyntaxTree?[sourceFiles.Length];
            var normalizedFilePaths = new string?[sourceFiles.Length];
            var diagnosticBag       = DiagnosticBag.GetInstance();

            if (Arguments.CompilationOptions.ConcurrentBuild)
            {
                RoslynParallel.For(
                    0,
                    sourceFiles.Length,
                    UICultureUtilities.WithCurrentUICulture <int>(
                        i =>
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(
                        parseOptions,
                        scriptParseOptions,
                        ref hadErrors,
                        sourceFiles[i],
                        diagnosticBag,
                        out normalizedFilePaths[i]
                        );
                }
                        ),
                    CancellationToken.None
                    );
            }
            else
            {
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(
                        parseOptions,
                        scriptParseOptions,
                        ref hadErrors,
                        sourceFiles[i],
                        diagnosticBag,
                        out normalizedFilePaths[i]
                        );
                }
            }

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (
                ReportDiagnostics(
                    diagnosticBag.ToReadOnlyAndFree(),
                    consoleOutput,
                    errorLogger,
                    compilation: null
                    )
                )
            {
                Debug.Assert(hadErrors);
                return(null);
            }

            var diagnostics     = new List <DiagnosticInfo>();
            var uniqueFilePaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < sourceFiles.Length; i++)
            {
                var normalizedFilePath = normalizedFilePaths[i];
                Debug.Assert(normalizedFilePath != null);
                Debug.Assert(
                    sourceFiles[i].IsInputRedirected || PathUtilities.IsAbsolute(normalizedFilePath)
                    );

                if (!uniqueFilePaths.Add(normalizedFilePath))
                {
                    // warning CS2002: Source file '{0}' specified multiple times
                    diagnostics.Add(
                        new DiagnosticInfo(
                            MessageProvider,
                            (int)ErrorCode.WRN_FileAlreadyIncluded,
                            Arguments.PrintFullPaths
                              ? normalizedFilePath
                              : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath)
                            )
                        );

                    trees[i] = null;
                }
            }

            if (Arguments.TouchedFilesPath != null)
            {
                Debug.Assert(touchedFilesLogger is object);
                foreach (var path in uniqueFilePaths)
                {
                    touchedFilesLogger.AddRead(path);
                }
            }

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            var appConfigPath            = this.Arguments.AppConfigPath;

            if (appConfigPath != null)
            {
                try
                {
                    using (
                        var appConfigStream = new FileStream(
                            appConfigPath,
                            FileMode.Open,
                            FileAccess.Read
                            )
                        )
                    {
                        assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(
                            appConfigStream
                            );
                    }

                    if (touchedFilesLogger != null)
                    {
                        touchedFilesLogger.AddRead(appConfigPath);
                    }
                }
                catch (Exception ex)
                {
                    diagnostics.Add(
                        new DiagnosticInfo(
                            MessageProvider,
                            (int)ErrorCode.ERR_CantReadConfigFile,
                            appConfigPath,
                            ex.Message
                            )
                        );
                }
            }

            var xmlFileResolver = new LoggingXmlFileResolver(
                Arguments.BaseDirectory,
                touchedFilesLogger
                );
            var sourceFileResolver = new LoggingSourceFileResolver(
                ImmutableArray <string> .Empty,
                Arguments.BaseDirectory,
                Arguments.PathMap,
                touchedFilesLogger
                );

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(
                diagnostics,
                touchedFilesLogger,
                out referenceDirectiveResolver
                );

            if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null))
            {
                return(null);
            }

            var loggingFileSystem = new LoggingStrongNameFileSystem(
                touchedFilesLogger,
                _tempDirectory
                );
            var optionsProvider = new CompilerSyntaxTreeOptionsProvider(
                trees,
                analyzerConfigOptions,
                globalConfigOptions
                );

            return(CSharpCompilation.Create(
                       Arguments.CompilationName,
                       trees.WhereNotNull(),
                       resolvedReferences,
                       Arguments.CompilationOptions
                       .WithMetadataReferenceResolver(referenceDirectiveResolver)
                       .WithAssemblyIdentityComparer(assemblyIdentityComparer)
                       .WithXmlReferenceResolver(xmlFileResolver)
                       .WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem))
                       .WithSourceReferenceResolver(sourceFileResolver)
                       .WithSyntaxTreeOptionsProvider(optionsProvider)
                       ));
        }
Example #53
0
 internal BuckStopsHereBinder(CSharpCompilation compilation)
     : base(compilation)
 {
 }
 private UnassignedFieldsWalker(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics)
     : base(compilation, method, node, trackClassFields: true)
 {
     _diagnostics = diagnostics;
 }
Example #55
0
        /// <summary>
        /// Lower a block of code by performing local rewritings.
        /// </summary>
        public static BoundStatement Rewrite(
            CSharpCompilation compilation,
            MethodSymbol method,
            int methodOrdinal,
            NamedTypeSymbol containingType,
            BoundStatement statement,
            TypeCompilationState compilationState,
            SynthesizedSubmissionFields previousSubmissionFields,
            bool allowOmissionOfConditionalCalls,
            bool instrumentForDynamicAnalysis,
            ref ImmutableArray <SourceSpan> dynamicAnalysisSpans,
            DebugDocumentProvider debugDocumentProvider,
            DiagnosticBag diagnostics,
            out bool sawLambdas,
            out bool sawLocalFunctions,
            out bool sawAwaitInExceptionHandler)
        {
            Debug.Assert(statement != null);
            Debug.Assert(compilationState != null);

            try
            {
                var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics);
                DynamicAnalysisInjector dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null;

                // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not.
                // Presence of sequence points in the tree affects final IL, therefore, we always generate them.
                var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics,
                                                      dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton);

                statement.CheckLocalsDefined();
                var loweredStatement = (BoundStatement)localRewriter.Visit(statement);
                loweredStatement.CheckLocalsDefined();
                sawLambdas                 = localRewriter._sawLambdas;
                sawLocalFunctions          = localRewriter._sawLocalFunctions;
                sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler;

                if (localRewriter._needsSpilling && !loweredStatement.HasErrors)
                {
                    // Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression.
                    var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics);
                    spilledStatement.CheckLocalsDefined();
                    loweredStatement = spilledStatement;
                }

                if (dynamicInstrumenter != null)
                {
                    dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans;
                }
#if DEBUG
                LocalRewritingValidator.Validate(loweredStatement);
#endif
                return(loweredStatement);
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false;
                return(new BoundBadStatement(statement.Syntax, ImmutableArray.Create <BoundNode>(statement), hasErrors: true));
            }
        }
Example #56
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
        {
#if XSHARP
            var parseOptions = Arguments.ParseOptions.WithOutput(consoleOutput);
#else
            var parseOptions = Arguments.ParseOptions;
#endif

            // We compute script parse options once so we don't have to do it repeatedly in
            // case there are many script files.
            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            bool hadErrors = false;

            var sourceFiles         = Arguments.SourceFiles;
            var trees               = new SyntaxTree[sourceFiles.Length];
            var normalizedFilePaths = new string[sourceFiles.Length];
            var diagnosticBag       = DiagnosticBag.GetInstance();

            if (Arguments.CompilationOptions.ConcurrentBuild)
            {
                Parallel.For(0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture <int>(i =>
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]);
                }));
            }
            else
            {
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]);
                }
            }

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                Debug.Assert(diagnosticBag.HasAnyErrors());
                ReportErrors(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger);
                return(null);
            }
            else
            {
                Debug.Assert(diagnosticBag.IsEmptyWithoutResolution);
                diagnosticBag.Free();
            }
#if XSHARP
            var newtree = InternalSyntax.XSharpLanguageParser.ProcessTrees(trees, parseOptions);
            if (newtree != null)
            {
                var newtrees = new SyntaxTree[trees.Length + 1];
                Array.Copy(trees, newtrees, trees.Length);
                newtrees[trees.Length] = newtree;
                trees = newtrees;
            }
#endif

            var diagnostics = new List <DiagnosticInfo>();

            var uniqueFilePaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            for (int i = 0; i < sourceFiles.Length; i++)
            {
                var normalizedFilePath = normalizedFilePaths[i];
                Debug.Assert(normalizedFilePath != null);
                Debug.Assert(PathUtilities.IsAbsolute(normalizedFilePath));

                if (!uniqueFilePaths.Add(normalizedFilePath))
                {
                    // warning CS2002: Source file '{0}' specified multiple times
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded,
                                                       Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath)));

                    trees[i] = null;
                }
#if XSHARP
                else if (parseOptions.PreprocessorOutput && Arguments.TouchedFilesPath != null)
                {
                    touchedFilesLogger.AddWritten(FileNameUtilities.ChangeExtension(normalizedFilePath, ".ppo"));
                }
#endif
            }
#if XSHARP
            // Add the names of the header files that we have processed
            foreach (var tree in trees)
            {
                if (tree != null)
                {
                    if (tree.HasCompilationUnitRoot)
                    {
                        var root = tree.GetCompilationUnitRoot();
                        foreach (var file in root.IncludedFiles)
                        {
                            uniqueFilePaths.Add(file.Key);
                        }
                    }
                }
            }
#endif
            if (Arguments.TouchedFilesPath != null)
            {
                foreach (var path in uniqueFilePaths)
                {
                    touchedFilesLogger.AddRead(path);
                }
            }

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            var appConfigPath            = this.Arguments.AppConfigPath;
            if (appConfigPath != null)
            {
                try
                {
                    using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read))
                    {
                        assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream);
                    }

                    if (touchedFilesLogger != null)
                    {
                        touchedFilesLogger.AddRead(appConfigPath);
                    }
                }
                catch (Exception ex)
                {
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message));
                }
            }

            var xmlFileResolver    = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray <string> .Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger);

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver);
            if (ReportErrors(diagnostics, consoleOutput, errorLogger))
            {
                return(null);
            }

            var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger);

            return(CSharpCompilation.Create(
                       Arguments.CompilationName,
                       trees.WhereNotNull(),
                       resolvedReferences,
                       Arguments.CompilationOptions.
                       WithMetadataReferenceResolver(referenceDirectiveResolver).
                       WithAssemblyIdentityComparer(assemblyIdentityComparer).
                       WithXmlReferenceResolver(xmlFileResolver).
                       WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem, _tempDirectory)).
                       WithSourceReferenceResolver(sourceFileResolver)));
        }
 internal VariablesDeclaredWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
     : base(compilation, member, node, firstInRegion, lastInRegion)
 {
 }
Example #58
0
        // TODO (https://github.com/dotnet/roslyn/issues/5517): skip namespace expansion if references haven't changed.
        internal static Imports ExpandPreviousSubmissionImports(Imports previousSubmissionImports, CSharpCompilation newSubmission)
        {
            if (previousSubmissionImports == Empty)
            {
                return(Empty);
            }

            Debug.Assert(previousSubmissionImports != null);
            Debug.Assert(previousSubmissionImports._compilation.IsSubmission);
            Debug.Assert(newSubmission.IsSubmission);

            var expandedGlobalNamespace = newSubmission.GlobalNamespace;

            var expandedAliases = ImmutableDictionary <string, AliasAndUsingDirective> .Empty;

            if (!previousSubmissionImports.UsingAliases.IsEmpty)
            {
                var expandedAliasesBuilder = ImmutableDictionary.CreateBuilder <string, AliasAndUsingDirective>();
                foreach (var pair in previousSubmissionImports.UsingAliases)
                {
                    var name      = pair.Key;
                    var directive = pair.Value;
                    expandedAliasesBuilder.Add(name, new AliasAndUsingDirective(directive.Alias.ToNewSubmission(newSubmission), directive.UsingDirective));
                }
                expandedAliases = expandedAliasesBuilder.ToImmutable();
            }

            var expandedUsings = ImmutableArray <NamespaceOrTypeAndUsingDirective> .Empty;

            if (!previousSubmissionImports.Usings.IsEmpty)
            {
                var expandedUsingsBuilder = ArrayBuilder <NamespaceOrTypeAndUsingDirective> .GetInstance(previousSubmissionImports.Usings.Length);

                foreach (var previousUsing in previousSubmissionImports.Usings)
                {
                    var previousTarget = previousUsing.NamespaceOrType;
                    if (previousTarget.IsType)
                    {
                        expandedUsingsBuilder.Add(previousUsing);
                    }
                    else
                    {
                        var expandedNamespace = ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace);
                        expandedUsingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(expandedNamespace, previousUsing.UsingDirective));
                    }
                }
                expandedUsings = expandedUsingsBuilder.ToImmutableAndFree();
            }

            return(new Imports(
                       newSubmission,
                       expandedAliases,
                       expandedUsings,
                       previousSubmissionImports.ExternAliases,
                       diagnostics: null));
        }
Example #59
0
 private AlwaysAssignedWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
     : base(compilation, member, node, firstInRegion, lastInRegion)
 {
 }
Example #60
0
        /// <summary>
        /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS.
        /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type.
        /// Returns null if a merged tuple type could not be fabricated.
        /// </summary>
        private static TypeSymbol MakeMergedTupleType(ArrayBuilder <DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, CSharpCompilation compilation, DiagnosticBag diagnostics)
        {
            int leftLength  = lhsVariables.Count;
            int rightLength = rhsLiteral.Arguments.Length;

            var typesBuilder = ArrayBuilder <TypeSymbol> .GetInstance(leftLength);

            for (int i = 0; i < rightLength; i++)
            {
                BoundExpression element    = rhsLiteral.Arguments[i];
                TypeSymbol      mergedType = element.Type;

                if (i < leftLength)
                {
                    var variable = lhsVariables[i];
                    if (variable.HasNestedVariables)
                    {
                        if (element.Kind == BoundKind.TupleLiteral)
                        {
                            // (variables) on the left and (elements) on the right
                            mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, compilation, diagnostics);
                        }
                        else if ((object)mergedType == null)
                        {
                            // (variables) on the left and null on the right
                            Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax);
                        }
                    }
                    else
                    {
                        if ((object)variable.Single.Type != null)
                        {
                            // typed-variable on the left
                            mergedType = variable.Single.Type;
                        }
                    }
                }
                else
                {
                    if ((object)mergedType == null)
                    {
                        // a typeless element on the right, matching no variable on the left
                        Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax);
                    }
                }

                typesBuilder.Add(mergedType);
            }

            if (typesBuilder.Any(t => t == null))
            {
                typesBuilder.Free();
                return(null);
            }

            return(TupleTypeSymbol.Create(locationOpt: null, elementTypes: typesBuilder.ToImmutableAndFree(), elementLocations: default(ImmutableArray <Location>),
                                          elementNames: default(ImmutableArray <string>), compilation: compilation, diagnostics: diagnostics));
        }