CommandLineParser.cs 69.1 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6 7 8 9 10 11

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
12
using Microsoft.CodeAnalysis.Emit;
13
using Microsoft.CodeAnalysis.Text;
P
Pilchie 已提交
14 15 16 17 18 19
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    public class CSharpCommandLineParser : CommandLineParser
    {
20 21
        public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser();

22
        public static CSharpCommandLineParser Interactive { get; } = new CSharpCommandLineParser(isInteractive: true);
P
Pilchie 已提交
23 24 25 26 27 28

        internal CSharpCommandLineParser(bool isInteractive = false)
            : base(CSharp.MessageProvider.Instance, isInteractive)
        {
        }

29 30
        protected override string RegularFileExtension { get { return ".cs"; } }
        protected override string ScriptFileExtension { get { return ".csx"; } }
P
Pilchie 已提交
31

32
        internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories)
P
Pilchie 已提交
33
        {
34
            return Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories);
P
Pilchie 已提交
35 36
        }

37 38 39 40 41 42 43 44 45
        /// <summary>
        /// Parses a command line.
        /// </summary>
        /// <param name="args">A collection of strings representing the command line arguments.</param>
        /// <param name="baseDirectory">The base directory used for qualifying file locations.</param>
        /// <param name="sdkDirectory">The directory to search for mscorlib.</param>
        /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param>
        /// <returns>a commandlinearguments object representing the parsed command line.</returns>
        public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null)
P
Pilchie 已提交
46
        {
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
            List<Diagnostic> diagnostics = new List<Diagnostic>();
            List<string> flattenedArgs = new List<string>();
            List<string> scriptArgs = IsInteractive ? new List<string>() : null;
            FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory);

            string appConfigPath = null;
            bool displayLogo = true;
            bool displayHelp = false;
            bool optimize = false;
            bool checkOverflow = false;
            bool allowUnsafe = false;
            bool concurrentBuild = true;
            bool emitPdb = false;
            string pdbPath = null;
            bool noStdLib = false;
            string outputDirectory = baseDirectory;
            string outputFileName = null;
            string documentationPath = null;
65
            string errorLogPath = null;
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid.
            bool utf8output = false;
            OutputKind outputKind = OutputKind.ConsoleApplication;
            SubsystemVersion subsystemVersion = SubsystemVersion.None;
            LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion;
            string mainTypeName = null;
            string win32ManifestFile = null;
            string win32ResourceFile = null;
            string win32IconFile = null;
            bool noWin32Manifest = false;
            Platform platform = Platform.AnyCpu;
            ulong baseAddress = 0;
            int fileAlignment = 0;
            bool? delaySignSetting = null;
            string keyFileSetting = null;
            string keyContainerSetting = null;
            List<ResourceDescription> managedResources = new List<ResourceDescription>();
            List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>();
            List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>();
            bool sourceFilesSpecified = false;
            bool resourcesOrModulesSpecified = false;
            Encoding codepage = null;
            var checksumAlgorithm = SourceHashAlgorithm.Sha1;
            var defines = ArrayBuilder<string>.GetInstance();
            List<CommandLineReference> metadataReferences = new List<CommandLineReference>();
            List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>();
            List<string> libPaths = new List<string>();
            List<string> keyFileSearchPaths = new List<string>();
            List<string> usings = new List<string>();
            var generalDiagnosticOption = ReportDiagnostic.Default;
            var diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
            var noWarns = new Dictionary<string, ReportDiagnostic>();
            var warnAsErrors = new Dictionary<string, ReportDiagnostic>();
            int warningLevel = 4;
            bool highEntropyVA = false;
            bool printFullPaths = false;
            string moduleAssemblyName = null;
            string moduleName = null;
            List<string> features = new List<string>();
            string runtimeMetadataVersion = null;
            bool errorEndLocation = false;
107
            bool reportAnalyzer = false;
108 109 110 111 112 113 114
            CultureInfo preferredUILang = null;
            string touchedFilesPath = null;
            var sqmSessionGuid = Guid.Empty;

            // Process ruleset files first so that diagnostic severity settings specified on the command line via
            // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
            if (!IsInteractive)
P
Pilchie 已提交
115
            {
116
                foreach (string arg in flattenedArgs)
117
                {
118 119
                    string name, value;
                    if (TryParseOption(arg, out name, out value) && (name == "ruleset"))
120
                    {
121
                        var unquoted = RemoveAllQuotes(value);
122

123 124 125 126 127 128 129
                        if (string.IsNullOrEmpty(unquoted))
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
                        }
                        else
                        {
                            generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory);
130 131 132
                        }
                    }
                }
133
            }
134

135 136 137 138 139 140
            foreach (string arg in flattenedArgs)
            {
                Debug.Assert(!arg.StartsWith("@", StringComparison.Ordinal));

                string name, value;
                if (!TryParseOption(arg, out name, out value))
P
Pilchie 已提交
141
                {
142 143 144 145
                    sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics));
                    sourceFilesSpecified = true;
                    continue;
                }
P
Pilchie 已提交
146

