private static Stream OpenStream(CommonMessageProvider messageProvider, string path, string baseDirectory, int errorCode, IList <DiagnosticInfo> errors)
        {
            if (path == null)
            {
                return(null);
            }

            string fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, errors);

            if (fullPath == null)
            {
                return(null);
            }

            try
            {
                return(new FileStream(fullPath, FileMode.Open, FileAccess.Read));
            }
            catch (Exception ex)
            {
                errors.Add(ReflDiagnosticInfo.ctor(messageProvider, errorCode, new[] { fullPath, ex.Message }));
            }

            return(null);
        }
        // internal for testing
        internal static Stream GetWin32ResourcesInternal(CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable <DiagnosticInfo> errors)
        {
            List <DiagnosticInfo> errorList = new List <DiagnosticInfo>();

            errors = errorList;

            if (arguments.Win32ResourceFile != null)
            {
                return(OpenStream(messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.GetFieldOrProperty <int>("ERR_CantOpenWin32Resource"), errorList));
            }

            using (Stream manifestStream = OpenManifestStream(messageProvider, compilation.Options.OutputKind, arguments, errorList))
            {
                using (Stream iconStream = OpenStream(messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.GetFieldOrProperty <int>("ERR_CantOpenWin32Icon"), errorList))
                {
                    try
                    {
                        return(compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream));
                    }
                    catch (Exception ex) when(ex.GetType().FullName == "Microsoft.CodeAnalysis.ResourceException")
                    {
                        errorList.Add(ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("ERR_ErrorBuildingWin32Resource"), new[] { ex.Message }));
                    }
                    catch (OverflowException ex)
                    {
                        errorList.Add(ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("ERR_ErrorBuildingWin32Resource"), new[] { ex.Message }));
                    }
                }
            }

            return(null);
        }
        private static string ResolveRelativePath(CommonMessageProvider messageProvider, string path, string baseDirectory, IList <DiagnosticInfo> errors)
        {
            string fullPath = (string)Refl.Type_FileUtilities.InvokeFunction("ResolveRelativePath", path, baseDirectory);

            if (fullPath == null)
            {
                errors.Add(ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("FTL_InputFileNameTooLong"), new[] { path }));
            }

            return(fullPath);
        }
        private Stream OpenFile(string filePath, TextWriter consoleOutput, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None)
        {
            try
            {
                return(FileOpen(filePath, mode, access, share));
            }
            catch (Exception e)
            {
                if (consoleOutput != null)
                {
                    // TODO: distinct error message?
                    DiagnosticInfo diagnosticInfo = ReflDiagnosticInfo.ctor(MessageProvider, (int)MessageProvider.GetFieldOrProperty <int>("ERR_OutputWriteFailed"), new[] { filePath, e.Message });
                    consoleOutput.WriteLine(diagnosticInfo.InvokeFunction("ToString", Culture));
                }

                return(null);
            }
        }
        /// <summary>
        /// csc.exe and vbc.exe entry point.
        /// </summary>
        public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default(CancellationToken))
        {
            var          saveUICulture = CultureInfo.CurrentUICulture;
            ErrorLogger2 errorLogger   = null;

            try
            {
                // Messages from exceptions can be used as arguments for errors and they are often localized.
                // Ensure they are localized to the right language.
                var culture = this.Culture;
                if (culture != null)
                {
                    Compatibility.SetCurrentUICulture(culture);
                }

                if (Arguments.ErrorLogPath != null)
                {
                    errorLogger = GetErrorLogger(consoleOutput, cancellationToken);
                    if (errorLogger == null)
                    {
                        return(Failed);
                    }
                }

                return(RunCore(consoleOutput, errorLogger, cancellationToken));
            }
            catch (OperationCanceledException)
            {
                var errorCode = MessageProvider.GetFieldOrProperty <int>("ERR_CompileCancelled");
                if (errorCode > 0)
                {
                    var diag = ReflDiagnosticInfo.ctor(MessageProvider, errorCode, new object[] {});
                    ReportErrors(new[] { diag }, consoleOutput, errorLogger);
                }

                return(Failed);
            }
            finally
            {
                Compatibility.SetCurrentUICulture(saveUICulture);
                ((IDisposable)errorLogger)?.Dispose();
            }
        }
        internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath)
        {
            DiagnosticInfo diagnosticInfo;

            if (e is FileNotFoundException || e.GetType().Name == "DirectoryNotFoundException")
            {
                diagnosticInfo = ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("ERR_FileNotFound"), new[] { filePath });
            }
            else if (e is InvalidDataException)
            {
                diagnosticInfo = ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("ERR_BinaryFile"), new[] { filePath });
            }
            else
            {
                diagnosticInfo = ReflDiagnosticInfo.ctor(messageProvider, messageProvider.GetFieldOrProperty <int>("ERR_NoSourceFile"), new[] { filePath, e.Message });
            }

            return(diagnosticInfo);
        }
Exemplo n.º 7
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger2 errorLogger)
        {
            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];

            for (int i = 0; i < sourceFiles.Length; i++)
            {
                //NOTE: order of trees is important!!
                trees[i] = ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger, out normalizedFilePaths[i]);
            }


            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                return(null);
            }

            var diagnostics = typeof(List <>).MakeGenericTypeFast(Refl.Type_DiagnosticInfo).InvokeFunction(".ctor");

            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(ReflPathUtilities.IsAbsolute(normalizedFilePath));

                if (!uniqueFilePaths.Add(normalizedFilePath))
                {
                    // warning CS2002: Source file '{0}' specified multiple times
                    diagnostics.InvokeAction("Add", ReflDiagnosticInfo.ctor(MessageProvider, (int)Compatibility.WRN_FileAlreadyIncluded,
                                                                            new object[] { Arguments.PrintFullPaths?normalizedFilePath: ReflCommandLineDiagnosticFormatter.RelativizeNormalizedPath(_diagnosticFormatter, normalizedFilePath) }));

                    trees[i] = null;
                }
            }

            if (Arguments.TouchedFilesPath != null)
            {
                foreach (var path in uniqueFilePaths)
                {
                    ReflTouchedFileLogger.AddRead(touchedFilesLogger, 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)
                    {
                        ReflTouchedFileLogger.AddRead(touchedFilesLogger, appConfigPath);
                    }
                }
                catch (Exception ex)
                {
                    diagnostics.InvokeAction("Add", ReflDiagnosticInfo.ctor(MessageProvider, (int)Compatibility.ERR_CantReadConfigFile, new object[] { appConfigPath, ex.Message }));
                }
            }

            var xmlFileResolver    = ReflLoggingXmlFileResolver.ctor(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = ReflLoggingSourceFileResolver.ctor(ImmutableArray <string> .Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger);

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

            if (ReportErrors((IEnumerable <DiagnosticInfo>)diagnostics, consoleOutput, errorLogger))
            {
                return(null);
            }

            var strongNameProvider = ReflLoggingStrongNameProvider.ctor(Arguments.KeyFileSearchPaths, touchedFilesLogger);

            var compilation = CSharpCompilation.Create(
                Arguments.CompilationName,
                trees.Where(x => x != null),
                resolvedReferences,
                Arguments.CompilationOptions.
                WithMetadataReferenceResolver(referenceDirectiveResolver).
                WithAssemblyIdentityComparer(assemblyIdentityComparer).
                WithStrongNameProvider(strongNameProvider).
                WithXmlReferenceResolver(xmlFileResolver).
                WithSourceReferenceResolver(sourceFileResolver));

            return(compilation);
        }