Пример #1
0
        public PEAssemblyBuilderBase(
            SourceAssemblySymbol sourceAssembly,
            EmitOptions emitOptions,
            OutputKind outputKind,
            Cci.ModulePropertiesForSerialization serializationProperties,
            IEnumerable <ResourceDescription> manifestResources,
            ImmutableArray <NamedTypeSymbol> additionalTypes
            )
            : base(
                (SourceModuleSymbol)sourceAssembly.Modules[0],
                emitOptions,
                outputKind,
                serializationProperties,
                manifestResources
                )
        {
            Debug.Assert(sourceAssembly is object);

            _sourceAssembly  = sourceAssembly;
            _additionalTypes = additionalTypes.NullToEmpty();
            _metadataName    =
                (emitOptions.OutputNameOverride == null)
                    ? sourceAssembly.MetadataName
                    : FileNameUtilities.ChangeExtension(
                    emitOptions.OutputNameOverride,
                    extension: null
                    );

            AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
        }
Пример #2
0
        public string Execute(string path)
        {
            var folderName = Path.GetFileName(path);
            var parentPath = path.Substring(0, path.Length - folderName.Length);

            folderName = FileNameUtilities.Sanitize(folderName);
            return(Path.Combine(parentPath, folderName));
        }
Пример #3
0
        public string Execute(QueuedDownloadToken item)
        {
            var folderName = item.Token.StudyName;

            if (item.Token.Job != null)
            {
                folderName += " - " + item.Token.Job.JobName;
            }

            return(FileNameUtilities.Sanitize(folderName));
        }
Пример #4
0
        /// <summary>
        /// Determines whether an assembly reference is considered an assembly file path or an assembly name.
        /// used, for example, on values of /r and #r.
        /// </summary>
        public static bool IsFilePath(string assemblyDisplayNameOrPath)
        {
            Debug.Assert(assemblyDisplayNameOrPath != null);

            string extension = FileNameUtilities.GetExtension(assemblyDisplayNameOrPath);

            return(string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase) ||
                   string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase) ||
                   assemblyDisplayNameOrPath.IndexOf(DirectorySeparatorChar) != -1 ||
                   assemblyDisplayNameOrPath.IndexOf(AltDirectorySeparatorChar) != -1);
        }
Пример #5
0
            public DocumentId AddTextContainer(SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray <string> folders)
            {
                if (textContainer == null)
                {
                    throw new ArgumentNullException(nameof(textContainer));
                }

                var documentId   = DocumentId.CreateNewId(_project.Id, fullPath);
                var textLoader   = new SourceTextLoader(textContainer, fullPath);
                var documentInfo = DocumentInfo.Create(
                    documentId,
                    FileNameUtilities.GetFileName(fullPath),
                    folders: folders.IsDefault ? null : (IEnumerable <string>)folders,
                    sourceCodeKind: sourceCodeKind,
                    loader: textLoader,
                    filePath: fullPath);

                lock (_project._gate)
                {
                    if (_sourceTextContainersToDocumentIds.ContainsKey(textContainer))
                    {
                        throw new ArgumentException($"{nameof(textContainer)} is already added to this project.", nameof(textContainer));
                    }

                    if (fullPath != null)
                    {
                        if (_documentPathsToDocumentIds.ContainsKey(fullPath))
                        {
                            throw new ArgumentException($"'{fullPath}' has already been added to this project.");
                        }

                        _documentPathsToDocumentIds.Add(fullPath, documentId);
                    }

                    _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.Add(textContainer, documentInfo.Id);

                    if (_project._activeBatchScopes > 0)
                    {
                        _documentsAddedInBatch.Add(documentInfo);
                    }
                    else
                    {
                        _project._workspace.ApplyChangeToWorkspace(w =>
                        {
                            _project._workspace.AddDocumentToDocumentsNotFromFiles(documentInfo.Id);
                            _documentAddAction(w, documentInfo);
                            w.OnDocumentOpened(documentInfo.Id, textContainer);
                        });
                    }
                }

                return(documentId);
            }
        public void ExportPngAndCompareWithBaseline()
        {
            const string DestinationDirectory = "ExampleLibrary.Actual";
            const string BaselineDirectory    = "ExampleLibrary.Baseline";
            const string DiffDirectory        = "ExampleLibrary.Diff";

            if (!Directory.Exists(BaselineDirectory))
            {
                Directory.CreateDirectory(BaselineDirectory);
            }

            if (!Directory.Exists(DestinationDirectory))
            {
                Directory.CreateDirectory(DestinationDirectory);
            }

            if (!Directory.Exists(DiffDirectory))
            {
                Directory.CreateDirectory(DiffDirectory);
            }

            foreach (var example in ExampleLibrary.Examples.GetList())
            {
                if (example.PlotModel == null)
                {
                    continue;
                }

                var filename     = FileNameUtilities.CreateValidFileName(example.Category + " - " + example.Title, ".png");
                var baselinePath = Path.Combine(BaselineDirectory, filename);
                var path         = Path.Combine(DestinationDirectory, filename);
                var diffpath     = Path.Combine(DiffDirectory, filename);

                PngExporter.Export(example.PlotModel, path, 800, 500, OxyColors.White);
                if (File.Exists(baselinePath))
                {
                    PngAssert.AreEqual(baselinePath, path, example.Title, diffpath);
                }
                else
                {
                    File.Copy(path, baselinePath);
                }
            }
        }