147 148 149 150 151
                switch (name)
                {
                    case "?":
                    case "help":
                        displayHelp = true;
P
Pilchie 已提交
152 153
                        continue;

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                    case "r":
                    case "reference":
                        metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false));
                        continue;

                    case "a":
                    case "analyzer":
                        analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics));
                        continue;

                    case "d":
                    case "define":
                        if (string.IsNullOrEmpty(value))
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
                            continue;
                        }

                        IEnumerable<Diagnostic> defineDiagnostics;
                        defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics));
                        diagnostics.AddRange(defineDiagnostics);
                        continue;

                    case "codepage":
                        if (value == null)
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
                            continue;
                        }

                        var encoding = TryParseEncodingName(value);
                        if (encoding == null)
                        {
                            AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value);
P
Pilchie 已提交
188
                            continue;
189
                        }
P
Pilchie 已提交
190

191 192 193 194 195 196 197
                        codepage = encoding;
                        continue;

                    case "checksumalgorithm":
                        if (string.IsNullOrEmpty(value))
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
P
Pilchie 已提交
198
                            continue;
199
                        }
P
Pilchie 已提交
200

201 202 203 204
                        var newChecksumAlgorithm = TryParseHashAlgorithmName(value);
                        if (newChecksumAlgorithm == SourceHashAlgorithm.None)
                        {
                            AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value);
P
Pilchie 已提交
205
                            continue;
206
                        }
P
Pilchie 已提交
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                        checksumAlgorithm = newChecksumAlgorithm;
                        continue;

                    case "checked":
                    case "checked+":
                        if (value != null)
                        {
                            break;
                        }

                        checkOverflow = true;
                        continue;

                    case "checked-":
                        if (value != null)
                            break;

                        checkOverflow = false;
                        continue;

                    case "features":
                        if (value == null)
                        {
                            features.Clear();
                        }
                        else
                        {
                            features.Add(value);
                        }
                        continue;

                    case "noconfig":
                        // It is already handled (see CommonCommandLineCompiler.cs).
                        continue;

                    case "sqmsessionguid":
                        if (value == null)
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name);
                        }
                        else
                        {
                            if (!Guid.TryParse(value, out sqmSessionGuid))
P
Pilchie 已提交
251
                            {
252
                                AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name);
P
Pilchie 已提交
253
                            }
254 255
                        }
                        continue;
P
Pilchie 已提交
256

257 258 259 260
                    case "preferreduilang":
                        if (string.IsNullOrEmpty(value))
                        {
                            AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
P
Pilchie 已提交
261
                            continue;
262
                        }
P
Pilchie 已提交
263

264 265 266
                        try
                        {
                            preferredUILang = new CultureInfo(value);
267
                            if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false)
268 269 270 271
                            {
                                // Do not use user custom cultures.
                                preferredUILang = null;
                            }
272 273
                        }
                        catch (CultureNotFoundException)
274 275 276 277
                        {
                        }

                        if (preferredUILang == null)
278 279 280
                        {
                            AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value);
                        }
281

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                        continue;

#if DEBUG
                    case "attachdebugger":
                        Debugger.Launch();
                        continue;
#endif
                }

                if (IsInteractive)
                {
                    switch (name)
                    {
                        // interactive:
                        case "rp":
                        case "referencepath":
                            // TODO: should it really go to libPaths?
                            ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics);
                            continue;

                        case "u":
                        case "using":
                            usings.AddRange(ParseUsings(arg, value, diagnostics));
                            continue;
                    }
                }
                else
                {
                    switch (name)
                    {
                        case "out":
                            if (string.IsNullOrWhiteSpace(value))
P
Pilchie 已提交
314
                            {
315
                                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
P
Pilchie 已提交
316
                            }
317
                            else
P
Pilchie 已提交
318
                            {
319
                                ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory);
P
Pilchie 已提交
320 321 322 323
                            }

                            continue;

324 325 326
                        case "t":
                        case "target":
                            if (value == null)
327
                            {
328
                                break; // force 'unrecognized option'
329 330
                            }

331
                            if (string.IsNullOrEmpty(value))
332
                            {
333 334 335 336 337
                                AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
                            }
                            else
                            {
                                outputKind = ParseTarget(value, diagnostics);
338 339 340 341
                            }

                            continue;

342 343 344 345
                        case "moduleassemblyname":
                            value = value != null ? value.Unquote() : null;

                            if (string.IsNullOrEmpty(value))
P
Pilchie 已提交
346
                            {
347 348 349 350 351 352 353 354 355 356
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
                            }
                            else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value))
                            {
                                // Dev11 C# doesn't check the name (VB does)
                                AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg);
                            }
                            else
                            {
                                moduleAssemblyName = value;
P
Pilchie 已提交
357 358 359 360
                            }

                            continue;

361 362 363 364 365 366 367 368 369 370 371
                        case "modulename":
                            var unquotedModuleName = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquotedModuleName))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename");
                                continue;
                            }
                            else
                            {
                                moduleName = unquotedModuleName;
                            }
P
Pilchie 已提交
372 373 374

                            continue;

375 376
                        case "platform":
                            if (string.IsNullOrEmpty(value))
P
Pilchie 已提交
377
                            {
378
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg);
P
Pilchie 已提交
379 380 381
                            }
                            else
                            {
382
                                platform = ParsePlatform(value, diagnostics);
P
Pilchie 已提交
383 384 385
                            }
                            continue;

386
                        case "recurse":
P
Pilchie 已提交
387 388
                            if (value == null)
                            {
389 390 391 392 393
                                break; // force 'unrecognized option'
                            }
                            else if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
P
Pilchie 已提交
394 395 396
                            }
                            else
                            {
397 398 399
                                int before = sourceFiles.Count;
                                sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics));
                                if (sourceFiles.Count > before)
P
Pilchie 已提交
400
                                {
401
                                    sourceFilesSpecified = true;
P
Pilchie 已提交
402 403 404
                                }
                            }
                            continue;
405

406 407
                        case "doc":
                            parseDocumentationComments = true;
408 409
                            if (string.IsNullOrEmpty(value))
                            {
410
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
411 412
                                continue;
                            }
413 414 415 416 417 418 419 420 421 422 423 424
                            string unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out)
                                // if we just let the next case handle /doc:"".
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument.
                            }
                            else
                            {
                                documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
                            }
                            continue;
425

426 427
                        case "addmodule":
                            if (value == null)
428
                            {
429
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:");
430
                            }
431
                            else if (string.IsNullOrEmpty(value))
432
                            {
433 434 435 436 437 438 439 440 441
                                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                            }
                            else
                            {
                                // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
                                // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
                                // An error will be reported by the assembly manager anyways.
                                metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module)));
                                resourcesOrModulesSpecified = true;
442 443 444
                            }
                            continue;

445 446 447
                        case "l":
                        case "link":
                            metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true));
P
Pilchie 已提交
448 449
                            continue;

450 451 452
                        case "win32res":
                            win32ResourceFile = GetWin32Setting(arg, value, diagnostics);
                            continue;
P
Pilchie 已提交
453

454 455 456
                        case "win32icon":
                            win32IconFile = GetWin32Setting(arg, value, diagnostics);
                            continue;
P
Pilchie 已提交
457

458 459 460 461
                        case "win32manifest":
                            win32ManifestFile = GetWin32Setting(arg, value, diagnostics);
                            noWin32Manifest = false;
                            continue;
P
Pilchie 已提交
462

463 464 465 466
                        case "nowin32manifest":
                            noWin32Manifest = true;
                            win32ManifestFile = null;
                            continue;
P
Pilchie 已提交
467

468 469 470 471
                        case "res":
                        case "resource":
                            if (value == null)
                            {
C
Charles Stoner 已提交
472
                                break; // Dev11 reports unrecognized option
473
                            }
P
Pilchie 已提交
474

475 476 477 478 479 480
                            var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true);
                            if (embeddedResource != null)
                            {
                                managedResources.Add(embeddedResource);
                                resourcesOrModulesSpecified = true;
                            }
P
Pilchie 已提交
481

482
                            continue;
P
Pilchie 已提交
483

484 485 486 487
                        case "linkres":
                        case "linkresource":
                            if (value == null)
                            {
C
Charles Stoner 已提交
488
                                break; // Dev11 reports unrecognized option
489
                            }
P
Pilchie 已提交
490

491 492 493 494 495 496
                            var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false);
                            if (linkedResource != null)
                            {
                                managedResources.Add(linkedResource);
                                resourcesOrModulesSpecified = true;
                            }
P
Pilchie 已提交
497

498
                            continue;
499

500 501
                        case "debug":
                            emitPdb = true;
502

503 504 505 506
                            // unused, parsed for backward compat only
                            if (value != null)
                            {
                                if (value.IsEmpty())
P
Pilchie 已提交
507
                                {
508
                                    AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name);
P
Pilchie 已提交
509
                                }
510 511
                                else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) &&
                                         !string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase))
P
Pilchie 已提交
512
                                {
513
                                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value);
P
Pilchie 已提交
514
                                }
515 516
                            }
                            continue;
P
Pilchie 已提交
517

518 519 520 521
                        case "debug+":
                            //guard against "debug+:xx"
                            if (value != null)
                                break;
P
Pilchie 已提交
522

523 524
                            emitPdb = true;
                            continue;
P
Pilchie 已提交
525

526 527 528
                        case "debug-":
                            if (value != null)
                                break;
P
Pilchie 已提交
529

530 531
                            emitPdb = false;
                            continue;
P
Pilchie 已提交
532

533 534 535 536 537 538
                        case "o":
                        case "optimize":
                        case "o+":
                        case "optimize+":
                            if (value != null)
                                break;
P
Pilchie 已提交
539

540 541
                            optimize = true;
                            continue;
P
Pilchie 已提交
542

543 544 545 546
                        case "o-":
                        case "optimize-":
                            if (value != null)
                                break;
P
Pilchie 已提交
547

548 549
                            optimize = false;
                            continue;
P
Pilchie 已提交
550

551 552 553 554 555 556
                        case "p":
                        case "parallel":
                        case "p+":
                        case "parallel+":
                            if (value != null)
                                break;
P
Pilchie 已提交
557

558 559
                            concurrentBuild = true;
                            continue;
P
Pilchie 已提交
560

561 562 563 564
                        case "p-":
                        case "parallel-":
                            if (value != null)
                                break;
P
Pilchie 已提交
565

566 567
                            concurrentBuild = false;
                            continue;
P
Pilchie 已提交
568