Пример #7
0
        internal override bool GenerateResourcesAndDocumentationComments(CommonPEModuleBuilder moduleBuilder, Stream xmlDocStream, Stream win32Resources, string outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken)
        {
            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
            DiagnosticBag methodBodyDiagnosticBag = DiagnosticBag.GetInstance();

            var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder;

            try
            {
                SetupWin32Resources(moduleBeingBuilt, win32Resources, methodBodyDiagnosticBag);

                ReportManifestResourceDuplicates(
                    moduleBeingBuilt.ManifestResources,
                    SourceAssembly.Modules.Skip(1).Select((m) => m.Name),   //all modules except the first one
                    AddedModulesResourceNames(methodBodyDiagnosticBag),
                    methodBodyDiagnosticBag);

                if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                this.TrackException(ex);
                throw;
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
            DiagnosticBag xmlDiagnostics = DiagnosticBag.GetInstance();

            string assemblyName = FileNameUtilities.ChangeExtension(moduleBeingBuilt.EmitOptions.OutputNameOverride, extension: null);

            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, xmlDiagnostics, cancellationToken);

            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics))
            {
                return(false);
            }

            return(true);
        }
Пример #8
0
        private void InitializeDisplayAndId()
        {
            try
            {
                // AssemblyName.GetAssemblyName(path) is not available on CoreCLR.
                // Use our metadata reader to do the equivalent thing.
                using var reader = new PEReader(FileUtilities.OpenRead(FullPath));

                var metadataReader   = reader.GetMetadataReader();
                var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow();
                _lazyDisplay  = assemblyIdentity.Name;
                _lazyIdentity = assemblyIdentity;
            }
            catch
            {
                _lazyDisplay  = FileNameUtilities.GetFileName(FullPath, includeExtension: false);
                _lazyIdentity = _lazyDisplay;
            }
        }
Пример #9
0
            public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray <string> folders)
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
                }

                var documentId   = DocumentId.CreateNewId(_project.Id, fullPath);
                var textLoader   = new FileTextLoader(fullPath, defaultEncoding: null);
                var documentInfo = DocumentInfo.Create(
                    documentId,
                    FileNameUtilities.GetFileName(fullPath),
                    folders: folders.IsDefault ? null : (IEnumerable <string>)folders,
                    sourceCodeKind: sourceCodeKind,
                    loader: textLoader,
                    filePath: fullPath);

                lock (_project._gate)
                {
                    if (_documentPathsToDocumentIds.ContainsKey(fullPath))
                    {
                        throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath));
                    }

                    _documentPathsToDocumentIds.Add(fullPath, documentId);
                    _project._fileWatchingTokens.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath));

                    if (_project._activeBatchScopes > 0)
                    {
                        _documentsAddedInBatch.Add(documentInfo);
                    }
                    else
                    {
                        _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo));
                        _project._workspace.CheckForOpenDocuments(ImmutableArray.Create(fullPath));
                    }
                }

                return(documentId);
            }