569 570 571 572 573
                        case "warnaserror":
                        case "warnaserror+":
                            if (value == null)
                            {
                                generalDiagnosticOption = ReportDiagnostic.Error;
574

575 576 577 578
                                // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins),
                                // and bump warnings to errors.
                                warnAsErrors.Clear();
                                foreach (var key in diagnosticOptions.Keys)
P
Pilchie 已提交
579
                                {
580
                                    if (diagnosticOptions[key] == ReportDiagnostic.Warn)
P
Pilchie 已提交
581
                                    {
582
                                        warnAsErrors[key] = ReportDiagnostic.Error;
P
Pilchie 已提交
583 584 585 586
                                    }
                                }

                                continue;
587
                            }
P
Pilchie 已提交
588

589 590 591 592 593 594 595 596 597
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
                            }
                            else
                            {
                                AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value));
                            }
                            continue;
P
Pilchie 已提交
598

599 600 601 602
                        case "warnaserror-":
                            if (value == null)
                            {
                                generalDiagnosticOption = ReportDiagnostic.Default;
P
Pilchie 已提交
603

604 605
                                // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
                                warnAsErrors.Clear();
P
Pilchie 已提交
606 607

                                continue;
608
                            }
P
Pilchie 已提交
609

610 611 612 613 614 615 616
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
                            }
                            else
                            {
                                foreach (var id in ParseWarnings(value))
P
Pilchie 已提交
617
                                {
618 619
                                    ReportDiagnostic ruleSetValue;
                                    if (diagnosticOptions.TryGetValue(id, out ruleSetValue))
620
                                    {
621
                                        warnAsErrors[id] = ruleSetValue;
622
                                    }
623
                                    else
624
                                    {
625
                                        warnAsErrors[id] = ReportDiagnostic.Default;
626
                                    }
P
Pilchie 已提交
627
                                }
628 629
                            }
                            continue;
P
Pilchie 已提交
630

631 632 633 634 635
                        case "w":
                        case "warn":
                            if (value == null)
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
P
Pilchie 已提交
636
                                continue;
637
                            }
P
Pilchie 已提交
638

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
                            int newWarningLevel;
                            if (string.IsNullOrEmpty(value) ||
                                !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
                            }
                            else if (newWarningLevel < 0 || newWarningLevel > 4)
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name);
                            }
                            else
                            {
                                warningLevel = newWarningLevel;
                            }
                            continue;
P
Pilchie 已提交
654

655 656 657 658
                        case "nowarn":
                            if (value == null)
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
P
Pilchie 已提交
659
                                continue;
660
                            }
P
Pilchie 已提交
661

662 663 664 665 666 667 668 669 670
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
                            }
                            else
                            {
                                AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value));
                            }
                            continue;
P
Pilchie 已提交
671

672 673 674 675
                        case "unsafe":
                        case "unsafe+":
                            if (value != null)
                                break;
P
Pilchie 已提交
676

677 678
                            allowUnsafe = true;
                            continue;
P
Pilchie 已提交
679

680 681 682
                        case "unsafe-":
                            if (value != null)
                                break;
P
Pilchie 已提交
683

684 685
                            allowUnsafe = false;
                            continue;
P
Pilchie 已提交
686

687 688 689 690 691 692 693 694 695 696
                        case "langversion":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:");
                            }
                            else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value);
                            }
                            continue;
P
Pilchie 已提交
697

698 699 700 701 702 703
                        case "delaysign":
                        case "delaysign+":
                            if (value != null)
                            {
                                break;
                            }
P
Pilchie 已提交
704

705 706
                            delaySignSetting = true;
                            continue;
P
Pilchie 已提交
707

708 709 710 711 712
                        case "delaysign-":
                            if (value != null)
                            {
                                break;
                            }
P
Pilchie 已提交
713

714 715
                            delaySignSetting = false;
                            continue;
P
Pilchie 已提交
716

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
                        case "keyfile":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile");
                            }
                            else
                            {
                                keyFileSetting = RemoveAllQuotes(value);
                            }
                            // NOTE: Dev11/VB also clears "keycontainer", see also:
                            //
                            // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by 
                            // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. 
                            // MSDN: If that succeeds, then the assembly is signed with the information in the key container. 
                            // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. 
                            // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key 
                            // MSDN: information will be installed in the key container (similar to sn -i) so that on the next 
                            // MSDN: compilation, the key container will be valid.
                            continue;
P
Pilchie 已提交
736

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
                        case "keycontainer":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer");
                            }
                            else
                            {
                                keyContainerSetting = value;
                            }
                            // NOTE: Dev11/VB also clears "keyfile", see also:
                            //
                            // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by 
                            // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. 
                            // MSDN: If that succeeds, then the assembly is signed with the information in the key container. 
                            // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. 
                            // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key 
                            // MSDN: information will be installed in the key container (similar to sn -i) so that on the next 
                            // MSDN: compilation, the key container will be valid.
                            continue;
P
Pilchie 已提交
756

757 758 759 760
                        case "highentropyva":
                        case "highentropyva+":
                            if (value != null)
                                break;
P
Pilchie 已提交
761

762 763
                            highEntropyVA = true;
                            continue;
P
Pilchie 已提交
764

765 766 767
                        case "highentropyva-":
                            if (value != null)
                                break;
P
Pilchie 已提交
768

769 770
                            highEntropyVA = false;
                            continue;
P
Pilchie 已提交
771

772 773 774
                        case "nologo":
                            displayLogo = false;
                            continue;
P
Pilchie 已提交
775

776 777 778 779
                        case "baseaddress":
                            ulong newBaseAddress;
                            if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress))
                            {
P
Pilchie 已提交
780 781
                                if (string.IsNullOrEmpty(value))
                                {
782
                                    AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
P
Pilchie 已提交
783 784 785
                                }
                                else
                                {
786
                                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value);
P
Pilchie 已提交
787
                                }
788 789 790 791 792
                            }
                            else
                            {
                                baseAddress = newBaseAddress;
                            }
793

794 795 796 797 798 799
                            continue;

                        case "subsystemversion":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion");
P
Pilchie 已提交
800
                                continue;
801
                            }
P
Pilchie 已提交
802

803 804 805 806 807 808 809 810 811 812
                            // It seems VS 2012 just silently corrects invalid values and suppresses the error message
                            SubsystemVersion version = SubsystemVersion.None;
                            if (SubsystemVersion.TryParse(value, out version))
                            {
                                subsystemVersion = version;
                            }
                            else
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value);
                            }
813

814
                            continue;
P
Pilchie 已提交
815

816 817 818 819 820
                        case "touchedfiles":
                            unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles");
P
Pilchie 已提交
821
                                continue;
822 823 824 825 826
                            }
                            else
                            {
                                touchedFilesPath = unquoted;
                            }
P
Pilchie 已提交
827

828
                            continue;
P
Pilchie 已提交
829

830 831 832
                        case "bugreport":
                            UnimplementedSwitch(diagnostics, name);
                            continue;
P
Pilchie 已提交
833

834 835 836 837 838 839
                        case "utf8output":
                            if (value != null)
                                break;

                            utf8output = true;
                            continue;
P
Pilchie 已提交
840

841 842 843 844 845 846 847 848
                        case "m":
                        case "main":
                            // Remove any quotes for consistent behaviour as MSBuild can return quoted or 
                            // unquoted main.    
                            unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
P
Pilchie 已提交
849
                                continue;
850
                            }
P
Pilchie 已提交
851

852 853
                            mainTypeName = unquoted;
                            continue;
P
Pilchie 已提交
854

855 856 857
                        case "fullpaths":
                            if (value != null)
                                break;
P
Pilchie 已提交
858

859 860
                            printFullPaths = true;
                            continue;
P
Pilchie 已提交
861

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
                        case "filealign":
                            ushort newAlignment;
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
                            }
                            else if (!TryParseUInt16(value, out newAlignment))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
                            }
                            else if (!CompilationOptions.IsValidFileAlignment(newAlignment))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
                            }
                            else
                            {
                                fileAlignment = newAlignment;
                            }
                            continue;
P
Pilchie 已提交
881

882 883 884 885 886 887 888 889 890 891
                        case "pdb":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                            }
                            else
                            {
                                pdbPath = ParsePdbPath(value, diagnostics, baseDirectory);
                            }
                            continue;
P
Pilchie 已提交
892

893 894 895
                        case "errorendlocation":
                            errorEndLocation = true;
                            continue;
P
Pilchie 已提交
896

897 898 899 900
                        case "reportanalyzer":
                            reportAnalyzer = true;
                            continue;

901 902 903 904
                        case "nostdlib":
                        case "nostdlib+":
                            if (value != null)
                                break;
P
Pilchie 已提交
905

906 907
                            noStdLib = true;
                            continue;
P
Pilchie 已提交
908

909 910 911
                        case "lib":
                            ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics);
                            continue;
P
Pilchie 已提交
912

913 914 915
                        case "nostdlib-":
                            if (value != null)
                                break;
P
Pilchie 已提交
916

917 918
                            noStdLib = false;
                            continue;
P
Pilchie 已提交
919

920 921
                        case "errorreport":
                            continue;
P
Pilchie 已提交
922

923 924 925 926 927 928 929 930 931 932 933 934
                        case "errorlog":
                            unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveAllQuotes(arg));
                            }
                            else
                            {
                                errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
                            }
                            continue;

935 936 937 938 939 940 941 942
                        case "appconfig":
                            unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg));
                            }
                            else
                            {
943
                                appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
944 945
                            }
                            continue;
P
Pilchie 已提交
946

947 948 949 950 951
                        case "runtimemetadataversion":
                            unquoted = RemoveAllQuotes(value);
                            if (string.IsNullOrEmpty(unquoted))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
P
Pilchie 已提交
952
                                continue;
953
                            }
P
Pilchie 已提交
954

955 956
                            runtimeMetadataVersion = unquoted;
                            continue;
957

958 959 960
                        case "ruleset":
                            // The ruleset arg has already been processed in a separate pass above.
                            continue;
961

962 963 964 965
                        case "additionalfile":
                            if (string.IsNullOrEmpty(value))
                            {
                                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name);
966
                                continue;
967
                            }
P
Pilchie 已提交
968

969 970 971
                            additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics));
                            continue;
                    }
P
Pilchie 已提交
972 973
                }

974 975
                AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg);
            }
976

977 978 979 980
            foreach (var o in warnAsErrors)
            {
                diagnosticOptions[o.Key] = o.Value;
            }
981

982 983 984 985 986
            // Specific nowarn options always override specific warnaserror options.
            foreach (var o in noWarns)
            {
                diagnosticOptions[o.Key] = o.Value;
            }