Пример #10
0
 public static string GetExtension(string path)
 {
     return(FileNameUtilities.GetExtension(path));
 }
Пример #11
0
        private void ProgressUpdated(string filePathOpt)
        {
            var current = DateTimeOffset.UtcNow;

            if (current - _lastTimeReported < s_minimumInterval)
            {
                // make sure we are not flooding UI.
                // this is just presentation, fine to not updating UI especially since
                // at the end, this notification will go away automatically
                return;
            }

            _lastTimeReported = current;
            ChangeProgress(_taskHandler, filePathOpt != null ? string.Format(ServicesVSResources.Analyzing_0, FileNameUtilities.GetFileName(filePathOpt)) : null);
        }
Пример #12
0
 public static string GetFileName(string path, bool includeExtension = true)
 {
     return(FileNameUtilities.GetFileName(path, includeExtension));
 }
Пример #13
0
 public static string RemoveExtension(string path)
 {
     return(FileNameUtilities.ChangeExtension(path, extension: null));
 }
Пример #14
0
        internal override bool CompileImpl(CommonPEModuleBuilder moduleBuilder, Stream win32Resources, Stream xmlDocStream, bool emittingPdb, DiagnosticBag diagnostics, Predicate <ISymbol> filterOpt, CancellationToken cancellationToken)
        {
            // The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that the emitter
            // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...)
            bool hasDeclarationErrors = false;  // !FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, true, cancellationToken));

            var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder;

            if (moduleBeingBuilt.EmitOptions.EmitMetadataOnly)
            {
                throw new NotImplementedException();
            }

            // Perform initial bind of method bodies in spite of earlier errors. This is the same
            // behavior as when calling GetDiagnostics()

            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
            DiagnosticBag methodBodyDiagnosticBag = DiagnosticBag.GetInstance();

            SourceCompiler.CompileSources(
                this,
                moduleBeingBuilt,
                emittingPdb,
                hasDeclarationErrors,
                methodBodyDiagnosticBag,
                cancellationToken);

            SetupWin32Resources(moduleBeingBuilt, win32Resources, methodBodyDiagnosticBag);

            ReportManifestResourceDuplicates(
                moduleBeingBuilt.ManifestResources,
                SourceAssembly.Modules.Skip(1).Select((m) => m.Name),   //all modules except the first one
                AddedModulesResourceNames(methodBodyDiagnosticBag),
                methodBodyDiagnosticBag);

            bool hasMethodBodyErrorOrWarningAsError = !FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag);

            if (hasDeclarationErrors || hasMethodBodyErrorOrWarningAsError)
            {
                return(false);
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
            DiagnosticBag xmlDiagnostics = DiagnosticBag.GetInstance();

            string assemblyName = FileNameUtilities.ChangeExtension(moduleBeingBuilt.EmitOptions.OutputNameOverride, extension: null);

            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, xmlDiagnostics, cancellationToken);

            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics))
            {
                return(false);
            }

            //// Use a temporary bag so we don't have to refilter pre-existing diagnostics.
            //DiagnosticBag importDiagnostics = DiagnosticBag.GetInstance();
            //this.ReportUnusedImports(importDiagnostics, cancellationToken);

            //if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref importDiagnostics))
            //{
            //    Debug.Assert(false, "Should never produce an error");
            //    return false;
            //}

            return(true);
        }
Пример #15
0
 /// <summary>
 /// Checks that the specified name is a valid metadata String and a file name.
 /// The specification isn't entirely consistent and complete but it mentiones:
 ///
 /// 22.19.2: "Name shall index a non-empty string in the String heap. It shall be in the format {filename}.{extension} (e.g., 'foo.dll', but not 'c:\utils\foo.dll')."
 /// 22.30.2: "The format of Name is {file name}.{file extension} with no path or drive letter; on POSIX-compliant systems Name contains no colon, no forward-slash, no backslash."
 ///          As Microsoft specific constraint.
 ///
 /// A reasonable restriction seems to be a valid UTF8 non-empty string that doesn't contain '\0', '\', '/', ':' characters.
 /// </summary>
 internal static bool IsValidMetadataFileName(string name)
 {
     return(FileNameUtilities.IsFileName(name) && IsValidMetadataIdentifier(name));
 }
Пример #16
0
        public PEAssemblyBuilder(
            SourceAssemblySymbol sourceAssembly,
            Cci.ModulePropertiesForSerialization serializationProperties,
            IEnumerable <ResourceDescription> manifestResources,
            OutputKind outputKind,
            EmitOptions emitOptions)
            : base(sourceAssembly.DeclaringCompilation, (SourceModuleSymbol)sourceAssembly.Modules[0], serializationProperties, manifestResources, outputKind, emitOptions)
        {
            _sourceAssembly = sourceAssembly;
            _metadataName   = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null);

            AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
        }
Пример #17
0
        public PEAssemblyBuilderBase(
            SourceAssemblySymbol sourceAssembly,
            string outputName,
            OutputKind outputKind,
            ModulePropertiesForSerialization serializationProperties,
            IEnumerable <ResourceDescription> manifestResources,
            Func <AssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            ImmutableArray <NamedTypeSymbol> additionalTypes,
            bool metadataOnly)
            : base((SourceModuleSymbol)sourceAssembly.Modules[0], outputName, outputKind, serializationProperties, manifestResources, assemblySymbolMapper, metadataOnly)
        {
            Debug.Assert((object)sourceAssembly != null);

            this.sourceAssembly  = sourceAssembly;
            this.additionalTypes = additionalTypes.NullToEmpty();
            this.metadataName    = outputName == null ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(outputName, extension: null);

            AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
        }
Пример #18
0
        public async Task ExecuteAsync(
            GetConfigsCommand.Parameters parameters)
        {
            var configType   = parameters.ConfigType;
            var username     = parameters.Username;
            var userId       = parameters.UserId;
            var outputFolder = parameters.OutputFolder;
            var format       = parameters.Format;
            var unwrap       = parameters.Unwrap;

            var simVersion = await this.simVersionCache.GetOrSet(parameters.SimVersion);

            var authenticatedUser = await this.ensureAuthenticated.ExecuteAsync();

            if (!string.IsNullOrWhiteSpace(username))
            {
                userId = await getUserIdFromUsername.ExecuteAsync(authenticatedUser.TenantId, username);
            }

            var filter = new JObject(
                new JProperty("continuationToken", null));

            if (!string.IsNullOrWhiteSpace(userId))
            {
                filter.Add(
                    new JProperty("filterUserId", userId));
            }

            this.logger.LogInformation("Requesting configs...");
            GetConfigsQueryResult?result = null;

            do
            {
                if (result != null)
                {
                    filter["continuationToken"] = result.QueryResults.ContinuationToken;
                }

                result = await this.configClient.GetConfigsAsync(
                    authenticatedUser.TenantId,
                    configType,
                    filter.ToString(Formatting.None),
                    null,
                    null);

                if (outputFolder != null)
                {
                    var outputFolderPath = this.getCreatedOutputFolder.Execute(outputFolder);

                    var sizes = new List <int>();

                    foreach (var configMetadata in result.QueryResults.Documents)
                    {
                        this.logger.LogInformation($"Downloading {configMetadata.Name}...");

                        var config = await this.configClient.GetConfigAsync(
                            configMetadata.TenantId,
                            configMetadata.DocumentId,
                            null,
                            simVersion,
                            null);

                        var content = JObject.FromObject(config.Config.Data);
                        if (!unwrap)
                        {
                            content = new JObject(
                                new JProperty("simVersion", config.ConvertedSimVersion),
                                new JProperty("config", content));
                        }

                        var formatting = format ? Formatting.Indented : Formatting.None;

                        var contentString = content.ToString(formatting);

                        await this.writeFile.ExecuteAsync(
                            Path.Combine(outputFolderPath, FileNameUtilities.Sanitize(config.Config.Name) + ".json"),
                            contentString);

                        sizes.Add(contentString.Length);
                    }

                    Utilities.WriteTable(
                        new[] { "Name", "Id", "UserId", "Size" },
                        result.QueryResults.Documents
                        .Zip(sizes, (d, s) => new { d, s }).Select(v => new string[] { v.d.Name, v.d.DocumentId, v.d.UserId, v.s.ToString() }));
                }
                else
                {
                    Utilities.WriteTable(
                        new[] { "Name", "Id", "UserId" },
                        result.QueryResults.Documents.Select(v => new string[] { v.Name, v.DocumentId, v.UserId }));
                }
            }while (result.QueryResults.HasMoreResults == true);
        }