P
Pilchie 已提交
987

988 989 990 991
            if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified))
            {
                AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources);
            }
P
Pilchie 已提交
992

993 994
            if (!noStdLib)
            {
J
Jared Parsons 已提交
995
                metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly));
996
            }
P
Pilchie 已提交
997

998 999 1000
            if (!platform.Requires64Bit())
            {
                if (baseAddress > uint.MaxValue - 0x8000)
P
Pilchie 已提交
1001
                {
1002 1003
                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress));
                    baseAddress = 0;
P
Pilchie 已提交
1004
                }
1005
            }
P
Pilchie 已提交
1006

1007
            // add additional reference paths if specified
1008
            if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories))
1009
            {
1010
                ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics);
1011
            }
P
Pilchie 已提交
1012

1013
            ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths);
P
Pilchie 已提交
1014

1015
            ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics);
P
Pilchie 已提交
1016

1017 1018 1019 1020 1021 1022 1023
            // Dev11 searches for the key file in the current directory and assembly output directory.
            // We always look to base directory and then examine the search paths.
            keyFileSearchPaths.Add(baseDirectory);
            if (baseDirectory != outputDirectory)
            {
                keyFileSearchPaths.Add(outputDirectory);
            }
P
Pilchie 已提交
1024

1025 1026 1027
            if (!emitPdb)
            {
                if (pdbPath != null)
P
Pilchie 已提交
1028
                {
1029 1030 1031
                    // Can't give a PDB file name and turn off debug information
                    AddDiagnostic(diagnostics, ErrorCode.ERR_MissingDebugSwitch);
                }
P
Pilchie 已提交
1032
            }
1033 1034 1035 1036 1037 1038 1039 1040 1041

            string compilationName;
            GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName);

            var parseOptions = new CSharpParseOptions
            (
                languageVersion: languageVersion,
                preprocessorSymbols: defines.ToImmutableAndFree(),
                documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None,
1042
                kind: SourceCodeKind.Regular,
1043
                features: ParseFeatures(features)
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            );

            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            var options = new CSharpCompilationOptions
            (
                outputKind: outputKind,
                moduleName: moduleName,
                mainTypeName: mainTypeName,
                scriptClassName: WellKnownMemberNames.DefaultScriptClassName,
                usings: usings,
                optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug,
                checkOverflow: checkOverflow,
                allowUnsafe: allowUnsafe,
                concurrentBuild: concurrentBuild,
                cryptoKeyContainer: keyContainerSetting,
                cryptoKeyFile: keyFileSetting,
                delaySign: delaySignSetting,
                platform: platform,
                generalDiagnosticOption: generalDiagnosticOption,
                warningLevel: warningLevel,
1065
                specificDiagnosticOptions: diagnosticOptions
1066
            );
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

            var emitOptions = new EmitOptions
            (
                metadataOnly: false,
                debugInformationFormat: DebugInformationFormat.Pdb,
                pdbFilePath: null, // to be determined later
                outputNameOverride: null, // to be determined later
                baseAddress: baseAddress,
                highEntropyVirtualAddressSpace: highEntropyVA,
                fileAlignment: fileAlignment,
                subsystemVersion: subsystemVersion,
                runtimeMetadataVersion: runtimeMetadataVersion
            );

            // add option incompatibility errors if any
            diagnostics.AddRange(options.Errors);

            return new CSharpCommandLineArguments
            {
                IsInteractive = IsInteractive,
                BaseDirectory = baseDirectory,
                Errors = diagnostics.AsImmutable(),
                Utf8Output = utf8output,
                CompilationName = compilationName,
                OutputFileName = outputFileName,
                PdbPath = pdbPath,
                EmitPdb = emitPdb,
                OutputDirectory = outputDirectory,
                DocumentationPath = documentationPath,
1096
                ErrorLogPath = errorLogPath,
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
                AppConfigPath = appConfigPath,
                SourceFiles = sourceFiles.AsImmutable(),
                Encoding = codepage,
                ChecksumAlgorithm = checksumAlgorithm,
                MetadataReferences = metadataReferences.AsImmutable(),
                AnalyzerReferences = analyzers.AsImmutable(),
                AdditionalFiles = additionalFiles.AsImmutable(),
                ReferencePaths = referencePaths,
                KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
                Win32ResourceFile = win32ResourceFile,
                Win32Icon = win32IconFile,
                Win32Manifest = win32ManifestFile,
                NoWin32Manifest = noWin32Manifest,
                DisplayLogo = displayLogo,
                DisplayHelp = displayHelp,
                ManifestResources = managedResources.AsImmutable(),
                CompilationOptions = options,
                ParseOptions = IsInteractive ? scriptParseOptions : parseOptions,
                EmitOptions = emitOptions,
                ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
                TouchedFilesPath = touchedFilesPath,
                PrintFullPaths = printFullPaths,
                ShouldIncludeErrorEndLocation = errorEndLocation,
                PreferredUILang = preferredUILang,
1121 1122
                SqmSessionGuid = sqmSessionGuid,
                ReportAnalyzer = reportAnalyzer
1123
            };
P
Pilchie 已提交
1124
        }
1125