Пример #19
0
 public static string ChangeExtension(string path, string extension)
 {
     return(FileNameUtilities.ChangeExtension(path, extension));
 }
Пример #20
0
        internal static EmitDifferenceResult EmitDifference(
            CSharpCompilation compilation,
            EmitBaseline baseline,
            IEnumerable <SemanticEdit> edits,
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
            ICollection <uint> updatedMethodTokens,
            CompilationTestData testData,
            CancellationToken cancellationToken)
        {
            Guid moduleVersionId;

            try
            {
                moduleVersionId = baseline.OriginalMetadata.GetModuleVersionId();
            }
            catch (BadImageFormatException)
            {
                // return MakeEmitResult(success: false, diagnostics: ..., baseline: null);
                throw;
            }

            var    pdbName                 = FileNameUtilities.ChangeExtension(compilation.SourceModule.Name, "pdb");
            var    diagnostics             = DiagnosticBag.GetInstance();
            string runtimeMDVersion        = compilation.GetRuntimeMetadataVersion(diagnostics);
            var    serializationProperties = compilation.ConstructModuleSerializationProperties(runtimeMDVersion, moduleVersionId);
            var    manifestResources       = SpecializedCollections.EmptyEnumerable <ResourceDescription>();

            var moduleBeingBuilt = new PEDeltaAssemblyBuilder(
                compilation.SourceAssembly,
                outputName: null,
                outputKind: compilation.Options.OutputKind,
                serializationProperties: serializationProperties,
                manifestResources: manifestResources,
                assemblySymbolMapper: null,
                previousGeneration: baseline,
                edits: edits);

            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            baseline = moduleBeingBuilt.PreviousGeneration;

            var definitionMap = moduleBeingBuilt.PreviousDefinitions;
            var changes       = moduleBeingBuilt.Changes;

            if (compilation.Compile(
                    moduleBeingBuilt,
                    outputName: null,
                    win32Resources: null,
                    xmlDocStream: null,
                    cancellationToken: cancellationToken,
                    generateDebugInfo: true,
                    diagnostics: diagnostics,
                    filterOpt: changes.RequiresCompilation))
            {
                // Map the definitions from the previous compilation to the current compilation.
                // This must be done after compiling above since synthesized definitions
                // (generated when compiling method bodies) may be required.
                baseline = MapToCompilation(compilation, moduleBeingBuilt);

                using (var pdbWriter = new Cci.PdbWriter(pdbName, pdbStream, (testData != null) ? testData.SymWriterFactory : null))
                {
                    var context = new EmitContext(moduleBeingBuilt, null, diagnostics);
                    var encId   = Guid.NewGuid();

                    try
                    {
                        var writer = new DeltaPeWriter(
                            context,
                            compilation.MessageProvider,
                            pdbWriter,
                            baseline,
                            encId,
                            definitionMap,
                            changes,
                            cancellationToken);

                        Cci.MetadataSizes metadataSizes;
                        writer.WriteMetadataAndIL(metadataStream, ilStream, out metadataSizes);
                        writer.GetMethodTokens(updatedMethodTokens);

                        return(new EmitDifferenceResult(
                                   success: true,
                                   diagnostics: diagnostics.ToReadOnlyAndFree(),
                                   baseline: writer.GetDelta(baseline, compilation, encId, metadataSizes)));
                    }
                    catch (Cci.PdbWritingException e)
                    {
                        diagnostics.Add(ErrorCode.FTL_DebugEmitFailure, Location.None, e.Message);
                    }
                    catch (PermissionSetFileReadException e)
                    {
                        diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message);
                    }
                }
            }

            return(new EmitDifferenceResult(success: false, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: null));
        }
Пример #21
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)));
        }