P
Pilchie 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

        private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics)
        {
            if (string.IsNullOrEmpty(switchValue))
            {
                Debug.Assert(!string.IsNullOrEmpty(switchName));
                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName);
                return;
            }

            foreach (string path in ParseSeparatedPaths(switchValue))
            {
                string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
                if (resolvedPath == null)
                {
                    AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize());
                }
1143
                else if (!PortableShim.Directory.Exists(resolvedPath))
P
Pilchie 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
                {
                    AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize());
                }
                else
                {
                    builder.Add(resolvedPath);
                }
            }
        }

        private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics)
        {
            if (value == null)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
            }
            else
            {
                string noQuotes = RemoveAllQuotes(value);
                if (string.IsNullOrWhiteSpace(noQuotes))
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                }
                else
                {
                    return noQuotes;
                }
            }

            return null;
        }

        private void GetCompilationAndModuleNames(
            List<Diagnostic> diagnostics,
            OutputKind outputKind,
            List<CommandLineSourceFile> sourceFiles,
            bool sourceFilesSpecified,
            string moduleAssemblyName,
            ref string outputFileName,
            ref string moduleName,
            out string compilationName)
        {
            string simpleName;
            if (outputFileName == null)
            {
                // In C#, if the output file name isn't specified explicitly, then executables take their
                // names from the files containing their entrypoints and libraries derive their names from 
                // their first input files.

                if (!IsInteractive && !sourceFilesSpecified)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName);
                    simpleName = null;
                }
                else if (outputKind.IsApplication())
                {
                    simpleName = null;
                }
                else
                {
                    simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path));
                    outputFileName = simpleName + outputKind.GetDefaultExtension();
1206 1207 1208 1209 1210 1211

                    if (simpleName.Length == 0 && !outputKind.IsNetModule())
                    {
                        AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
                        outputFileName = simpleName = null;
                    }
P
Pilchie 已提交
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
                }
            }
            else
            {
                simpleName = PathUtilities.RemoveExtension(outputFileName);

                if (simpleName.Length == 0)
                {
                    AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
                    outputFileName = simpleName = null;
                }
            }

            if (outputKind.IsNetModule())
            {
                Debug.Assert(!IsInteractive);

                compilationName = moduleAssemblyName;
            }
            else
            {
                if (moduleAssemblyName != null)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule);
                }

                compilationName = simpleName;
            }

            if (moduleName == null)
            {
                moduleName = outputFileName;
            }
        }

1247
        private static ImmutableArray<string> BuildSearchPaths(string sdkDirectory, List<string> libPaths)
P
Pilchie 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256
        {
            var builder = ArrayBuilder<string>.GetInstance();

            // Match how Dev11 builds the list of search paths
            //    see PCWSTR LangCompiler::GetSearchPath()

            // current folder first -- base directory is searched by default

            // SDK path is specified or current runtime directory
1257
            builder.Add(sdkDirectory);
P
Pilchie 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

            // libpath
            builder.AddRange(libPaths);

            return builder.ToImmutableAndFree();
        }

        public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics)
        {
            Diagnostic myDiagnostic = null;

            value = value.TrimEnd(null);
            // Allow a trailing semicolon or comma in the options
            if (!value.IsEmpty() &&
                (value.Last() == ';' || value.Last() == ','))
            {
                value = value.Substring(0, value.Length - 1);
            }

            string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/);
            var defines = new ArrayBuilder<string>(values.Length);

            foreach (string id in values)
            {
                string trimmedId = id.Trim();
                if (SyntaxFacts.IsValidIdentifier(trimmedId))
                {
                    defines.Add(trimmedId);
                }
                else if (myDiagnostic == null)
                {
                    myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId);
                }
            }

            diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>()
                                                : SpecializedCollections.SingletonEnumerable(myDiagnostic);

            return defines.AsEnumerable();
        }

        private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics)
        {
            switch (value.ToLowerInvariant())
            {
                case "x86":
                    return Platform.X86;
                case "x64":
                    return Platform.X64;
                case "itanium":
                    return Platform.Itanium;
                case "anycpu":
                    return Platform.AnyCpu;
                case "anycpu32bitpreferred":
                    return Platform.AnyCpu32BitPreferred;
                case "arm":
                    return Platform.Arm;
                default:
                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value);
                    return Platform.AnyCpu;
            }
        }

        private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics)
        {
            switch (value.ToLowerInvariant())
            {
                case "exe":
                    return OutputKind.ConsoleApplication;

                case "winexe":
                    return OutputKind.WindowsApplication;

                case "library":
                    return OutputKind.DynamicallyLinkedLibrary;

                case "module":
                    return OutputKind.NetModule;

                case "appcontainerexe":
                    return OutputKind.WindowsRuntimeApplication;

                case "winmdobj":
                    return OutputKind.WindowsRuntimeMetadata;

                default:
                    AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
                    return OutputKind.ConsoleApplication;
            }
        }

        private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics)
        {
            if (value.Length == 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg);
                yield break;
            }

            foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                yield return u;
            }
        }

1363
        private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics)
P
Pilchie 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        {
            if (value == null)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
                yield break;
            }
            else if (value.Length == 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                yield break;
1374
            }
P
Pilchie 已提交
1375 1376 1377 1378 1379

            List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();

            foreach (string path in paths)
            {
1380
                yield return new CommandLineAnalyzerReference(path);
P
Pilchie 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
            }
        }

        private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
        {
            if (value == null)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
                yield break;
            }
            else if (value.Length == 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                yield break;
            }

            // /r:"reference"
            // /r:alias=reference
            // /r:alias="reference"
            // /r:reference;reference
            // /r:"path;containing;semicolons"
            // /r:"unterminated_quotes
            // /r:"quotes"in"the"middle
            // /r:alias=reference;reference      ... error 2034
            // /r:nonidf=reference               ... error 1679

            int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });

            string alias;
            if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
            {
                alias = value.Substring(0, eqlOrQuote);
                value = value.Substring(eqlOrQuote + 1);

                if (!SyntaxFacts.IsValidIdentifier(alias))
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
                    yield break;
                }
            }
            else
            {
                alias = null;
            }

            List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
            if (alias != null)
            {
                if (paths.Count > 1)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
                    yield break;
                }

                if (paths.Count == 0)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
                    yield break;
                }
            }

            foreach (string path in paths)
            {
                // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
                // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.

1447 1448 1449
                var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;

                var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
1450
                yield return new CommandLineReference(path, properties);
P
Pilchie 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
            }
        }

        private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics)
        {
            if (win32ResourceFile != null)
            {
                if (win32IconResourceFile != null)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon);
                }

                if (win32ManifestFile != null)
                {
                    AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest);
                }
            }

            if (outputKind.IsNetModule() && win32ManifestFile != null)
            {
                AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule);
            }
        }

        internal static ResourceDescription ParseResourceDescription(
            string arg,
            string resourceDescriptor,
            string baseDirectory,
            IList<Diagnostic> diagnostics,
            bool embedded)
        {
            string filePath;
            string fullPath;
            string fileName;
            string resourceName;
            string accessibility;

            ParseResourceDescription(
                resourceDescriptor,
                baseDirectory,
                false,
                out filePath,
                out fullPath,
                out fileName,
                out resourceName,
                out accessibility);

            bool isPublic;
            if (accessibility == null)
            {
                // If no accessibility is given, we default to "public".
                // NOTE: Dev10 distinguishes between null and empty/whitespace-only.
                isPublic = true;
            }
            else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
            {
                isPublic = true;
            }
            else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
            {
                isPublic = false;
            }
            else
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
                return null;
            }

            if (string.IsNullOrEmpty(filePath))
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                return null;
            }

            if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
                return null;
            }

1531 1532 1533 1534
            Func<Stream> dataProvider = () =>
                                            {
                                                // Use FileShare.ReadWrite because the file could be opened by the current process.
                                                // For example, it is an XML doc file produced by the build.
1535
                                                return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite);
1536
                                            };
P
Pilchie 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
            return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
        }

        private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version)
        {
            if (str == null)
            {
                version = defaultVersion;
                return true;
            }

            switch (str.ToLowerInvariant())
            {
                case "iso-1":
                    version = LanguageVersion.CSharp1;
                    return true;

                case "iso-2":
                    version = LanguageVersion.CSharp2;
                    return true;

                case "default":
                    version = defaultVersion;
                    return true;
1561

P
Pilchie 已提交
1562 1563
                default:
                    int versionNumber;
N
nmgafter 已提交
1564
                    if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid())
P
Pilchie 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573
                    {
                        version = (LanguageVersion)versionNumber;
                        return true;
                    }
                    version = defaultVersion;
                    return false;
            }
        }

1574
        private static IEnumerable<string> ParseWarnings(string value)
P
Pilchie 已提交
1575
        {
1576
            value = value.Unquote();
P
Pilchie 已提交
1577 1578 1579 1580
            string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string id in values)
            {
                ushort number;
1581 1582
                if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) &&
                    ErrorFacts.IsWarning((ErrorCode)number))
P
Pilchie 已提交
1583
                {
1584 1585
                    // The id refers to a compiler warning.
                    yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number);
P
Pilchie 已提交
1586 1587 1588
                }
                else
                {
1589 1590 1591 1592 1593
                    // Previous versions of the compiler used to report a warning (CS1691)
                    // whenever an unrecognized warning code was supplied in /nowarn or 
                    // /warnaserror. We no longer generate a warning in such cases.
                    // Instead we assume that the unrecognized id refers to a custom diagnostic.
                    yield return id;
P
Pilchie 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
                }
            }
        }

        private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
        {
            foreach (var id in items)
            {
                ReportDiagnostic existing;
                if (d.TryGetValue(id, out existing))
                {
                    // Rewrite the existing value with the latest one unless it is for /nowarn.
                    if (existing != ReportDiagnostic.Suppress)
                        d[id] = kind;
                }
                else
                {
                    d.Add(id, kind);
                }
            }
        }

        private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName)
        {
            AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName);
        }

        private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value)
        {
            AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value);
        }

        internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics)
        {
            //  no error in csc.exe
        }

P
Pharring 已提交
1631 1632 1633 1634 1635
        private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode)
        {
            diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode));
        }

P
Pilchie 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
        private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
        {
            diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments));
        }

        /// <summary>
        /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode.
        /// </summary>
        private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments)
        {
            int code = (int)errorCode;
            ReportDiagnostic value;
            warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value);
            if (value != ReportDiagnostic.Suppress)
            {
                AddDiagnostic(diagnostics, errorCode, arguments);
            }
        }
    }
}