CommandLineTests.cs 500.3 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

using System;
using System.Collections.Generic;
5
using System.Collections.Immutable;
P
Pilchie 已提交
6
using System.ComponentModel;
7
using System.Diagnostics;
P
Pilchie 已提交
8 9
using System.Globalization;
using System.IO;
10
using System.IO.MemoryMappedFiles;
P
Pilchie 已提交
11 12
using System.Linq;
using System.Reflection;
13
using System.Reflection.Metadata;
P
Pilchie 已提交
14 15
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
16
using System.Security.Cryptography;
P
Pilchie 已提交
17 18 19 20
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
21
using Microsoft.CodeAnalysis.CSharp.Syntax;
P
Pilchie 已提交
22 23
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
24
using Microsoft.CodeAnalysis.Emit;
P
Pilchie 已提交
25
using Microsoft.CodeAnalysis.Test.Utilities;
26
using Microsoft.CodeAnalysis.Text;
27 28
using Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
P
Pilchie 已提交
29 30 31
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
32
using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers;
33
using static Roslyn.Test.Utilities.SharedResourceHelpers;
V
VSadov 已提交
34

35
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
P
Pilchie 已提交
36
{
J
Jared Parsons 已提交
37
    public class CommandLineTests : CommandLineTestBase
P
Pilchie 已提交
38
    {
39 40
        private static readonly string s_CSharpCompilerExecutable = Path.Combine(
            Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location),
J
Jared Parsons 已提交
41
            Path.Combine("dependency", "csc.exe"));
J
Jared Parsons 已提交
42

43 44 45
        private static readonly string s_compilerVersion = typeof(CommandLineTests).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
        private static readonly string s_compilerCommitHash = typeof(CommandLineTests).Assembly.GetCustomAttribute<CommitHashAttribute>()?.Hash;
        private static readonly string s_compilerShortCommitHash = CommonCompiler.ExtractShortCommitHash(s_compilerCommitHash);
P
Pilchie 已提交
46 47 48

        private class TestCommandLineParser : CSharpCommandLineParser
        {
49 50 51
            private readonly Dictionary<string, string> _responseFiles;
            private readonly Dictionary<string, string[]> _recursivePatterns;
            private readonly Dictionary<string, string[]> _patterns;
P
Pilchie 已提交
52 53 54 55 56 57 58 59

            public TestCommandLineParser(
                Dictionary<string, string> responseFiles = null,
                Dictionary<string, string[]> patterns = null,
                Dictionary<string, string[]> recursivePatterns = null,
                bool isInteractive = false)
                : base(isInteractive)
            {
60 61 62
                _responseFiles = responseFiles;
                _recursivePatterns = recursivePatterns;
                _patterns = patterns;
P
Pilchie 已提交
63 64
            }

65 66 67
            internal override IEnumerable<string> EnumerateFiles(string directory,
                                                                 string fileNamePattern,
                                                                 SearchOption searchOption)
P
Pilchie 已提交
68 69
            {
                var key = directory + "|" + fileNamePattern;
70
                if (searchOption == SearchOption.TopDirectoryOnly)
P
Pilchie 已提交
71
                {
72
                    return _patterns[key];
P
Pilchie 已提交
73 74 75
                }
                else
                {
76
                    return _recursivePatterns[key];
P
Pilchie 已提交
77 78 79 80 81
                }
            }

            internal override TextReader CreateTextFileReader(string fullPath)
            {
82
                return new StringReader(_responseFiles[fullPath]);
P
Pilchie 已提交
83 84
            }
        }
85

J
Jared Parsons 已提交
86
        private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory)
87
        {
J
Jared Parsons 已提交
88
            return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory);
89 90
        }

J
Jared Parsons 已提交
91
        private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null)
92
        {
J
Jared Parsons 已提交
93
            sdkDirectory = sdkDirectory ?? SdkDirectory;
94 95 96 97
            var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true);
            return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories);
        }

98
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)]
99 100 101 102 103 104
        public void XmlMemoryMapped()
        {
            var dir = Temp.CreateDirectory();
            var src = dir.CreateFile("temp.cs").WriteAllText("class C {}");
            const string docName = "doc.xml";

J
Jared Parsons 已提交
105
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path });
106 107 108 109 110 111

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString());

A
Andy Gocke 已提交
112 113 114
            var xmlPath = Path.Combine(dir.Path, docName);
            using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true))
115
            {
A
Andy Gocke 已提交
116 117
                exitCode = cmd.Run(outWriter);
                Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString());
118
                Assert.Equal(1, exitCode);
119 120 121
            }
        }

A
Andy Gocke 已提交
122

123
        // This test should only run when the machine's default encoding is shift-JIS
J
Jared Parsons 已提交
124
        [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
125 126 127 128 129
        public void CompileShiftJisOnShiftJis()
        {
            var dir = Temp.CreateDirectory();
            var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource);

J
Jared Parsons 已提交
130
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path });
131 132 133 134 135 136 137 138 139 140 141 142 143

            Assert.Null(cmd.Arguments.Encoding);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString());

            var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path);
            Assert.Equal(0, result.ExitCode);
            Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932)));
        }

J
Jared Parsons 已提交
144
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
A
Andy Gocke 已提交
145 146 147 148 149
        public void RunWithShiftJisFile()
        {
            var dir = Temp.CreateDirectory();
            var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource);

J
Jared Parsons 已提交
150
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path });
A
Andy Gocke 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163

            Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString());

            var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path);
            Assert.Equal(0, result.ExitCode);
            Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932)));
        }

J
Jared Parsons 已提交
164
        [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")]
J
Jared Parsons 已提交
165
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
166 167
        public void CompilerBinariesAreAnyCPU()
        {
168
            Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture);
169
        }
170

P
Pilchie 已提交
171 172 173 174 175 176 177 178 179 180
        [Fact]
        public void ResponseFiles1()
        {
            string rsp = Temp.CreateFile().WriteAllText(@"
/r:System.dll
/nostdlib
# this is ignored
System.Console.WriteLine(""*?"");  # this is error
a.cs
").Path;
J
Jared Parsons 已提交
181
            var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" });
P
Pilchie 已提交
182 183 184 185 186 187

            cmd.Arguments.Errors.Verify(
                // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found
                Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);"));

            AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference));
J
Jared Parsons 已提交
188
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path));
189 190

            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
191 192
        }

J
Jared Parsons 已提交
193
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)]
P
Pilchie 已提交
194 195 196 197 198 199 200
        public void ResponseFiles_RelativePaths()
        {
            var parentDir = Temp.CreateDirectory();
            var baseDir = parentDir.CreateDirectory("temp");
            var dirX = baseDir.CreateDirectory("x");
            var dirAB = baseDir.CreateDirectory("a b");
            var dirSubDir = baseDir.CreateDirectory("subdir");
201
            var dirGoo = parentDir.CreateDirectory("goo");
P
Pilchie 已提交
202 203 204 205 206 207
            var dirBar = parentDir.CreateDirectory("bar");

            string basePath = baseDir.Path;
            Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName);

            var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>()
208
            {
P
Pilchie 已提交
209 210 211
                { prependBasePath(@"a.rsp"), @"
""@subdir\b.rsp""
/r:..\v4.0.30319\System.dll
212
/r:.\System.Data.dll
P
Pilchie 已提交
213
a.cs @""..\c.rsp"" @\d.rsp
214
/libpaths:..\goo;../bar;""a b""
215
"
P
Pilchie 已提交
216 217 218
                },
                { Path.Combine(dirSubDir.Path, @"b.rsp"), @"
b.cs
219
"
P
Pilchie 已提交
220 221
                },
                { prependBasePath(@"..\c.rsp"), @"
T
Tomas Matousek 已提交
222
c.cs /lib:x
223
"
P
Pilchie 已提交
224 225 226 227 228
                },
                {  Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @"

# comment
d.cs
229
"
P
Pilchie 已提交
230
                }
T
Tomas Matousek 已提交
231
            }, isInteractive: false);
P
Pilchie 已提交
232

J
Jared Parsons 已提交
233
            var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory);
P
Pilchie 已提交
234
            args.Errors.Verify();
235
            Assert.False(args.IsScriptRunner);
P
Pilchie 已提交
236 237 238 239 240 241

            string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
            string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray();

            AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles);
            AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references);
242
            AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray());
P
Pilchie 已提交
243 244 245
            Assert.Equal(basePath, args.BaseDirectory);
        }

246 247 248 249 250 251 252
        [Fact]
        public void NullBaseDirectoryNotAddedToKeyFileSearchPaths()
        {
            var parser = CSharpCommandLineParser.Default.Parse(new string[0], null, SdkDirectory);
            AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths);
        }

J
jaredpar 已提交
253
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
254 255 256 257
        public void SourceFiles_Patterns()
        {
            var parser = new TestCommandLineParser(
                patterns: new Dictionary<string, string[]>()
258
                {
P
Pilchie 已提交
259 260 261
                    { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } }
                },
                recursivePatterns: new Dictionary<string, string[]>()
262
                {
263
                    { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } },
P
Pilchie 已提交
264 265
                });

J
Jared Parsons 已提交
266
            var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory);
P
Pilchie 已提交
267 268 269 270 271 272 273
            args.Errors.Verify();

            string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();

            AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles);
        }

274 275 276 277 278 279 280 281 282 283
        [Fact]
        public void ParseQuotedMainType()
        {
            // Verify the main switch are unquoted when used because of the issue with
            // MSBuild quoting some usages and not others. A quote character is not valid in either
            // these names.

            CSharpCommandLineArguments args;
            var folder = Temp.CreateDirectory();
            CreateFile(folder, "a.cs");
284

285
            args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path);
286 287 288
            args.Errors.Verify();
            Assert.Equal("Test", args.CompilationOptions.MainTypeName);

289
            args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path);
290 291 292
            args.Errors.Verify();
            Assert.Equal("Test", args.CompilationOptions.MainTypeName);

293
            args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path);
294 295 296
            args.Errors.Verify();
            Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName);

297
            args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path);
298 299 300
            args.Errors.Verify();
            Assert.Equal("Test", args.CompilationOptions.MainTypeName);

301
            args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path);
302 303 304
            args.Errors.Verify();
            Assert.Equal("Test", args.CompilationOptions.MainTypeName);

305
            args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path);
306 307 308 309
            args.Errors.Verify();
            Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName);

            // Use of Cyrillic namespace
310
            args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path);
311 312 313 314
            args.Errors.Verify();
            Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName);
        }

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        [Fact]
        [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")]
        public void ArgumentStartWithDashAndContainingSlash()
        {
            CSharpCommandLineArguments args;
            var folder = Temp.CreateDirectory();

            args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path);
            args.Errors.Verify(
                // error CS2007: Unrecognized option: '-debug+/debug:portable'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)
                );
        }

J
Jared Parsons 已提交
333 334
        [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")]
        [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")]
J
jaredpar 已提交
335
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        public void SourceFiles_Patterns2()
        {
            var folder = Temp.CreateDirectory();
            CreateFile(folder, "a.cs");
            CreateFile(folder, "b.vb");
            CreateFile(folder, "c.cpp");

            var folderA = folder.CreateDirectory("A");
            CreateFile(folderA, "A_a.cs");
            CreateFile(folderA, "A_b.cs");
            CreateFile(folderA, "A_c.vb");

            var folderB = folder.CreateDirectory("B");
            CreateFile(folderB, "B_a.cs");
            CreateFile(folderB, "B_b.vb");
            CreateFile(folderB, "B_c.cpx");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
354
            int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter);
P
Pilchie 已提交
355 356 357 358
            Assert.Equal(0, exitCode);
            Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
359
            exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.  ", "/out:abc.dll" }).Run(outWriter);
P
Pilchie 已提交
360 361 362 363
            Assert.Equal(0, exitCode);
            Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
364
            exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:  .  ", "/out:abc.dll" }).Run(outWriter);
P
Pilchie 已提交
365 366 367 368
            Assert.Equal(0, exitCode);
            Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
369
            exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter);
P
Pilchie 已提交
370 371 372 373 374 375
            Assert.Equal(0, exitCode);
            Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());

            CSharpCommandLineArguments args;
            string[] resolvedSourceFiles;

376
            args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path);
P
Pilchie 已提交
377 378 379 380
            args.Errors.Verify();
            resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
            AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles);

381
            args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path);
P
Pilchie 已提交
382 383 384 385
            args.Errors.Verify();
            resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
            Assert.Equal(4, resolvedSourceFiles.Length);

386
            args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path);
P
Pilchie 已提交
387 388 389 390 391
            args.Errors.Verify();
            resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
            Assert.Equal(4, resolvedSourceFiles.Length);
        }

J
Jared Parsons 已提交
392 393 394
        [ConditionalFact(typeof(WindowsOnly))]
        public void SourceFile_BadPath()
        {
J
Jared Parsons 已提交
395
            var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory);
J
Jared Parsons 已提交
396
            Assert.Equal(3, args.Errors.Length);
397
            Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code);
J
Jared Parsons 已提交
398 399 400 401
            Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code);
            Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code);
        }

P
Pilchie 已提交
402 403 404 405 406 407
        private void CreateFile(TempDirectory folder, string file)
        {
            var f = folder.CreateFile(file);
            f.WriteAllText("");
        }

J
Jared Parsons 已提交
408
        [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")]
P
Pilchie 已提交
409 410
        public void Win32ResourceArguments()
        {
411
            string[] args = new string[]
P
Pilchie 已提交
412 413 414 415
            {
                @"/win32manifest:..\here\there\everywhere\nonexistent"
            };

J
Jared Parsons 已提交
416
            var parsedArgs = DefaultParse(args, WorkingDirectory);
J
Jared Parsons 已提交
417
            var compilation = CreateCompilation(new SyntaxTree[0]);
P
Pilchie 已提交
418 419 420 421 422 423 424 425 426 427 428
            IEnumerable<DiagnosticInfo> errors;
            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());

            args = new string[]
            {
                @"/Win32icon:\bogus"
            };

J
Jared Parsons 已提交
429
            parsedArgs = DefaultParse(args, WorkingDirectory);
P
Pilchie 已提交
430 431 432 433 434 435 436 437 438 439 440

            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());

            args = new string[]
            {
                @"/Win32Res:\bogus"
            };

J
Jared Parsons 已提交
441
            parsedArgs = DefaultParse(args, WorkingDirectory);
P
Pilchie 已提交
442 443 444 445 446 447 448
            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());

            args = new string[]
            {
449
                @"/Win32Res:goo.win32data:bar.win32data2"
P
Pilchie 已提交
450 451
            };

J
Jared Parsons 已提交
452
            parsedArgs = DefaultParse(args, WorkingDirectory);
P
Pilchie 已提交
453 454 455 456 457 458 459
            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());

            args = new string[]
            {
460
                @"/Win32icon:goo.win32data:bar.win32data2"
P
Pilchie 已提交
461 462
            };

J
Jared Parsons 已提交
463
            parsedArgs = DefaultParse(args, WorkingDirectory);
P
Pilchie 已提交
464 465 466 467 468 469 470
            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());

            args = new string[]
            {
471
                @"/Win32manifest:goo.win32data:bar.win32data2"
P
Pilchie 已提交
472 473
            };

J
Jared Parsons 已提交
474
            parsedArgs = DefaultParse(args, WorkingDirectory);
P
Pilchie 已提交
475 476 477 478 479 480 481 482 483
            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code);
            Assert.Equal(2, errors.First().Arguments.Count());
        }

        [Fact]
        public void Win32ResConflicts()
        {
J
Jared Parsons 已提交
484
            var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
485 486 487
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
488
            parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
489 490 491
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
492
            parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
493 494 495 496
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
            Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);

J
Jared Parsons 已提交
497
            parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
498 499 500 501
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
            Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);

J
Jared Parsons 已提交
502
            parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
503 504 505 506
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
            Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);

J
Jared Parsons 已提交
507
            parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
508 509 510 511 512 513 514 515
            Assert.Equal(0, parsedArgs.Errors.Length);
            Assert.True(parsedArgs.NoWin32Manifest);
            Assert.Equal(null, parsedArgs.Win32Manifest);
        }

        [Fact]
        public void Win32ResInvalid()
        {
J
Jared Parsons 已提交
516
            var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
517 518
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res"));

J
Jared Parsons 已提交
519
            parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
520 521
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+"));

J
Jared Parsons 已提交
522
            parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
523 524
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon"));

J
Jared Parsons 已提交
525
            parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
526 527
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+"));

J
Jared Parsons 已提交
528
            parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
529 530
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest"));

J
Jared Parsons 已提交
531
            parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
532 533 534 535 536 537 538 539
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+"));
        }

        [Fact]
        public void Win32IconContainsGarbage()
        {
            string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path;

J
Jared Parsons 已提交
540
            var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory);
J
Jared Parsons 已提交
541
            var compilation = CreateCompilation(new SyntaxTree[0]);
P
Pilchie 已提交
542 543 544 545 546 547
            IEnumerable<DiagnosticInfo> errors;

            CSharpCompiler.GetWin32ResourcesInternal(MessageProvider.Instance, parsedArgs, compilation, out errors);
            Assert.Equal(1, errors.Count());
            Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code);
            Assert.Equal(1, errors.First().Arguments.Count());
548

549
            CleanupAllGeneratedFiles(tmpFileName);
P
Pilchie 已提交
550 551
        }

552
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
553 554 555 556 557 558
        public void Win32ResQuotes()
        {
            string[] responseFile = new string[] {
                @" /win32res:d:\\""abc def""\a""b c""d\a.res",
            };

559
            CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
P
Pilchie 已提交
560 561 562 563 564 565
            Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile);

            responseFile = new string[] {
                @" /win32icon:d:\\""abc def""\a""b c""d\a.ico",
            };

566
            args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
P
Pilchie 已提交
567 568 569 570 571 572
            Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon);

            responseFile = new string[] {
                @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest",
            };

573
            args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
P
Pilchie 已提交
574 575 576
            Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest);
        }

J
Jared Parsons 已提交
577
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
578 579 580 581
        public void ParseResources()
        {
            var diags = new List<Diagnostic>();

J
Jared Parsons 已提交
582
            ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
583
            Assert.Equal(0, diags.Count);
584 585
            Assert.Equal(@"someFile.goo.bar", desc.FileName);
            Assert.Equal("someFile.goo.bar", desc.ResourceName);
P
Pilchie 已提交
586

J
Jared Parsons 已提交
587
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
588
            Assert.Equal(0, diags.Count);
589
            Assert.Equal(@"someFile.goo.bar", desc.FileName);
P
Pilchie 已提交
590 591
            Assert.Equal("someName", desc.ResourceName);

J
Jared Parsons 已提交
592
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
593
            Assert.Equal(0, diags.Count);
594
            Assert.Equal(@"some File.goo.bar", desc.FileName);
P
Pilchie 已提交
595 596
            Assert.Equal("someName", desc.ResourceName);

J
Jared Parsons 已提交
597
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
598
            Assert.Equal(0, diags.Count);
599
            Assert.Equal(@"someFile.goo.bar", desc.FileName);
P
Pilchie 已提交
600 601 602 603
            Assert.Equal("some Name", desc.ResourceName);
            Assert.True(desc.IsPublic);

            // Use file name in place of missing resource name.
J
Jared Parsons 已提交
604
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
605
            Assert.Equal(0, diags.Count);
606 607
            Assert.Equal(@"someFile.goo.bar", desc.FileName);
            Assert.Equal("someFile.goo.bar", desc.ResourceName);
P
Pilchie 已提交
608 609 610
            Assert.False(desc.IsPublic);

            // Quoted accessibility is fine.
J
Jared Parsons 已提交
611
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
612
            Assert.Equal(0, diags.Count);
613 614
            Assert.Equal(@"someFile.goo.bar", desc.FileName);
            Assert.Equal("someFile.goo.bar", desc.ResourceName);
P
Pilchie 已提交
615 616 617
            Assert.False(desc.IsPublic);

            // Leading commas are not ignored...
J
Jared Parsons 已提交
618
            desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
619
            diags.Verify(
620 621
                // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar"));
P
Pilchie 已提交
622 623 624 625
            diags.Clear();
            Assert.Null(desc);

            // ...even if there's whitespace between them.
J
Jared Parsons 已提交
626
            desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
627
            diags.Verify(
628 629
                // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar"));
P
Pilchie 已提交
630 631 632 633
            diags.Clear();
            Assert.Null(desc);

            // Trailing commas are ignored...
J
Jared Parsons 已提交
634
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
635 636
            diags.Verify();
            diags.Clear();
637 638
            Assert.Equal("someFile.goo.bar", desc.FileName);
            Assert.Equal("someFile.goo.bar", desc.ResourceName);
P
Pilchie 已提交
639 640 641
            Assert.False(desc.IsPublic);

            // ...even if there's whitespace between them.
J
Jared Parsons 已提交
642
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
643 644
            diags.Verify();
            diags.Clear();
645 646
            Assert.Equal("someFile.goo.bar", desc.FileName);
            Assert.Equal("someFile.goo.bar", desc.ResourceName);
P
Pilchie 已提交
647 648
            Assert.False(desc.IsPublic);

J
Jared Parsons 已提交
649
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false);
650
            diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi"));
P
Pilchie 已提交
651 652 653
            Assert.Null(desc);
            diags.Clear();

J
Jared Parsons 已提交
654
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false);
655
            diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path"));
P
Pilchie 已提交
656 657 658
            Assert.Null(desc);
            diags.Clear();

J
Jared Parsons 已提交
659
            desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false);
660
            diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path"));
P
Pilchie 已提交
661 662 663
            Assert.Null(desc);
            diags.Clear();

J
Jared Parsons 已提交
664
            desc = CSharpCommandLineParser.ParseResourceDescription("", null, WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
665 666 667 668
            diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(""));
            Assert.Null(desc);
            diags.Clear();

J
Jared Parsons 已提交
669
            desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
670 671 672 673
            diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(""));
            Assert.Null(desc);
            diags.Clear();

J
Jared Parsons 已提交
674
            desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
675 676
            diags.Verify(
                // error CS2021: File name ' ' contains invalid characters, has a drive specification without an absolute path, or is too long
677
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(" "));
P
Pilchie 已提交
678 679 680
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
681
            desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
682 683
            diags.Verify(
                // error CS2021: File name ' ' contains invalid characters, has a drive specification without an absolute path, or is too long
684
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(" "));
P
Pilchie 已提交
685 686 687
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
688
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
689 690 691 692 693 694
            diags.Verify();
            diags.Clear();
            Assert.Equal("path", desc.FileName);
            Assert.Equal("path", desc.ResourceName);
            Assert.True(desc.IsPublic);

J
Jared Parsons 已提交
695
            desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
696 697
            diags.Verify(
                // error CS2021: File name ' ' contains invalid characters, has a drive specification without an absolute path, or is too long
698
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(" "));
P
Pilchie 已提交
699 700 701
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
702
            desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
703 704 705 706 707 708
            diags.Verify(
                // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
709
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
710 711 712 713 714 715
            diags.Verify(
                // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
716
            desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
717 718 719 720 721 722
            diags.Verify(
                // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
723
            desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
724 725
            diags.Verify(
                // error CS2021: File name ' ' contains invalid characters, has a drive specification without an absolute path, or is too long
726
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(" "));
P
Pilchie 已提交
727 728 729
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
730
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
731 732 733 734 735 736 737
            diags.Verify(
                // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe)
                // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(""));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
738
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
739 740 741 742 743 744 745
            diags.Verify(
                // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe)
                // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(""));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
746
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
747 748 749 750 751 752
            diags.Verify(
                // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
                Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
            diags.Clear();
            Assert.Null(desc);

J
Jared Parsons 已提交
753
            desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
754 755 756 757 758 759
            diags.Verify();
            diags.Clear();
            Assert.Equal("path", desc.FileName);
            Assert.Equal("path", desc.ResourceName);
            Assert.False(desc.IsPublic);

J
Jared Parsons 已提交
760
            desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
761 762
            diags.Verify(
                // error CS2021: File name ' ' contains invalid characters, has a drive specification without an absolute path, or is too long
763
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(" "));
P
Pilchie 已提交
764 765 766 767 768
            diags.Clear();
            Assert.Null(desc);

            var longE = new String('e', 1024);

J
Jared Parsons 已提交
769
            desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false);
P
Pilchie 已提交
770 771 772 773 774 775 776 777
            diags.Verify(); // Now checked during emit.
            diags.Clear();
            Assert.Equal("path", desc.FileName);
            Assert.Equal(longE, desc.ResourceName);
            Assert.False(desc.IsPublic);

            var longI = new String('i', 260);

J
Jared Parsons 已提交
778
            desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false);
779 780
            diags.Verify(
                // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
781
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1));
P
Pilchie 已提交
782 783 784 785 786 787 788 789
        }

        [Fact]
        public void ManagedResourceOptions()
        {
            CSharpCommandLineArguments parsedArgs;
            ResourceDescription resourceDescription;

J
Jared Parsons 已提交
790
            parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
791
            parsedArgs.Errors.Verify();
792
            Assert.False(parsedArgs.DisplayHelp);
P
Pilchie 已提交
793 794 795 796
            resourceDescription = parsedArgs.ManifestResources.Single();
            Assert.Null(resourceDescription.FileName); // since embedded
            Assert.Equal("a", resourceDescription.ResourceName);

J
Jared Parsons 已提交
797
            parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
798
            parsedArgs.Errors.Verify();
799
            Assert.False(parsedArgs.DisplayHelp);
P
Pilchie 已提交
800 801 802 803
            resourceDescription = parsedArgs.ManifestResources.Single();
            Assert.Null(resourceDescription.FileName); // since embedded
            Assert.Equal("b", resourceDescription.ResourceName);

J
Jared Parsons 已提交
804
            parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
805
            parsedArgs.Errors.Verify();
806
            Assert.False(parsedArgs.DisplayHelp);
P
Pilchie 已提交
807 808 809 810
            resourceDescription = parsedArgs.ManifestResources.Single();
            Assert.Equal("c", resourceDescription.FileName);
            Assert.Equal("c", resourceDescription.ResourceName);

J
Jared Parsons 已提交
811
            parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
812
            parsedArgs.Errors.Verify();
813
            Assert.False(parsedArgs.DisplayHelp);
P
Pilchie 已提交
814 815 816 817 818 819 820 821
            resourceDescription = parsedArgs.ManifestResources.Single();
            Assert.Equal("d", resourceDescription.FileName);
            Assert.Equal("d", resourceDescription.ResourceName);
        }

        [Fact]
        public void ManagedResourceOptions_SimpleErrors()
        {
J
Jared Parsons 已提交
822
            var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
823 824
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:"));

J
Jared Parsons 已提交
825
            parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
826 827
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:"));

J
Jared Parsons 已提交
828
            parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
829 830
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res"));

J
Jared Parsons 已提交
831
            parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
832 833
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+"));

J
Jared Parsons 已提交
834
            parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
835 836
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:"));

J
Jared Parsons 已提交
837
            parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
838 839
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:"));

J
Jared Parsons 已提交
840
            parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
841 842
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:"));

J
Jared Parsons 已提交
843
            parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
844 845
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres"));

J
Jared Parsons 已提交
846
            parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
847 848
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+"));

J
Jared Parsons 已提交
849
            parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
850 851 852 853 854 855
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:"));
        }

        [Fact]
        public void Link_SimpleTests()
        {
J
Jared Parsons 已提交
856
            var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
857 858 859 860 861 862
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { "a", "b", "c" },
                       parsedArgs.MetadataReferences.
                                  Where((res) => res.Properties.EmbedInteropTypes).
                                  Select((res) => res.Reference));

J
Jared Parsons 已提交
863
            parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
864 865 866 867 868 869
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { " b " },
                           parsedArgs.MetadataReferences.
                                      Where((res) => res.Properties.EmbedInteropTypes).
                                      Select((res) => res.Reference));

J
Jared Parsons 已提交
870
            parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
871 872
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:"));

J
Jared Parsons 已提交
873
            parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
874 875
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L"));

J
Jared Parsons 已提交
876
            parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
877 878
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+"));

J
Jared Parsons 已提交
879
            parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
880 881 882
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:"));
        }

J
jaredpar 已提交
883
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
        public void Recurse_SimpleTests()
        {
            var dir = Temp.CreateDirectory();
            var file1 = dir.CreateFile("a.cs");
            var file2 = dir.CreateFile("b.cs");
            var file3 = dir.CreateFile("c.txt");
            var file4 = dir.CreateDirectory("d1").CreateFile("d.txt");
            var file5 = dir.CreateDirectory("d2").CreateFile("e.cs");

            file1.WriteAllText("");
            file2.WriteAllText("");
            file3.WriteAllText("");
            file4.WriteAllText("");
            file5.WriteAllText("");

J
Jared Parsons 已提交
899
            var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory);
P
Pilchie 已提交
900 901 902 903
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" },
                           parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}")));

904
            parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString());
P
Pilchie 已提交
905 906 907 908
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" },
                           parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}")));

J
Jared Parsons 已提交
909
            parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
910 911
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:"));

J
Jared Parsons 已提交
912
            parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
913 914
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:"));

J
Jared Parsons 已提交
915
            parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
916 917
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse"));

J
Jared Parsons 已提交
918
            parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
919 920
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+"));

J
Jared Parsons 已提交
921
            parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
922
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:"));
923

924 925 926 927 928
            CleanupAllGeneratedFiles(file1.Path);
            CleanupAllGeneratedFiles(file2.Path);
            CleanupAllGeneratedFiles(file3.Path);
            CleanupAllGeneratedFiles(file4.Path);
            CleanupAllGeneratedFiles(file5.Path);
P
Pilchie 已提交
929 930 931 932 933
        }

        [Fact]
        public void Reference_SimpleTests()
        {
J
Jared Parsons 已提交
934
            var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
935 936 937 938 939 940
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { "a", "b", "c" },
                           parsedArgs.MetadataReferences.
                                      Where((res) => !res.Properties.EmbedInteropTypes).
                                      Select((res) => res.Reference));

J
Jared Parsons 已提交
941
            parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
942 943 944 945 946 947
            parsedArgs.Errors.Verify();
            AssertEx.Equal(new[] { " b " },
                           parsedArgs.MetadataReferences.
                                      Where((res) => !res.Properties.EmbedInteropTypes).
                                      Select((res) => res.Reference));

J
Jared Parsons 已提交
948
            parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
949
            parsedArgs.Errors.Verify();
950 951
            Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single());
            Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference);
P
Pilchie 已提交
952

J
Jared Parsons 已提交
953
            parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
954 955
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c"));

J
Jared Parsons 已提交
956
            parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
957 958
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1"));

J
Jared Parsons 已提交
959
            parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
960 961
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:"));

J
Jared Parsons 已提交
962
            parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
963 964
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R"));

J
Jared Parsons 已提交
965
            parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
966 967
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+"));

J
Jared Parsons 已提交
968
            parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
969 970 971 972 973 974
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:"));
        }

        [Fact]
        public void Target_SimpleTests()
        {
J
Jared Parsons 已提交
975
            var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
976 977 978
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
979
            parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
980 981 982
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
983
            parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
984 985 986
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
987
            parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
988 989 990
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
991
            parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
992 993 994
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
995
            parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
996 997 998
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
999
            parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1000 1001 1002
            parsedArgs.Errors.Verify();
            Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1003
            parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1004 1005
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t"));

J
Jared Parsons 已提交
1006
            parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1007 1008
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget));

J
Jared Parsons 已提交
1009
            parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1010 1011
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget));

J
Jared Parsons 已提交
1012
            parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1013 1014
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+"));

J
Jared Parsons 已提交
1015
            parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1016 1017 1018
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:"));
        }

T
Ty Overby 已提交
1019 1020 1021
        [Fact]
        public void Target_SimpleTestsNoSource()
        {
J
Jared Parsons 已提交
1022
            var parsedArgs = DefaultParse(new[] { "/target:exe"}, WorkingDirectory);
T
Ty Overby 已提交
1023 1024 1025 1026 1027 1028 1029
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1030
            parsedArgs = DefaultParse(new[] { "/t:module"}, WorkingDirectory);
T
Ty Overby 已提交
1031 1032 1033 1034 1035 1036 1037
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1038
            parsedArgs = DefaultParse(new[] { "/target:library"}, WorkingDirectory);
T
Ty Overby 已提交
1039 1040 1041 1042 1043 1044 1045
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1046
            parsedArgs = DefaultParse(new[] { "/TARGET:winexe"}, WorkingDirectory);
T
Ty Overby 已提交
1047 1048 1049 1050 1051 1052 1053
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1054
            parsedArgs = DefaultParse(new[] { "/target:appcontainerexe"}, WorkingDirectory);
T
Ty Overby 已提交
1055 1056 1057 1058 1059 1060 1061
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1062
            parsedArgs = DefaultParse(new[] { "/target:winmdobj"}, WorkingDirectory);
T
Ty Overby 已提交
1063 1064 1065 1066 1067 1068 1069
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1070
            parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module"}, WorkingDirectory);
T
Ty Overby 已提交
1071 1072 1073 1074 1075 1076 1077
            parsedArgs.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );
            Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);

J
Jared Parsons 已提交
1078
            parsedArgs = DefaultParse(new[] { "/t"}, WorkingDirectory);
T
Ty Overby 已提交
1079 1080 1081 1082 1083 1084 1085 1086
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/t'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) );

J
Jared Parsons 已提交
1087
            parsedArgs = DefaultParse(new[] { "/target:"}, WorkingDirectory);
T
Ty Overby 已提交
1088 1089 1090 1091 1092 1093 1094 1095
            parsedArgs.Errors.Verify(
                // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'
                Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));

J
Jared Parsons 已提交
1096
            parsedArgs = DefaultParse(new[] { "/target:xyz"}, WorkingDirectory);
1097
            parsedArgs.Errors.Verify(
T
Ty Overby 已提交
1098 1099 1100 1101 1102 1103 1104
                // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'
                Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));

J
Jared Parsons 已提交
1105
            parsedArgs = DefaultParse(new[] { "/T+"}, WorkingDirectory);
1106
            parsedArgs.Errors.Verify(
T
Ty Overby 已提交
1107 1108 1109 1110 1111 1112 1113
                // error CS2007: Unrecognized option: '/T+'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));

J
Jared Parsons 已提交
1114
            parsedArgs = DefaultParse(new[] { "/TARGET-:"}, WorkingDirectory);
T
Ty Overby 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/TARGET-:'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1),
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
        }

P
Pilchie 已提交
1124 1125 1126
        [Fact]
        public void ModuleManifest()
        {
J
Jared Parsons 已提交
1127
            CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
            args.Errors.Verify(
                // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies
                Diagnostic(ErrorCode.WRN_CantHaveManifestForModule));

            // Illegal, but not clobbered.
            Assert.Equal("blah", args.Win32Manifest);
        }

        [Fact]
        public void ArgumentParsing()
        {
J
Jared Parsons 已提交
1139 1140
            var sdkDirectory = SdkDirectory;
            var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1141
            parsedArgs.Errors.Verify();
1142 1143
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1144

J
Jared Parsons 已提交
1145
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1146
            parsedArgs.Errors.Verify();
1147 1148
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1149

J
Jared Parsons 已提交
1150
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1151
            parsedArgs.Errors.Verify();
1152 1153
            Assert.True(parsedArgs.DisplayHelp);
            Assert.False(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1154

J
Jared Parsons 已提交
1155
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory);
1156 1157 1158 1159
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.DisplayVersion);
            Assert.False(parsedArgs.SourceFiles.Any());

J
Jared Parsons 已提交
1160
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory);
1161 1162 1163 1164 1165
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/langversion:?'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/langversion:?").WithLocation(1, 1)
                );

J
Jared Parsons 已提交
1166
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory);
1167 1168 1169 1170
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.DisplayVersion);
            Assert.True(parsedArgs.SourceFiles.Any());

J
Jared Parsons 已提交
1171
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory);
1172 1173 1174 1175
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.DisplayVersion);
            Assert.False(parsedArgs.SourceFiles.Any());

J
Jared Parsons 已提交
1176
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1177
            parsedArgs.Errors.Verify();
1178 1179
            Assert.True(parsedArgs.DisplayHelp);
            Assert.False(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1180

J
Jared Parsons 已提交
1181
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx  /langversion:6" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1182
            parsedArgs.Errors.Verify();
1183 1184
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1185

J
Jared Parsons 已提交
1186
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1187 1188 1189 1190
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/langversion:-1'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/langversion:-1"));

1191
            Assert.False(parsedArgs.DisplayHelp);
P
Pilchie 已提交
1192 1193
            Assert.Equal(1, parsedArgs.SourceFiles.Length);

J
Jared Parsons 已提交
1194
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx  /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1195
            parsedArgs.Errors.Verify();
1196 1197
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1198

J
Jared Parsons 已提交
1199
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1200 1201
            parsedArgs.Errors.Verify(
                // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd'
J
Jared Parsons 已提交
1202
                Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file")));
P
Pilchie 已提交
1203

1204 1205
            Assert.False(parsedArgs.DisplayHelp);
            Assert.False(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1206

J
Jared Parsons 已提交
1207
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1208
            parsedArgs.Errors.Verify();
1209 1210
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1211

J
Jared Parsons 已提交
1212
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1213
            parsedArgs.Errors.Verify();
1214 1215
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1216

J
Jared Parsons 已提交
1217
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1218
            parsedArgs.Errors.Verify();
1219 1220
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1221

J
Jared Parsons 已提交
1222
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory);
T
Tomas Matousek 已提交
1223
            parsedArgs.Errors.Verify(
1224 1225
                // error CS2007: Unrecognized option: '/define:goo'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo"));
1226 1227
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
T
Tomas Matousek 已提交
1228

J
Jared Parsons 已提交
1229
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1230
            parsedArgs.Errors.Verify();
1231 1232
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1233

J
Jared Parsons 已提交
1234
            parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
1235
            parsedArgs.Errors.Verify();
1236 1237
            Assert.False(parsedArgs.DisplayHelp);
            Assert.True(parsedArgs.SourceFiles.Any());
P
Pilchie 已提交
1238 1239
        }

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        [Theory]
        [InlineData("iso-1", LanguageVersion.CSharp1)]
        [InlineData("iso-2", LanguageVersion.CSharp2)]
        [InlineData("1", LanguageVersion.CSharp1)]
        [InlineData("1.0", LanguageVersion.CSharp1)]
        [InlineData("2", LanguageVersion.CSharp2)]
        [InlineData("2.0", LanguageVersion.CSharp2)]
        [InlineData("3", LanguageVersion.CSharp3)]
        [InlineData("3.0", LanguageVersion.CSharp3)]
        [InlineData("4", LanguageVersion.CSharp4)]
        [InlineData("4.0", LanguageVersion.CSharp4)]
        [InlineData("5", LanguageVersion.CSharp5)]
        [InlineData("5.0", LanguageVersion.CSharp5)]
        [InlineData("6", LanguageVersion.CSharp6)]
        [InlineData("6.0", LanguageVersion.CSharp6)]
        [InlineData("7", LanguageVersion.CSharp7)]
        [InlineData("7.0", LanguageVersion.CSharp7)]
        [InlineData("7.1", LanguageVersion.CSharp7_1)]
        public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion)
P
Pilchie 已提交
1259
        {
J
Jared Parsons 已提交
1260
            var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1261
            parsedArgs.Errors.Verify();
1262 1263 1264
            Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion);
            Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
        }
1265

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        [Theory]
        [InlineData("6", "7", LanguageVersion.CSharp7)]
        [InlineData("7", "6", LanguageVersion.CSharp6)]
        [InlineData("7", "1", LanguageVersion.CSharp1)]
        [InlineData("6", "iso-1", LanguageVersion.CSharp1)]
        [InlineData("6", "iso-2", LanguageVersion.CSharp2)]
        [InlineData("6", "default", LanguageVersion.Default)]
        [InlineData("7", "default", LanguageVersion.Default)]
        [InlineData("iso-2", "6", LanguageVersion.CSharp6)]
        public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion)
        {
J
Jared Parsons 已提交
1277
            var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory);
1278
            parsedArgs.Errors.Verify();
1279 1280
            Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
        }
1281

1282 1283 1284 1285 1286
        [Fact]
        public void LangVersion_DefaultMapsCorrectly()
        {
            LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion();
            Assert.NotEqual(defaultEffectiveVersion, LanguageVersion.Default);
1287

J
Jared Parsons 已提交
1288
            var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory);
O
Omar Tawfik 已提交
1289 1290
            parsedArgs.Errors.Verify();

G
gafter 已提交
1291
            Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
O
Omar Tawfik 已提交
1292
            Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion);
1293
        }
1294

1295 1296 1297 1298 1299
        [Fact]
        public void LangVersion_LatestMapsCorrectly()
        {
            LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion();
            Assert.NotEqual(latestEffectiveVersion, LanguageVersion.Latest);
1300

J
Jared Parsons 已提交
1301
            var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1302 1303
            parsedArgs.Errors.Verify();

1304 1305 1306
            Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
            Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion);
        }
P
Pilchie 已提交
1307

1308 1309 1310
        [Fact]
        public void LangVersion_NoValueSpecified()
        {
J
Jared Parsons 已提交
1311
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1312
            parsedArgs.Errors.Verify();
O
Omar Tawfik 已提交
1313
            Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
1314
        }
P
Pilchie 已提交
1315

1316 1317 1318
        [Theory]
        [InlineData("iso-3")]
        [InlineData("iso1")]
C
Charles Stoner 已提交
1319 1320
        [InlineData("8.1")]
        [InlineData("9")]
1321 1322 1323
        [InlineData("1000")]
        public void LangVersion_BadVersion(string value)
        {
J
Jared Parsons 已提交
1324
            DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify(
1325 1326 1327
                // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values.
                Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1)
                );
1328
        }
P
Pilchie 已提交
1329

1330 1331 1332 1333 1334 1335 1336
        [Theory]
        [InlineData("0")]
        [InlineData("05")]
        [InlineData("07")]
        [InlineData("07.1")]
        public void LangVersion_LeadingZeroes(string value)
        {
J
Jared Parsons 已提交
1337
            DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify(
1338 1339 1340
                // error CS8303: Specified language version 'XXX' cannot have leading zeroes
                Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1));
        }
P
Pilchie 已提交
1341

1342 1343 1344 1345 1346 1347
        [Theory]
        [InlineData("/langversion")]
        [InlineData("/langversion:")]
        [InlineData("/LANGversion:")]
        public void LangVersion_NoVersion(string option)
        {
J
Jared Parsons 已提交
1348
            DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify(
1349 1350
                // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1));
P
Pilchie 已提交
1351 1352
        }

1353 1354 1355
        [Fact]
        public void LangVersion_LangVersions()
        {
J
Jared Parsons 已提交
1356
            var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory);
1357 1358 1359 1360 1361 1362 1363 1364 1365
            args.Errors.Verify(
                // warning CS2008: No source files specified.
                Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
                // error CS1562: Outputs without source must have the /out option specified
                Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)
                );
            Assert.True(args.DisplayLangVersions);
        }

1366
        [Fact]
1367
        public void LanguageVersionAdded_Canary()
1368
        {
1369 1370
            // When a new version is added, this test will break. This list must be checked:
            // - update the "UpgradeProject" codefixer
1371
            // - update the IDE drop-down for selecting Language Version (in project-systems repo)
1372
            // - update all the tests that call this canary
1373
            AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "latest" },
1374
                Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString()));
1375
            // For minor versions and new major versions, the format should be "x.y", such as "7.1"
1376 1377
        }

1378 1379 1380 1381 1382 1383 1384 1385
        [Fact]
        public void LanguageVersion_GetErrorCode()
        {
            var versions = Enum.GetValues(typeof(LanguageVersion))
                .Cast<LanguageVersion>()
                .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest })
                .Select(v => v.GetErrorCode());

C
Charles Stoner 已提交
1386 1387
            var errorCodes = new[]
            {
1388 1389 1390 1391 1392 1393 1394
                ErrorCode.ERR_FeatureNotAvailableInVersion1,
                ErrorCode.ERR_FeatureNotAvailableInVersion2,
                ErrorCode.ERR_FeatureNotAvailableInVersion3,
                ErrorCode.ERR_FeatureNotAvailableInVersion4,
                ErrorCode.ERR_FeatureNotAvailableInVersion5,
                ErrorCode.ERR_FeatureNotAvailableInVersion6,
                ErrorCode.ERR_FeatureNotAvailableInVersion7,
1395
                ErrorCode.ERR_FeatureNotAvailableInVersion7_1,
C
Charles Stoner 已提交
1396
                ErrorCode.ERR_FeatureNotAvailableInVersion7_2,
1397
                ErrorCode.ERR_FeatureNotAvailableInVersion7_3,
C
Charles Stoner 已提交
1398
                ErrorCode.ERR_FeatureNotAvailableInVersion8,
1399 1400 1401
            };

            AssertEx.SetEqual(versions, errorCodes);
1402 1403 1404

            // The canary check is a reminder that this test needs to be updated when a language version is added
            LanguageVersionAdded_Canary();
1405 1406
        }

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
        [Theory,
            InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1),
            InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2),
            InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3),
            InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4),
            InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5),
            InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6),
            InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7),
            InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1),
            InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2),
            InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3),
1418 1419 1420
            InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8),
            InlineData(LanguageVersion.CSharp7, LanguageVersion.Default),
            InlineData(LanguageVersion.CSharp7_3, LanguageVersion.Latest)]
1421
        public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input)
1422
        {
1423 1424
            Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion());
            Assert.True(expectedMappedVersion.IsValid());
1425

1426
            // https://github.com/dotnet/roslyn/issues/29819 Once we are ready to remove the beta tag from C# 8.0, we should update Default/Latest accordingly
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

            // The canary check is a reminder that this test needs to be updated when a language version is added
            LanguageVersionAdded_Canary();
        }

        [Theory,
            InlineData("iso-1", true, LanguageVersion.CSharp1),
            InlineData("ISO-1", true, LanguageVersion.CSharp1),
            InlineData("iso-2", true, LanguageVersion.CSharp2),
            InlineData("1", true, LanguageVersion.CSharp1),
1437
            InlineData("1.0", true, LanguageVersion.CSharp1),
1438
            InlineData("2", true, LanguageVersion.CSharp2),
1439
            InlineData("2.0", true, LanguageVersion.CSharp2),
1440
            InlineData("3", true, LanguageVersion.CSharp3),
1441
            InlineData("3.0", true, LanguageVersion.CSharp3),
1442
            InlineData("4", true, LanguageVersion.CSharp4),
1443
            InlineData("4.0", true, LanguageVersion.CSharp4),
1444
            InlineData("5", true, LanguageVersion.CSharp5),
1445 1446
            InlineData("5.0", true, LanguageVersion.CSharp5),
            InlineData("05", false, LanguageVersion.Default),
1447
            InlineData("6", true, LanguageVersion.CSharp6),
1448
            InlineData("6.0", true, LanguageVersion.CSharp6),
1449
            InlineData("7", true, LanguageVersion.CSharp7),
1450 1451
            InlineData("7.0", true, LanguageVersion.CSharp7),
            InlineData("07", false, LanguageVersion.Default),
O
Omar Tawfik 已提交
1452
            InlineData("7.1", true, LanguageVersion.CSharp7_1),
1453
            InlineData("7.2", true, LanguageVersion.CSharp7_2),
1454
            InlineData("7.3", true, LanguageVersion.CSharp7_3),
1455 1456
            InlineData("8", true, LanguageVersion.CSharp8),
            InlineData("8.0", true, LanguageVersion.CSharp8),
O
Omar Tawfik 已提交
1457
            InlineData("08", false, LanguageVersion.Default),
1458
            InlineData("07.1", false, LanguageVersion.Default),
1459 1460 1461 1462 1463 1464
            InlineData("default", true, LanguageVersion.Default),
            InlineData("latest", true, LanguageVersion.Latest),
            InlineData(null, true, LanguageVersion.Default),
            InlineData("bad", false, LanguageVersion.Default)]
        public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected)
        {
1465
            Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version));
1466 1467 1468 1469 1470 1471
            Assert.Equal(expected, version);

            // The canary check is a reminder that this test needs to be updated when a language version is added
            LanguageVersionAdded_Canary();
        }

1472 1473 1474 1475
        [Fact]
        public void LanguageVersion_TryParseTurkishDisplayString()
        {
            var originalCulture = Thread.CurrentThread.CurrentCulture;
1476
            Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false);
1477
            Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version));
1478 1479 1480 1481
            Assert.Equal(LanguageVersion.CSharp1, version);
            Thread.CurrentThread.CurrentCulture = originalCulture;
        }

1482
        [Fact]
1483
        public void LangVersion_ListLangVersions()
1484
        {
1485 1486
            var dir = Temp.CreateDirectory();
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
1487
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" });
1488 1489 1490
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

1491 1492 1493
            var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>()
                .Select(v => v.ToDisplayString());

1494 1495
            var actual = outWriter.ToString();
            var acceptableSurroundingChar = new[] { '\r', '\n', '(' , ')', ' '};
1496 1497
            foreach (var version in expected)
            {
1498
                var foundIndex = actual.IndexOf(version);
1499
                Assert.True(foundIndex > 0, $"Missing version '{version}'");
1500 1501
                Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0);
                Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0);
1502 1503 1504
            }
        }

P
Pilchie 已提交
1505
        [Fact]
J
Jared Parsons 已提交
1506
        [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")]
P
Pilchie 已提交
1507 1508
        public void Define()
        {
J
Jared Parsons 已提交
1509
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1510
            Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
1511
            Assert.False(parsedArgs.Errors.Any());
P
Pilchie 已提交
1512

J
Jared Parsons 已提交
1513
            parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1514
            Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
1515
            Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
1516
            Assert.False(parsedArgs.Errors.Any());
P
Pilchie 已提交
1517

J
Jared Parsons 已提交
1518
            parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1519
            Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
1520
            Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
P
Pilchie 已提交
1521 1522
            Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames);
            Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames);
1523
            Assert.False(parsedArgs.Errors.Any());
P
Pilchie 已提交
1524

J
Jared Parsons 已提交
1525
            parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1526
            Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
1527
            Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
P
Pilchie 已提交
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code);
            Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]);

            IEnumerable<Diagnostic> diagnostics;

            // The docs say /d:def1[;def2]
            string compliant = "def1;def2;def3";
            var expected = new[] { "def1", "def2", "def3" };
            var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics);
            diagnostics.Verify();
            Assert.Equal<string>(expected, parsed);

            // Bug 17360: Dev11 allows for a terminating semicolon
            var dev11Compliant = "def1;def2;def3;";
            parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics);
            diagnostics.Verify();
            Assert.Equal<string>(expected, parsed);

            // And comma
            dev11Compliant = "def1,def2,def3,";
            parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics);
            diagnostics.Verify();
            Assert.Equal<string>(expected, parsed);

            // This breaks everything
            var nonCompliant = "def1;;def2;";
            parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics);
            diagnostics.Verify(
O
Omar Tawfik 已提交
1557
                // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier
P
Pilchie 已提交
1558 1559 1560 1561
                Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments(""));
            Assert.Equal(new[] { "def1", "def2" }, parsed);

            // Bug 17360
J
Jared Parsons 已提交
1562
            parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1563 1564 1565 1566 1567 1568
            parsedArgs.Errors.Verify();
        }

        [Fact]
        public void Debug()
        {
1569 1570
            var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb;

J
Jared Parsons 已提交
1571
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1572
            parsedArgs.Errors.Verify();
1573 1574
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.False(parsedArgs.EmitPdb);
1575
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1576

J
Jared Parsons 已提交
1577
            parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1578
            parsedArgs.Errors.Verify();
1579 1580
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.False(parsedArgs.EmitPdb);
1581
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1582

J
Jared Parsons 已提交
1583
            parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1584
            parsedArgs.Errors.Verify();
1585 1586
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1587
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
1588

J
Jared Parsons 已提交
1589
            parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1590
            parsedArgs.Errors.Verify();
1591 1592
            Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1593
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1594

J
Jared Parsons 已提交
1595
            parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1596
            parsedArgs.Errors.Verify();
1597 1598
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.False(parsedArgs.EmitPdb);
1599
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1600

J
Jared Parsons 已提交
1601
            parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1602
            parsedArgs.Errors.Verify();
1603 1604
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1605
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1606

J
Jared Parsons 已提交
1607
            parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1608
            parsedArgs.Errors.Verify();
1609 1610
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1611
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1612

J
Jared Parsons 已提交
1613
            parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1614
            parsedArgs.Errors.Verify();
1615 1616
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1617
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
T
Ty Overby 已提交
1618

J
Jared Parsons 已提交
1619
            parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory);
T
Ty Overby 已提交
1620
            parsedArgs.Errors.Verify();
1621 1622
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
T
Ty Overby 已提交
1623 1624
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.PortablePdb);

J
Jared Parsons 已提交
1625
            parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory);
T
Ty Overby 已提交
1626
            parsedArgs.Errors.Verify();
1627 1628
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
T
Ty Overby 已提交
1629
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.Embedded);
P
Pilchie 已提交
1630

J
Jared Parsons 已提交
1631
            parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1632
            parsedArgs.Errors.Verify();
1633 1634
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1635
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1636

J
Jared Parsons 已提交
1637
            parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1638
            parsedArgs.Errors.Verify();
1639 1640
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
1641
            Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
P
Pilchie 已提交
1642

J
Jared Parsons 已提交
1643
            parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1644
            parsedArgs.Errors.Verify();
1645
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
1646
            Assert.True(parsedArgs.EmitPdb);
1647
            Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
P
Pilchie 已提交
1648

J
Jared Parsons 已提交
1649
            parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1650
            parsedArgs.Errors.Verify();
1651
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
1652
            Assert.False(parsedArgs.EmitPdb);
1653
            Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
P
Pilchie 已提交
1654

J
Jared Parsons 已提交
1655
            parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1656
            parsedArgs.Errors.Verify();
1657
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
1658
            Assert.True(parsedArgs.EmitPdb);
1659
            Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
P
Pilchie 已提交
1660

J
Jared Parsons 已提交
1661
            parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1662
            parsedArgs.Errors.Verify();
1663
            Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
1664
            Assert.True(parsedArgs.EmitPdb);
1665
            Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
1666

J
Jared Parsons 已提交
1667
            parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory);
1668 1669 1670 1671 1672
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.True(parsedArgs.EmitPdb);
            Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat);

J
Jared Parsons 已提交
1673
            parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory);
1674 1675 1676 1677
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
            Assert.False(parsedArgs.EmitPdb);
            Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat);
1678

J
Jared Parsons 已提交
1679
            parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1680 1681
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug"));

J
Jared Parsons 已提交
1682
            parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1683 1684
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+"));

J
Jared Parsons 已提交
1685
            parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1686 1687
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid"));

J
Jared Parsons 已提交
1688
            parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1689 1690 1691
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:"));
        }

J
Jared Parsons 已提交
1692
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
1693 1694
        public void Pdb()
        {
J
Jared Parsons 已提交
1695 1696
            var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory);
            Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath);
P
Pilchie 已提交
1697 1698

            // No pdb
J
Jared Parsons 已提交
1699
            parsedArgs = DefaultParse(new[] { @"/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1700
            parsedArgs.Errors.Verify();
1701
            Assert.Null(parsedArgs.PdbPath);
P
Pilchie 已提交
1702

J
Jared Parsons 已提交
1703
            parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1704 1705
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb"));

J
Jared Parsons 已提交
1706
            parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1707 1708
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:"));

J
Jared Parsons 已提交
1709
            parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1710 1711 1712
            parsedArgs.Errors.Verify();

            // temp: path changed
1713
            //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory);
P
Pilchie 已提交
1714 1715
            //parsedArgs.Errors.Verify(
            //    // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
1716
            //    Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
P
Pilchie 已提交
1717

J
Jared Parsons 已提交
1718
            parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1719
            parsedArgs.Errors.Verify(
1720 1721
                // error CS2005: Missing file specification for '/pdb:""' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1));
P
Pilchie 已提交
1722

J
Jared Parsons 已提交
1723
            parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1724
            parsedArgs.Errors.Verify(
1725
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\"));
P
Pilchie 已提交
1726 1727

            // Should preserve fully qualified paths
J
Jared Parsons 已提交
1728
            parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1729 1730 1731 1732
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath);

            // Should preserve fully qualified paths
J
Jared Parsons 已提交
1733
            parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1734 1735 1736
            parsedArgs.Errors.Verify();
            Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath);

J
Jared Parsons 已提交
1737
            parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1738
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
1739
            Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath);
P
Pilchie 已提交
1740 1741

            // Should handle quotes
J
Jared Parsons 已提交
1742
            parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1743 1744 1745 1746
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath);

            // Should expand partially qualified paths
J
Jared Parsons 已提交
1747
            parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1748
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
1749
            Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath);
P
Pilchie 已提交
1750 1751

            // Should expand partially qualified paths
J
Jared Parsons 已提交
1752
            parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1753 1754 1755
            parsedArgs.Errors.Verify();
            // Temp: Path info changed
            // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath);
1756

J
Jared Parsons 已提交
1757
            parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1758 1759
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
1760
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
1761
            Assert.Null(parsedArgs.PdbPath);
P
Pilchie 已提交
1762

J
Jared Parsons 已提交
1763
            parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1764 1765
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
1766
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb"));
1767 1768
            Assert.Null(parsedArgs.PdbPath);

J
Jared Parsons 已提交
1769
            parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1770 1771 1772 1773
            parsedArgs.Errors.Verify();
            Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath);

            // invalid name:
J
Jared Parsons 已提交
1774
            parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1775
            parsedArgs.Errors.Verify(
1776
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
1777 1778
            Assert.Null(parsedArgs.PdbPath);

P
Pilchie 已提交
1779

J
Jared Parsons 已提交
1780
            parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1781
            //parsedArgs.Errors.Verify(
1782
            //    Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb"));
P
Pilchie 已提交
1783 1784 1785
            Assert.Null(parsedArgs.PdbPath);

            // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z'
J
Jared Parsons 已提交
1786
            parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory);
P
Pilchie 已提交
1787 1788
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
1789
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb"));
1790
            Assert.Null(parsedArgs.PdbPath);
P
Pilchie 已提交
1791

J
Jared Parsons 已提交
1792
            parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
1793 1794
            //parsedArgs.Errors.Verify(
            //    // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
1795
            //    Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
P
Pilchie 已提交
1796 1797 1798
            Assert.Null(parsedArgs.PdbPath);
        }

1799 1800 1801
        [Fact]
        public void SourceLink()
        {
J
Jared Parsons 已提交
1802
            var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory);
1803
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
1804
            Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink);
1805

J
Jared Parsons 已提交
1806
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory);
1807
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
1808
            Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink);
1809

J
Jared Parsons 已提交
1810
            parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory);
1811
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
1812
            Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink);
1813

J
Jared Parsons 已提交
1814
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory);
1815
            parsedArgs.Errors.Verify();
1816

J
Jared Parsons 已提交
1817
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
1818
            parsedArgs.Errors.Verify();
1819

J
Jared Parsons 已提交
1820
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory);
1821
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb));
1822

J
Jared Parsons 已提交
1823
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory);
1824
            parsedArgs.Errors.Verify();
1825

J
Jared Parsons 已提交
1826
            parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory);
1827
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb));
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
        }

        [Fact]
        public void SourceLink_EndToEnd_EmbeddedPortable()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"class C { public static void Main() {} }");

            var sl = dir.CreateFile("sl.json");
            sl.WriteAllText(@"{ ""documents"" : {} }");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
1842
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" });
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe"));

            using (var peReader = new PEReader(peStream))
            {
                var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
                using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry))
                {
                    var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob();
                    AssertEx.Equal(File.ReadAllBytes(sl.Path), blob);
                }
            }

            // Clean up temp files
            CleanupAllGeneratedFiles(src.Path);
        }

        [Fact]
        public void SourceLink_EndToEnd_Portable()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"class C { public static void Main() {} }");

            var sl = dir.CreateFile("sl.json");
            sl.WriteAllText(@"{ ""documents"" : {} }");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
1874
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" });
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb"));

            using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
            {
                var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob();
                AssertEx.Equal(File.ReadAllBytes(sl.Path), blob);
            }

            // Clean up temp files
            CleanupAllGeneratedFiles(src.Path);
        }
P
Pilchie 已提交
1889

1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
        [Fact]
        public void SourceLink_EndToEnd_Windows()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"class C { public static void Main() {} }");

            var sl = dir.CreateFile("sl.json");
            byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }");
            sl.WriteAllBytes(slContent);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
1903
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" });
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb"));
            var actualData = PdbValidation.GetSourceLinkData(pdbStream);
            AssertEx.Equal(slContent, actualData);

            // Clean up temp files
            CleanupAllGeneratedFiles(src.Path);
        }

1915 1916 1917
        [Fact]
        public void Embed()
        {
J
Jared Parsons 已提交
1918
            var parsedArgs = DefaultParse(new[] { "a.cs "}, WorkingDirectory);
1919 1920 1921
            parsedArgs.Errors.Verify();
            Assert.Empty(parsedArgs.EmbeddedFiles);

J
Jared Parsons 已提交
1922
            parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
1923 1924 1925
            parsedArgs.Errors.Verify();
            AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles);
            AssertEx.Equal(
J
Jared Parsons 已提交
1926
                new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
1927 1928
                parsedArgs.EmbeddedFiles.Select(f => f.Path));

J
Jared Parsons 已提交
1929
            parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
1930 1931
            parsedArgs.Errors.Verify();
            AssertEx.Equal(
J
Jared Parsons 已提交
1932
                new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
1933 1934
                parsedArgs.EmbeddedFiles.Select(f => f.Path));

J
Jared Parsons 已提交
1935
            parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
1936 1937
            parsedArgs.Errors.Verify();
            AssertEx.Equal(
J
Jared Parsons 已提交
1938
                new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
1939 1940
                parsedArgs.EmbeddedFiles.Select(f => f.Path));

J
Jared Parsons 已提交
1941
            parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
1942 1943
            parsedArgs.Errors.Verify();;
            AssertEx.Equal(
J
Jared Parsons 已提交
1944
                new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
1945 1946
                parsedArgs.EmbeddedFiles.Select(f => f.Path));

J
Jared Parsons 已提交
1947
            parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory);
1948 1949
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));

J
Jared Parsons 已提交
1950
            parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory);
1951 1952
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));

J
Jared Parsons 已提交
1953
            parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory);
1954 1955
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));

J
Jared Parsons 已提交
1956
            parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory);
1957 1958
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));

J
Jared Parsons 已提交
1959
            parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory);
1960
            parsedArgs.Errors.Verify();
1961

J
Jared Parsons 已提交
1962
            parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
1963
            parsedArgs.Errors.Verify();
1964

J
Jared Parsons 已提交
1965
            parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory);
1966
            parsedArgs.Errors.Verify();
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
        }

        [Theory]
        [InlineData("/debug:portable", "/embed", new[] {"embed.cs", "embed2.cs", "embed.xyz" })]
        [InlineData("/debug:portable", "/embed:embed.cs", new[] {"embed.cs", "embed.xyz" })]
        [InlineData("/debug:portable", "/embed:embed2.cs", new[] {"embed2.cs" })]
        [InlineData("/debug:portable", "/embed:embed.xyz", new[] {"embed.xyz" })]
        [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })]
        [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })]
        [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })]
        [InlineData("/debug:embedded", "/embed:embed.xyz", new[] {"embed.xyz" })]
1978
        public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded)
1979 1980 1981 1982
        {
            // embed.cs: large enough to compress, has #line directives
            const string embed_cs =
@"///////////////////////////////////////////////////////////////////////////////
1983
class Program {
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
    static void Main() {
#line 1 ""embed.xyz""
        System.Console.WriteLine(""Hello, World"");

#line 3
        System.Console.WriteLine(""Goodbye, World"");
    }
}
///////////////////////////////////////////////////////////////////////////////";

            // embed2.cs: small enough to not compress, no sequence points
            const string embed2_cs =
@"class C
{
}";
1999
            // target of #line
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
            const string embed_xyz =
@"print Hello, World

print Goodbye, World";

            Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold);
            Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold);

            var dir = Temp.CreateDirectory();
            var src = dir.CreateFile("embed.cs");
            var src2 = dir.CreateFile("embed2.cs");
            var txt = dir.CreateFile("embed.xyz");

            src.WriteAllText(embed_cs);
            src2.WriteAllText(embed2_cs);
            txt.WriteAllText(embed_xyz);

            var expectedEmbeddedMap = new Dictionary<string, string>();
            if (expectedEmbedded.Contains("embed.cs"))
            {
                expectedEmbeddedMap.Add(src.Path, embed_cs);
            }

            if (expectedEmbedded.Contains("embed2.cs"))
            {
                expectedEmbeddedMap.Add(src2.Path, embed2_cs);
            }

            if (expectedEmbedded.Contains("embed.xyz"))
            {
                expectedEmbeddedMap.Add(txt.Path, embed_xyz);
            }

            var output = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2034
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" });
2035 2036 2037
            int exitCode = csc.Run(output);
            Assert.Equal("", output.ToString().Trim());
            Assert.Equal(0, exitCode);
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057

            switch (debugSwitch)
            {
                case "/debug:embedded":
                    ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true);
                    break;
                case "/debug:portable":
                    ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false);
                    break;
                case "/debug:full":
                    ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir);
                    break;
            }

            Assert.Empty(expectedEmbeddedMap);
            CleanupAllGeneratedFiles(src.Path);
        }

        private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb)
        {
2058 2059 2060
            using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe"))))
            {
                var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
2061
                Assert.Equal(isEmbeddedPdb, entry.DataSize > 0);
2062

2063
                using (var mdProvider = isEmbeddedPdb ?
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
                    peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) :
                    MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))))
                {
                    var mdReader = mdProvider.GetMetadataReader();

                    foreach (var handle in mdReader.Documents)
                    {
                        var doc = mdReader.GetDocument(handle);
                        var docPath = mdReader.GetString(doc.Name);

                        SourceText embeddedSource = mdReader.GetEmbeddedSource(handle);
                        if (embeddedSource == null)
                        {
                            continue;
                        }

                        Assert.True(embeddedSource.Encoding is UTF8Encoding && embeddedSource.Encoding.GetPreamble().Length == 0);
                        Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString());
                        Assert.True(expectedEmbeddedMap.Remove(docPath));
                    }
                }
            }
2086
        }
2087

2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
        private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir)
        {
            ISymUnmanagedReader5 symReader = null;

            try
            {
                symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")));

                foreach (var doc in symReader.GetDocuments())
                {
                    var docPath = doc.GetName();

                    var sourceBlob = doc.GetEmbeddedSource();
                    if (sourceBlob.Array == null)
                    {
                        continue;
                    }

                    var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count);

                    Assert.Equal(expectedEmbeddedMap[docPath], sourceStr);
                    Assert.True(expectedEmbeddedMap.Remove(docPath));
                }
            }
            catch
            {
                symReader?.Dispose();
            }
2116 2117
        }

P
Pilchie 已提交
2118 2119 2120
        [Fact]
        public void Optimize()
        {
J
Jared Parsons 已提交
2121
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2122
            parsedArgs.Errors.Verify();
2123
            Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2124

J
Jared Parsons 已提交
2125
            parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2126
            parsedArgs.Errors.Verify();
2127
            Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2128

J
Jared Parsons 已提交
2129
            parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2130
            parsedArgs.Errors.Verify();
2131
            Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2132

J
Jared Parsons 已提交
2133
            parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2134
            parsedArgs.Errors.Verify();
2135
            Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2136

J
Jared Parsons 已提交
2137
            parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2138
            parsedArgs.Errors.Verify();
2139
            Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2140

J
Jared Parsons 已提交
2141
            parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2142 2143
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+"));

J
Jared Parsons 已提交
2144
            parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2145 2146
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:"));

J
Jared Parsons 已提交
2147
            parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2148 2149
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:"));

J
Jared Parsons 已提交
2150
            parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory);
2151
            Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2152

J
Jared Parsons 已提交
2153
            parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory);
2154
            Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2155

J
Jared Parsons 已提交
2156
            parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory);
2157
            Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2158

J
Jared Parsons 已提交
2159
            parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory);
2160
            Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
P
Pilchie 已提交
2161

J
Jared Parsons 已提交
2162
            parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2163 2164
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+"));

J
Jared Parsons 已提交
2165
            parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2166 2167
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:"));

J
Jared Parsons 已提交
2168
            parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2169 2170 2171
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:"));
        }

2172 2173 2174
        [Fact]
        public void Deterministic()
        {
J
Jared Parsons 已提交
2175
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
2176
            parsedArgs.Errors.Verify();
2177
            Assert.False(parsedArgs.CompilationOptions.Deterministic);
2178

J
Jared Parsons 已提交
2179
            parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory);
2180
            parsedArgs.Errors.Verify();
2181
            Assert.True(parsedArgs.CompilationOptions.Deterministic);
2182

J
Jared Parsons 已提交
2183
            parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory);
2184
            parsedArgs.Errors.Verify();
2185
            Assert.True(parsedArgs.CompilationOptions.Deterministic);
2186

J
Jared Parsons 已提交
2187
            parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory);
2188
            parsedArgs.Errors.Verify();
2189
            Assert.False(parsedArgs.CompilationOptions.Deterministic);
2190 2191
        }

P
Pilchie 已提交
2192 2193 2194
        [Fact]
        public void ParseReferences()
        {
J
Jared Parsons 已提交
2195
            var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2196 2197 2198
            parsedArgs.Errors.Verify();
            Assert.Equal(2, parsedArgs.MetadataReferences.Length);

J
Jared Parsons 已提交
2199
            parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2200 2201 2202
            parsedArgs.Errors.Verify();
            Assert.Equal(2, parsedArgs.MetadataReferences.Length);

J
Jared Parsons 已提交
2203
            Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
P
Pilchie 已提交
2204 2205
            Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);

2206
            Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
P
Pilchie 已提交
2207 2208 2209
            Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties);


J
Jared Parsons 已提交
2210
            parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2211 2212 2213
            parsedArgs.Errors.Verify();
            Assert.Equal(2, parsedArgs.MetadataReferences.Length);

J
Jared Parsons 已提交
2214
            Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
P
Pilchie 已提交
2215 2216
            Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);

2217
            Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
P
Pilchie 已提交
2218 2219 2220
            Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties);


J
Jared Parsons 已提交
2221
            parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2222 2223 2224
            parsedArgs.Errors.Verify();
            Assert.Equal(2, parsedArgs.MetadataReferences.Length);

J
Jared Parsons 已提交
2225
            Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
P
Pilchie 已提交
2226 2227
            Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);

2228
            Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
P
Pilchie 已提交
2229 2230 2231
            Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties);


J
Jared Parsons 已提交
2232
            parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2233 2234 2235
            parsedArgs.Errors.Verify();
            Assert.Equal(4, parsedArgs.MetadataReferences.Length);

J
Jared Parsons 已提交
2236
            Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
P
Pilchie 已提交
2237 2238
            Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);

2239
            Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
2240
            Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties);
2241

P
Pilchie 已提交
2242
            Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference);
2243
            Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties);
P
Pilchie 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253

            Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference);
            Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties);

            // TODO: multiple files, quotes, etc.
        }

        [Fact]
        public void ParseAnalyzers()
        {
J
Jared Parsons 已提交
2254
            var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2255
            parsedArgs.Errors.Verify();
2256
            Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
2257
            Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
2258

J
Jared Parsons 已提交
2259
            parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2260
            parsedArgs.Errors.Verify();
2261
            Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
2262
            Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
P
Pilchie 已提交
2263

J
Jared Parsons 已提交
2264
            parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2265
            parsedArgs.Errors.Verify();
2266
            Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
2267
            Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
P
Pilchie 已提交
2268

J
Jared Parsons 已提交
2269
            parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2270
            parsedArgs.Errors.Verify();
2271
            Assert.Equal(2, parsedArgs.AnalyzerReferences.Length);
2272
            Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
2273
            Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath);
P
Pilchie 已提交
2274

J
Jared Parsons 已提交
2275
            parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2276 2277 2278
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:"));

J
Jared Parsons 已提交
2279
            parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a"));
        }

        [Fact]
        public void Analyzers_Missing()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2298
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" });
P
Pilchie 已提交
2299 2300 2301
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim());
2302 2303 2304

            // Clean up temp files
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
        }

        [Fact]
        public void Analyzers_Empty()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2321
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" });
P
Pilchie 已提交
2322 2323
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
T
Tom Meschter 已提交
2324
            Assert.DoesNotContain("warning", outWriter.ToString());
2325 2326

            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
        }

        private TempFile CreateRuleSetFile(string source)
        {
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.ruleset");
            file.WriteAllText(source);
            return file;
        }

        [Fact]
        public void RuleSetSwitchPositive()
        {
            string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
  <IncludeAll Action=""Warning"" />
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""CA1012"" Action=""Error"" />
    <Rule Id=""CA1013"" Action=""Warning"" />
    <Rule Id=""CA1014"" Action=""None"" />
  </Rules>
</RuleSet>
";
            var file = CreateRuleSetFile(source);
J
Jared Parsons 已提交
2351
            var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2352
            parsedArgs.Errors.Verify();
2353
            Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
P
Pilchie 已提交
2354 2355 2356 2357 2358 2359 2360 2361 2362
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012"));
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error);
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013"));
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn);
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014"));
            Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress);
            Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn);
        }

2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
        [Fact]
        public void RuleSetSwitchQuoted()
        {
            string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
  <IncludeAll Action=""Warning"" />
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""CA1012"" Action=""Error"" />
    <Rule Id=""CA1013"" Action=""Warning"" />
    <Rule Id=""CA1014"" Action=""None"" />
  </Rules>
</RuleSet>
";
            var file = CreateRuleSetFile(source);
J
Jared Parsons 已提交
2377
            var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory);
2378
            parsedArgs.Errors.Verify();
2379
            Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
2380 2381
        }

P
Pilchie 已提交
2382 2383 2384
        [Fact]
        public void RuleSetSwitchParseErrors()
        {
J
Jared Parsons 已提交
2385
            var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2386 2387
            parsedArgs.Errors.Verify(
                 Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset"));
2388
            Assert.Null(parsedArgs.RuleSetPath);
P
Pilchie 已提交
2389

J
Jared Parsons 已提交
2390
            parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2391 2392
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset"));
2393
            Assert.Null(parsedArgs.RuleSetPath);
P
Pilchie 已提交
2394

J
Jared Parsons 已提交
2395
            parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2396 2397
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found."));
2398
            Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath);
P
Pilchie 已提交
2399

J
Jared Parsons 已提交
2400
            parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
2401 2402
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found."));
2403
            Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath);
P
Pilchie 已提交
2404 2405

            var file = CreateRuleSetFile("Random text");
J
Jared Parsons 已提交
2406
            parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory);
2407 2408
            //parsedArgs.Errors.Verify(
            //    Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1."));
2409
            Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
2410 2411 2412 2413 2414
            var err = parsedArgs.Errors.Single();

            Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code);
            Assert.Equal(2, err.Arguments.Count);
            Assert.Equal(file.Path, (string)err.Arguments[0]);
2415 2416
            var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name;
            if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase))
2417 2418 2419
            {
                Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]);
            }
P
Pilchie 已提交
2420 2421
        }

J
Jared Parsons 已提交
2422
        [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")]
P
Pilchie 已提交
2423 2424 2425 2426 2427 2428 2429
        [Fact]
        public void Analyzers_Found()
        {
            string source = @"
class C
{
}
2430
";
P
Pilchie 已提交
2431 2432 2433 2434 2435 2436 2437
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
J
Jared Parsons 已提交
2438
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" });
P
Pilchie 已提交
2439 2440 2441
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            // Diagnostic thrown
2442
            Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared"));
P
Pilchie 已提交
2443 2444
            // Diagnostic cannot be instantiated
            Assert.True(outWriter.ToString().Contains("warning CS8032"));
2445 2446

            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
        }

        [Fact]
        public void Analyzers_WithRuleSet()
        {
            string source = @"
class C
{
    int x;
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
2466
    <Rule Id=""Warning01"" Action=""Error"" />
P
Pilchie 已提交
2467 2468 2469 2470 2471 2472 2473
  </Rules>
</RuleSet>
";
            var ruleSetFile = CreateRuleSetFile(rulesetSource);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
J
Jared Parsons 已提交
2474
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path });
P
Pilchie 已提交
2475 2476 2477
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            // Diagnostic thrown as error.
2478
            Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared"));
2479 2480 2481

            // Clean up temp files
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
2482 2483
        }

J
Jared Parsons 已提交
2484
        [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")]
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
        [Fact]
        public void Analyzers_CommandLineOverridesRuleset1()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <IncludeAll Action=""Warning"" />
</RuleSet>
";
            var ruleSetFile = CreateRuleSetFile(rulesetSource);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
J
Jared Parsons 已提交
2507
            var csc = CreateCSharpCompiler(null, dir.Path,
2508
                new[] {
2509
                    "/nologo", "/preferreduilang:en", "/t:library",
2510
                    "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
2511
                    "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" });
2512 2513 2514
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            // Diagnostic thrown as error: command line always overrides ruleset.
2515
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal);
2516 2517

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2518
            csc = CreateCSharpCompiler(null, dir.Path,
2519
                new[] {
2520
                    "/nologo", "/preferreduilang:en", "/t:library",
2521
                    "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
2522
                    "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" });
2523 2524 2525
            exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            // Diagnostic thrown as error: command line always overrides ruleset.
2526
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal);
2527 2528 2529 2530 2531

            // Clean up temp files
            CleanupAllGeneratedFiles(file.Path);
        }

2532
        [Fact]
2533 2534
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
        public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption()
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <IncludeAll Action=""Warning"" />
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2545
            var arguments = DefaultParse(
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
        }

        [Fact]
2563
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
        public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2577
            var arguments = DefaultParse(
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error);
        }

        [Fact]
2596
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
        public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Info"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2610
            var arguments = DefaultParse(
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info);
        }

        [Fact]
2629
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
        public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Info"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2643
            var arguments = DefaultParse(
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+:Test001",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error);
        }

        [Fact]
2662
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
        public void RuleSet_GeneralWarnAsErrorMinusResetsRules()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2676
            var arguments = DefaultParse(
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "/warnaserror-",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
        }

        [Fact]
2696
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
        public void RuleSet_SpecificWarnAsErrorMinusResetsRules()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2710
            var arguments = DefaultParse(
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "/warnaserror-:Test001",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
        }

        [Fact]
2730
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
        public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2744
            var arguments = DefaultParse(
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+:Test002",
                    "/warnaserror-:Test002",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
            Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default);
        }

2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
        [Fact]
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
        public void NoWarn_SpecificNoWarnOverridesRuleSet()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2779
            var arguments = DefaultParse(
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/nowarn:Test001",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
            Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
        }

        [Fact]
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
        public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2813
            var arguments = DefaultParse(
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/warnaserror+",
                    "/nowarn:Test001",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
            Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
        }

        [Fact]
        [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
        public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError()
        {
            var dir = Temp.CreateDirectory();

            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
    <Rule Id=""Test001"" Action=""Warning"" />
  </Rules>
</RuleSet>
";
            var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);

2848
            var arguments = DefaultParse(
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
                new[]
                {
                    "/nologo",
                    "/t:library",
                    "/ruleset:Rules.ruleset",
                    "/nowarn:Test001",
                    "/warnaserror+:Test001",
                    "a.cs"
                },
                dir.Path);

            var errors = arguments.Errors;
            Assert.Empty(errors);

            Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
            Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
        }

J
Jared Parsons 已提交
2868
        [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")]
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
        [Fact]
        public void Analyzers_CommandLineOverridesRuleset2()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
  <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
2885
    <Rule Id=""Warning01"" Action=""Error"" />
2886 2887 2888 2889 2890 2891 2892
  </Rules>
</RuleSet>
";
            var ruleSetFile = CreateRuleSetFile(rulesetSource);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
J
Jared Parsons 已提交
2893
            var csc = CreateCSharpCompiler(null, dir.Path,
2894 2895 2896 2897 2898 2899 2900
                new[] {
                    "/nologo", "/t:library",
                    "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
                    "/ruleset:" + ruleSetFile.Path, "/warn:0" });
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            // Diagnostic suppressed: commandline always overrides ruleset.
2901
            Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal);
2902 2903

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2904
            csc = CreateCSharpCompiler(null, dir.Path,
2905 2906 2907 2908 2909 2910 2911
                new[] {
                    "/nologo", "/t:library",
                    "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
                    "/warn:0", "/ruleset:" + ruleSetFile.Path });
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            // Diagnostic suppressed: commandline always overrides ruleset.
2912
            Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal);
2913 2914 2915 2916 2917

            // Clean up temp files
            CleanupAllGeneratedFiles(file.Path);
        }

J
Jared Parsons 已提交
2918
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
2919 2920 2921 2922 2923 2924 2925 2926 2927
        public void DiagnosticFormatting()
        {
            string source = @"
using System;

class C
{
        public static void Main()
        {
2928
            Goo(0);
P
Pilchie 已提交
2929
#line 10 ""c:\temp\a\1.cs""
2930
            Goo(1);
P
Pilchie 已提交
2931
#line 20 ""C:\a\..\b.cs""
2932
            Goo(2);
P
Pilchie 已提交
2933
#line 30 ""C:\a\../B.cs""
2934
            Goo(3);
P
Pilchie 已提交
2935
#line 40 ""../b.cs""
2936
            Goo(4);
P
Pilchie 已提交
2937
#line 50 ""..\b.cs""
2938
            Goo(5);
P
Pilchie 已提交
2939
#line 60 ""C:\X.cs""
2940
            Goo(6);
P
Pilchie 已提交
2941
#line 70 ""C:\x.cs""
2942
            Goo(7);
P
Pilchie 已提交
2943
#line 90 ""      ""
2944
		    Goo(9);
P
Pilchie 已提交
2945
#line 100 ""C:\*.cs""
2946
		    Goo(10);
P
Pilchie 已提交
2947
#line 110 """"
2948
		    Goo(11);
P
Pilchie 已提交
2949
#line hidden
2950
            Goo(12);
P
Pilchie 已提交
2951
#line default
2952
            Goo(13);
P
Pilchie 已提交
2953
#line 140 ""***""
2954
            Goo(14);
P
Pilchie 已提交
2955 2956 2957 2958 2959 2960 2961
        }
    }
";
            var dir = Temp.CreateDirectory();
            dir.CreateFile("a.cs").WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2962
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" });
P
Pilchie 已提交
2963 2964 2965 2966 2967
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);

            // with /fullpaths off
            string expected = @"
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context
c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context
C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context
C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context
C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context
C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context
      (90,7): error CS0103: The name 'Goo' does not exist in the current context
C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context
(110,7): error CS0103: The name 'Goo' does not exist in the current context
(112,13): error CS0103: The name 'Goo' does not exist in the current context
a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context
***(140,13): error CS0103: The name 'Goo' does not exist in the current context";
P
Pilchie 已提交
2982 2983 2984 2985 2986 2987 2988 2989

            AssertEx.Equal(
                expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                itemSeparator: "\r\n");

            // with /fullpaths on
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
2990
            csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" });
P
Pilchie 已提交
2991 2992 2993 2994
            exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);

            expected = @"
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
" + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context
c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context
C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context
C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context
C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context
C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context
      (90,7): error CS0103: The name 'Goo' does not exist in the current context
C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context
(110,7): error CS0103: The name 'Goo' does not exist in the current context
(112,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context
***(140,13): error CS0103: The name 'Goo' does not exist in the current context";
P
Pilchie 已提交
3009 3010 3011 3012 3013 3014 3015

            AssertEx.Equal(
                expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                itemSeparator: "\r\n");
        }

J
Jared Parsons 已提交
3016
        [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")]
J
Jared Parsons 已提交
3017
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
3018 3019 3020 3021
        public void ParseOut()
        {
            const string baseDirectory = @"C:\abc\def\baz";

3022
            var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3023 3024
            parsedArgs.Errors.Verify(
                // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long
3025
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(""));
P
Pilchie 已提交
3026

3027
            parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3028 3029 3030 3031
            parsedArgs.Errors.Verify(
                // error CS2005: Missing file specification for '/out:' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:"));

3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
            parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory);
            parsedArgs.Errors.Verify(
                // error CS2005: Missing file specification for '/refout:' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:"));

            parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory);
            parsedArgs.Errors.Verify(
                // error CS8301: Do not use refout when using refonly.
                Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1));

3042
            parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory);
3043
            parsedArgs.Errors.Verify();
3044 3045

            parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory);
3046
            parsedArgs.Errors.Verify();
3047

3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
            parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory);
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/refonly:incorrect'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1)
                );

            parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory);
            parsedArgs.Errors.Verify(
                // error CS8302: Cannot compile net modules when using /refout or /refonly.
                Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)
                );

            parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory);
            parsedArgs.Errors.Verify(
                // error CS8302: Cannot compile net modules when using /refout or /refonly.
                Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)
                );

P
Pilchie 已提交
3066
            // Dev11 reports CS2007: Unrecognized option: '/out'
3067
            parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3068 3069 3070 3071
            parsedArgs.Errors.Verify(
                // error CS2005: Missing file specification for '/out' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out"));

3072
            parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3073 3074 3075 3076
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+"));

            // Should preserve fully qualified paths
3077
            parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3078 3079 3080 3081 3082 3083 3084
            parsedArgs.Errors.Verify();
            Assert.Equal("MyBinary", parsedArgs.CompilationName);
            Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
            Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory);

            // Should handle quotes
3085
            parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3086 3087 3088 3089 3090 3091 3092
            parsedArgs.Errors.Verify();
            Assert.Equal(@"MyBinary", parsedArgs.CompilationName);
            Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
            Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory);

            // Should expand partially qualified paths
3093
            parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3094 3095 3096 3097 3098 3099 3100
            parsedArgs.Errors.Verify();
            Assert.Equal("MyBinary", parsedArgs.CompilationName);
            Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
            Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // Should expand partially qualified paths
3101
            parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3102 3103 3104 3105 3106 3107 3108
            parsedArgs.Errors.Verify();
            Assert.Equal("MyBinary", parsedArgs.CompilationName);
            Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
            Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory);

            // not specified: exe
3109
            parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory);
P
Pilchie 已提交
3110 3111 3112 3113 3114 3115 3116
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // not specified: dll
3117
            parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3118 3119 3120 3121 3122 3123 3124
            parsedArgs.Errors.Verify();
            Assert.Equal("a", parsedArgs.CompilationName);
            Assert.Equal("a.dll", parsedArgs.OutputFileName);
            Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // not specified: module
3125
            parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3126 3127 3128 3129 3130 3131
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationName);
            Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // not specified: appcontainerexe
3132
            parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3133 3134 3135 3136 3137 3138 3139
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // not specified: winmdobj
3140
            parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3141 3142 3143 3144 3145 3146 3147 3148
            parsedArgs.Errors.Verify();
            Assert.Equal("a", parsedArgs.CompilationName);
            Assert.Equal("a.winmdobj", parsedArgs.OutputFileName);
            Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // drive-relative path:
            char currentDrive = Directory.GetCurrentDirectory()[0];
3149
            parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory);
P
Pilchie 已提交
3150 3151
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long
3152
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs"));
P
Pilchie 已提交
3153 3154 3155 3156 3157 3158 3159

            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);
            Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);

            // UNC
3160
            parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3161 3162
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3163
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
P
Pilchie 已提交
3164 3165 3166 3167 3168

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3169
            parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory);
P
Pilchie 已提交
3170 3171 3172 3173 3174 3175 3176
            parsedArgs.Errors.Verify();

            Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory);
            Assert.Equal("file.exe", parsedArgs.OutputFileName);
            Assert.Equal("file", parsedArgs.CompilationName);
            Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName);

3177
            // invalid name:
3178
            parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3179 3180
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3181
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
P
Pilchie 已提交
3182 3183 3184 3185 3186 3187

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

            // Temporary skip following scenarios because of the error message changed (path)
3188
            //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3189 3190
            //parsedArgs.Errors.Verify(
            //    // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3191
            //    Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll"));
P
Pilchie 已提交
3192 3193

            // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z'
3194
            parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory);
P
Pilchie 已提交
3195 3196
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3197
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll"));
P
Pilchie 已提交
3198 3199 3200 3201

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);
3202

3203
            parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory);
3204 3205
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3206
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe")
3207 3208 3209 3210 3211 3212
                );

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3213
            parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory);
3214 3215
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3216
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe")
3217 3218 3219 3220 3221 3222
                );

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3223
            parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory);
3224 3225
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3226
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll")
3227 3228 3229 3230 3231 3232
                );

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3233
            parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory);
3234 3235
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3236
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule")
3237 3238 3239 3240 3241 3242
                );

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3243
            parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory);
3244 3245 3246 3247 3248 3249
            parsedArgs.Errors.Verify();

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3250
            parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory);
3251 3252 3253 3254 3255 3256
            parsedArgs.Errors.Verify();

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3257
            parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory);
3258 3259
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3260
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll")
3261 3262 3263 3264 3265 3266
                );

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

3267
            parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory);
3268 3269 3270 3271 3272
            parsedArgs.Errors.Verify();

            Assert.Equal(".netmodule", parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName);
P
Pilchie 已提交
3273 3274
        }

J
Jared Parsons 已提交
3275 3276
        [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")]
        [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")]
P
Pilchie 已提交
3277 3278 3279
        [Fact]
        public void ParseOut2()
        {
J
Jared Parsons 已提交
3280
            var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3281 3282
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3283
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
P
Pilchie 已提交
3284 3285 3286 3287 3288

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);

J
Jared Parsons 已提交
3289
            parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3290 3291
            parsedArgs.Errors.Verify(
                // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3292
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
P
Pilchie 已提交
3293 3294 3295 3296 3297 3298

            Assert.Null(parsedArgs.OutputFileName);
            Assert.Null(parsedArgs.CompilationName);
            Assert.Null(parsedArgs.CompilationOptions.ModuleName);
        }

3299 3300 3301
        [Fact]
        public void ParseInstrumentTestNames()
        {
J
Jared Parsons 已提交
3302
            var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory);
3303
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
3304

J
Jared Parsons 已提交
3305
            parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3306 3307 3308
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
3309
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
A
Artur Spychaj 已提交
3310

J
Jared Parsons 已提交
3311
            parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3312 3313 3314
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
3315
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
A
Artur Spychaj 已提交
3316

J
Jared Parsons 已提交
3317
            parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory);
3318 3319 3320
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
3321
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
3322

J
Jared Parsons 已提交
3323
            parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory);
3324
            parsedArgs.Errors.Verify(
3325
                // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
3326
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
3327
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
3328

J
Jared Parsons 已提交
3329
            parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3330 3331
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption"));
3332
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
A
Artur Spychaj 已提交
3333

J
Jared Parsons 已提交
3334
            parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3335 3336
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None"));
3337 3338
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));

J
Jared Parsons 已提交
3339
            parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory);
3340 3341 3342
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption"));
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
A
Artur Spychaj 已提交
3343

J
Jared Parsons 已提交
3344
            parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3345
            parsedArgs.Errors.Verify();
3346
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
A
Artur Spychaj 已提交
3347

J
Jared Parsons 已提交
3348
            parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory);
3349
            parsedArgs.Errors.Verify();
3350
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
A
Artur Spychaj 已提交
3351

J
Jared Parsons 已提交
3352
            parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory);
A
Artur Spychaj 已提交
3353
            parsedArgs.Errors.Verify();
3354 3355
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));

J
Jared Parsons 已提交
3356
            parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory);
3357 3358 3359
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));

J
Jared Parsons 已提交
3360
            parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory);
3361
            parsedArgs.Errors.Verify();
3362
            Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
3363 3364
        }

J
Jared Parsons 已提交
3365
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
3366 3367 3368 3369
        public void ParseDoc()
        {
            const string baseDirectory = @"C:\abc\def\baz";

3370
            var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3371 3372 3373 3374 3375
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:"));
            Assert.Null(parsedArgs.DocumentationPath);

3376
            parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3377 3378 3379 3380 3381 3382
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:"));
            Assert.Null(parsedArgs.DocumentationPath);

            // NOTE: no colon in error message '/doc'
3383
            parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3384 3385 3386 3387 3388
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc"));
            Assert.Null(parsedArgs.DocumentationPath);

3389
            parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3390 3391 3392 3393 3394
            parsedArgs.Errors.Verify(
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+"));
            Assert.Null(parsedArgs.DocumentationPath);

            // Should preserve fully qualified paths
3395
            parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3396 3397 3398 3399 3400
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);

            // Should handle quotes
3401
            parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3402 3403 3404 3405 3406
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);

            // Should expand partially qualified paths
3407
            parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3408 3409 3410 3411 3412
            parsedArgs.Errors.Verify();
            Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);

            // Should expand partially qualified paths
3413
            parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3414 3415 3416 3417 3418 3419
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);

            // drive-relative path:
            char currentDrive = Directory.GetCurrentDirectory()[0];
3420
            parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3421 3422
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long
3423
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml"));
P
Pilchie 已提交
3424 3425 3426 3427 3428

            Assert.Null(parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect

            // UNC
3429
            parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3430
            parsedArgs.Errors.Verify(
3431
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
P
Pilchie 已提交
3432 3433 3434 3435

            Assert.Null(parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect

3436
            parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory);
P
Pilchie 已提交
3437 3438 3439 3440 3441 3442
            parsedArgs.Errors.Verify();

            Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);

            // invalid name:
3443
            parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3444
            parsedArgs.Errors.Verify(
3445
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
P
Pilchie 已提交
3446 3447 3448 3449 3450

            Assert.Null(parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect

            // Temp
3451
            // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3452
            // parsedArgs.Errors.Verify(
3453
            //    Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml"));
P
Pilchie 已提交
3454 3455 3456 3457

            // Assert.Null(parsedArgs.DocumentationPath);
            // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect

3458
            parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory);
P
Pilchie 已提交
3459 3460
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3461
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml"));
P
Pilchie 已提交
3462 3463 3464 3465 3466

            Assert.Null(parsedArgs.DocumentationPath);
            Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
        }

J
Jared Parsons 已提交
3467
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
3468 3469 3470 3471
        public void ParseErrorLog()
        {
            const string baseDirectory = @"C:\abc\def\baz";

3472
            var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory);
3473 3474 3475 3476
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<file>' for '/errorlog:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<file>", "/errorlog:"));
            Assert.Null(parsedArgs.ErrorLogPath);
3477
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3478

3479
            parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory);
3480 3481 3482 3483
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<file>' for '/errorlog:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<file>", "/errorlog:"));
            Assert.Null(parsedArgs.ErrorLogPath);
3484
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3485

3486
            parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory);
3487 3488 3489 3490
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<file>' for '/errorlog' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<file>", "/errorlog"));
            Assert.Null(parsedArgs.ErrorLogPath);
3491
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3492 3493

            // Should preserve fully qualified paths
3494
            parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory);
3495 3496
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogPath);
3497
            Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3498

3499
            // Escaped quote in the middle is an error
3500
            parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory);
3501
            parsedArgs.Errors.Verify(
3502
                 Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1));
3503 3504 3505

            // Should handle quotes
            parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory);
3506 3507
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogPath);
3508
            Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3509 3510

            // Should expand partially qualified paths
3511
            parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory);
3512 3513
            parsedArgs.Errors.Verify();
            Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogPath);
3514
            Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3515 3516

            // Should expand partially qualified paths
3517
            parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory);
3518 3519
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogPath);
3520
            Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3521 3522 3523

            // drive-relative path:
            char currentDrive = Directory.GetCurrentDirectory()[0];
3524
            parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory);
3525 3526
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long
3527
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml"));
3528 3529

            Assert.Null(parsedArgs.ErrorLogPath);
3530
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3531 3532

            // UNC
3533
            parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory);
3534
            parsedArgs.Errors.Verify(
3535
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
3536 3537

            Assert.Null(parsedArgs.ErrorLogPath);
3538
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3539

3540
            parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory);
3541 3542 3543 3544 3545
            parsedArgs.Errors.Verify();

            Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogPath);

            // invalid name:
3546
            parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory);
3547
            parsedArgs.Errors.Verify(
3548
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
3549 3550

            Assert.Null(parsedArgs.ErrorLogPath);
3551
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3552

3553
            parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory);
3554 3555
            parsedArgs.Errors.Verify(
                // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
3556
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml"));
3557 3558

            Assert.Null(parsedArgs.ErrorLogPath);
3559
            Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
3560 3561
        }

J
jaredpar 已提交
3562
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
3563 3564 3565 3566
        public void AppConfigParse()
        {
            const string baseDirectory = @"C:\abc\def\baz";

3567
            var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3568 3569 3570 3571 3572
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:"));
            Assert.Null(parsedArgs.AppConfigPath);

3573
            parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3574 3575 3576 3577 3578
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:"));
            Assert.Null(parsedArgs.AppConfigPath);

3579
            parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3580 3581 3582 3583 3584
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig"));
            Assert.Null(parsedArgs.AppConfigPath);

3585
            parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
            parsedArgs.Errors.Verify();
            Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath);

            // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath
        }

        [Fact]
        public void AppConfigBasic()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);
            var appConfigFile = Temp.CreateFile().WriteAllText(
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
       <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/>
    </assemblyBinding>
  </runtime>
</configuration>");

3607 3608
            var silverlight = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path;
            var net4_0dll = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.System).Path;
P
Pilchie 已提交
3609 3610 3611

            // Test linking two appconfig dlls with simple src
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
3612
            var exitCode = CreateCSharpCompiler(null, srcDirectory,
P
Pilchie 已提交
3613 3614 3615 3616 3617 3618 3619
                new[] { "/nologo",
                        "/r:" + silverlight,
                        "/r:" + net4_0dll,
                        "/appconfig:" + appConfigFile.Path,
                        srcFile.Path }).Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
3620 3621 3622

            CleanupAllGeneratedFiles(srcFile.Path);
            CleanupAllGeneratedFiles(appConfigFile.Path);
P
Pilchie 已提交
3623 3624
        }

J
jaredpar 已提交
3625
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
3626 3627 3628 3629
        public void AppConfigBasicFail()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);
3630
            string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready'
C
CyrusNajmabadi 已提交
3631

P
Pilchie 已提交
3632
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
3633
            var exitCode = CreateCSharpCompiler(null, srcDirectory,
3634
                new[] { "/nologo", "/preferreduilang:en",
3635
                        $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" ,
P
Pilchie 已提交
3636 3637
                        srcFile.Path }).Run(outWriter);
            Assert.NotEqual(0, exitCode);
3638
            Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim());
3639 3640

            CleanupAllGeneratedFiles(srcFile.Path);
P
Pilchie 已提交
3641 3642
        }

J
jaredpar 已提交
3643
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
3644 3645 3646 3647 3648
        public void ParseDocAndOut()
        {
            const string baseDirectory = @"C:\abc\def\baz";

            // Can specify separate directories for binary and XML output.
3649
            var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3650 3651 3652 3653 3654 3655 3656 3657
            parsedArgs.Errors.Verify();

            Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath);

            Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
            Assert.Equal("d.exe", parsedArgs.OutputFileName);

            // XML does not fall back on output directory.
3658
            parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
P
Pilchie 已提交
3659 3660 3661 3662 3663 3664 3665 3666
            parsedArgs.Errors.Verify();

            Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath);

            Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
            Assert.Equal("d.exe", parsedArgs.OutputFileName);
        }

J
jaredpar 已提交
3667
        [ConditionalFact(typeof(WindowsOnly))]
3668 3669 3670 3671 3672
        public void ParseErrorLogAndOut()
        {
            const string baseDirectory = @"C:\abc\def\baz";

            // Can specify separate directories for binary and error log output.
3673
            var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
3674 3675 3676 3677 3678 3679 3680 3681
            parsedArgs.Errors.Verify();

            Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogPath);

            Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
            Assert.Equal("d.exe", parsedArgs.OutputFileName);

            // XML does not fall back on output directory.
3682
            parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
3683 3684 3685 3686 3687 3688 3689 3690
            parsedArgs.Errors.Verify();

            Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogPath);

            Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
            Assert.Equal("d.exe", parsedArgs.OutputFileName);
        }

P
Pilchie 已提交
3691 3692 3693
        [Fact]
        public void ModuleAssemblyName()
        {
J
Jared Parsons 已提交
3694
            var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3695
            parsedArgs.Errors.Verify();
3696
            Assert.Equal("goo", parsedArgs.CompilationName);
P
Pilchie 已提交
3697 3698
            Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName);

J
Jared Parsons 已提交
3699
            parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3700 3701 3702 3703
            parsedArgs.Errors.Verify(
                // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
                Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));

J
Jared Parsons 已提交
3704
            parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3705 3706 3707 3708
            parsedArgs.Errors.Verify(
                // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
                Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));

J
Jared Parsons 已提交
3709
            parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3710 3711 3712 3713 3714
            parsedArgs.Errors.Verify(
                // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
                Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));
        }

3715 3716 3717
        [Fact]
        public void ModuleName()
        {
J
Jared Parsons 已提交
3718
            var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory);
3719
            parsedArgs.Errors.Verify();
3720
            Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName);
3721

J
Jared Parsons 已提交
3722
            parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory);
3723 3724 3725
            parsedArgs.Errors.Verify();
            Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName);

J
Jared Parsons 已提交
3726
            parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory);
3727 3728 3729
            parsedArgs.Errors.Verify();
            Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName);

J
Jared Parsons 已提交
3730
            parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory);
3731
            parsedArgs.Errors.Verify();
3732
            Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName);
3733

J
Jared Parsons 已提交
3734
            parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory);
3735 3736 3737 3738 3739 3740 3741
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1)
                );
        }

        [Fact]
3742
        public void ModuleName001()
3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
        {
            var dir = Temp.CreateDirectory();

            var file1 = dir.CreateFile("a.cs");
            file1.WriteAllText(@"
                    class c1
                    {
                        public static void Main(){}
                    }
                ");

            var exeName = "aa.exe";
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
3756
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path });
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
            int exitCode = csc.Run(outWriter);
            if (exitCode != 0)
            {
                Console.WriteLine(outWriter.ToString());
                Assert.Equal(0, exitCode);
            }


            Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count());

            using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe"))))
            {
                var peReader = metadata.Module.GetMetadataReader();

                Assert.True(peReader.IsAssembly);

                Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name));
                Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name));
            }

            if (System.IO.File.Exists(exeName))
            {
                System.IO.File.Delete(exeName);
            }

            CleanupAllGeneratedFiles(file1.Path);
        }

P
Pilchie 已提交
3785 3786 3787
        [Fact]
        public void ParsePlatform()
        {
J
Jared Parsons 已提交
3788
            var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3789 3790 3791
            Assert.False(parsedArgs.Errors.Any());
            Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3792
            parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3793 3794 3795
            Assert.False(parsedArgs.Errors.Any());
            Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3796
            parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3797 3798 3799 3800
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code);
            Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3801
            parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3802 3803 3804
            parsedArgs.Errors.Verify();
            Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3805
            parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3806 3807 3808
            parsedArgs.Errors.Verify();
            Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3809
            parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3810 3811 3812
            parsedArgs.Errors.Verify();
            Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3813
            parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3814 3815 3816
            parsedArgs.Errors.Verify();
            Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform);

J
Jared Parsons 已提交
3817
            parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3818 3819 3820 3821 3822
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform"));
            Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);  //anycpu is default

J
Jared Parsons 已提交
3823
            parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3824 3825 3826 3827 3828 3829
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:"));
            Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);  //anycpu is default
        }

J
Jared Parsons 已提交
3830 3831 3832 3833
        [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")]
        [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")]
        [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")]
        [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")]
P
Pilchie 已提交
3834 3835 3836
        [Fact]
        public void ParseBaseAddress()
        {
J
Jared Parsons 已提交
3837
            var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3838 3839 3840
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
3841
            parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3842
            Assert.False(parsedArgs.Errors.Any());
3843
            Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress);
P
Pilchie 已提交
3844

J
Jared Parsons 已提交
3845
            parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3846 3847 3848
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
3849
            parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3850 3851 3852
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
3853
            parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3854 3855 3856
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
3857
            parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory);
3858
            Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress);
P
Pilchie 已提交
3859

J
Jared Parsons 已提交
3860
            parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3861 3862
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
3863
            parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3864 3865
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
3866
            parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory);
P
Pilchie 已提交
3867 3868
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF"));

J
Jared Parsons 已提交
3869
            parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory);
P
Pilchie 已提交
3870 3871
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000"));

J
Jared Parsons 已提交
3872
            parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory);
P
Pilchie 已提交
3873 3874
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000"));

J
Jared Parsons 已提交
3875
            parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory);
P
Pilchie 已提交
3876 3877
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
3878
            parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory);
P
Pilchie 已提交
3879 3880
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
3881
            parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory);
P
Pilchie 已提交
3882 3883
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
3884
            parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory);
P
Pilchie 已提交
3885 3886
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000"));

J
Jared Parsons 已提交
3887
            parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory);
P
Pilchie 已提交
3888 3889
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000"));

J
Jared Parsons 已提交
3890
            parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory);
P
Pilchie 已提交
3891 3892 3893 3894 3895 3896
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000"));
        }

        [Fact]
        public void ParseFileAlignment()
        {
J
Jared Parsons 已提交
3897
            var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3898 3899
            parsedArgs.Errors.Verify(
                // error CS2024: Invalid file section alignment number 'x64'
3900
                Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64"));
P
Pilchie 已提交
3901

J
Jared Parsons 已提交
3902
            parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3903
            parsedArgs.Errors.Verify();
3904
            Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment);
P
Pilchie 已提交
3905

J
Jared Parsons 已提交
3906
            parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3907
            parsedArgs.Errors.Verify();
3908
            Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment);
P
Pilchie 已提交
3909

J
Jared Parsons 已提交
3910
            parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3911 3912 3913 3914
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign"));

J
Jared Parsons 已提交
3915
            parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3916 3917
            parsedArgs.Errors.Verify(
                // error CS2024: Invalid file section alignment number '-23'
3918
                Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23"));
P
Pilchie 已提交
3919

J
Jared Parsons 已提交
3920
            parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3921
            parsedArgs.Errors.Verify();
3922
            Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment);
P
Pilchie 已提交
3923

J
Jared Parsons 已提交
3924
            parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3925 3926
            parsedArgs.Errors.Verify(
                // error CS2024: Invalid file section alignment number '0'
3927
                Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0"));
P
Pilchie 已提交
3928

J
Jared Parsons 已提交
3929
            parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3930 3931
            parsedArgs.Errors.Verify(
                // error CS2024: Invalid file section alignment number '123'
3932
                Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123"));
P
Pilchie 已提交
3933 3934
        }

J
jaredpar 已提交
3935
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
3936
        public void SdkPathAndLibEnvVariable()
T
Tomas Matousek 已提交
3937 3938 3939 3940 3941 3942
        {
            var dir = Temp.CreateDirectory();
            var lib1 = dir.CreateDirectory("lib1");
            var lib2 = dir.CreateDirectory("lib2");
            var lib3 = dir.CreateDirectory("lib3");

J
Jared Parsons 已提交
3943 3944
            var sdkDirectory = SdkDirectory;
            var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory);
C
CyrusNajmabadi 已提交
3945
            AssertEx.Equal(new[]
T
Tomas Matousek 已提交
3946
            {
J
Jared Parsons 已提交
3947
                sdkDirectory,
T
Tomas Matousek 已提交
3948 3949 3950 3951 3952 3953 3954 3955
                lib1.Path,
                lib2.Path,
                lib3.Path
            }, parsedArgs.ReferencePaths);
        }

        [ConditionalFact(typeof(WindowsOnly))]
        public void SdkPathAndLibEnvVariable_Errors()
P
Pilchie 已提交
3956
        {
J
Jared Parsons 已提交
3957
            var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3958 3959 3960 3961 3962 3963
            parsedArgs.Errors.Verify(
                // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"),
                // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist"));

J
Jared Parsons 已提交
3964
            parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3965 3966 3967 3968 3969 3970
            parsedArgs.Errors.Verify(
                // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"),
                // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid"));

J
Jared Parsons 已提交
3971
            parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3972 3973 3974 3975 3976 3977
            parsedArgs.Errors.Verify(
                // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"),
                // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist"));

J
Jared Parsons 已提交
3978
            parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990
            parsedArgs.Errors.Verify(
                // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"),
                // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"),
                // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"),
                // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"),
                // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"));

J
Jared Parsons 已提交
3991
            parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3992 3993
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));

J
Jared Parsons 已提交
3994
            parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3995 3996
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));

J
Jared Parsons 已提交
3997
            parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
3998 3999
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+"));

J
Jared Parsons 已提交
4000
            parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory);
4001
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));
P
Pilchie 已提交
4002 4003
        }

J
Jared Parsons 已提交
4004
        [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")]
T
Renames  
TomasMatousek 已提交
4005
        public void SdkPathAndLibEnvVariable_Relative_csc()
P
Pilchie 已提交
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
        {
            var tempFolder = Temp.CreateDirectory();
            var baseDirectory = tempFolder.ToString();

            var subFolder = tempFolder.CreateDirectory("temp");
            var subDirectory = subFolder.ToString();

            var src = Temp.CreateFile("a.cs");
            src.WriteAllText("public class C{}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4017
            int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
4018 4019 4020 4021
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4022
            exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
4023 4024
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
4025 4026

            CleanupAllGeneratedFiles(src.Path);
P
Pilchie 已提交
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
        }

        [Fact]
        public void UnableWriteOutput()
        {
            var tempFolder = Temp.CreateDirectory();
            var baseDirectory = tempFolder.ToString();
            var subFolder = tempFolder.CreateDirectory("temp");

            var src = Temp.CreateFile("a.cs");
            src.WriteAllText("public class C{}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4040
            int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter);
P
Pilchie 已提交
4041
            Assert.Equal(1, exitCode);
4042
            Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists.
4043 4044

            CleanupAllGeneratedFiles(src.Path);
P
Pilchie 已提交
4045 4046 4047 4048 4049
        }

        [Fact]
        public void ParseHighEntropyVA()
        {
J
Jared Parsons 已提交
4050
            var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4051
            Assert.False(parsedArgs.Errors.Any());
4052
            Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
J
Jared Parsons 已提交
4053
            parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4054
            Assert.False(parsedArgs.Errors.Any());
4055
            Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
J
Jared Parsons 已提交
4056
            parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4057
            Assert.False(parsedArgs.Errors.Any());
4058
            Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
J
Jared Parsons 已提交
4059
            parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4060
            Assert.Equal(1, parsedArgs.Errors.Length);
4061
            Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
P
Pilchie 已提交
4062

J
Jared Parsons 已提交
4063
            parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4064
            Assert.Equal(1, parsedArgs.Errors.Length);
4065
            Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
P
Pilchie 已提交
4066 4067

            //last one wins
J
Jared Parsons 已提交
4068
            parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4069
            Assert.False(parsedArgs.Errors.Any());
4070
            Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
P
Pilchie 已提交
4071 4072 4073 4074 4075
        }

        [Fact]
        public void Checked()
        {
J
Jared Parsons 已提交
4076
            var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4077 4078 4079
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.CheckOverflow);

J
Jared Parsons 已提交
4080
            parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4081 4082 4083
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.CheckOverflow);

J
Jared Parsons 已提交
4084
            parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4085 4086 4087
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.CheckOverflow);

J
Jared Parsons 已提交
4088
            parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4089 4090 4091
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.CheckOverflow);

J
Jared Parsons 已提交
4092
            parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4093 4094 4095
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:"));
        }

4096 4097 4098
        [Fact]
        public void Nullable()
        {
4099
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
4100 4101 4102
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationOptions.Nullable);

4103
            parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory);
4104 4105 4106 4107 4108 4109
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'True' for C# 7.0. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "True", "7.0", "8.0").WithLocation(1, 1)
                );
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4110
            parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory);
4111 4112 4113 4114 4115 4116
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'False' for C# 7.0. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "False", "7.0", "8.0").WithLocation(1, 1)
                );
            Assert.False(parsedArgs.CompilationOptions.Nullable);

4117
            parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory);
4118 4119 4120 4121 4122 4123
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'True' for C# 7.0. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "True", "7.0", "8.0").WithLocation(1, 1)
                );
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4124
            parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
4125 4126 4127
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4128
            parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
4129 4130 4131
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.Nullable);

4132
            parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
4133 4134 4135
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4136
            parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
4137 4138 4139
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4140
            parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
4141 4142 4143
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.Nullable);

4144
            parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
4145 4146 4147
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/nullable:"));
            Assert.Null(parsedArgs.CompilationOptions.Nullable);

4148
            parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory);
4149 4150 4151 4152 4153 4154
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'True' for C# 7.3. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "True", "7.3", "8.0").WithLocation(1, 1)
                );
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4155
            parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.3", "a.cs" }, WorkingDirectory);
4156 4157 4158 4159 4160 4161
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'False' for C# 7.3. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "False", "7.3", "8.0").WithLocation(1, 1)
                );
            Assert.False(parsedArgs.CompilationOptions.Nullable);

4162
            parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory);
4163 4164 4165 4166 4167 4168
            parsedArgs.Errors.Verify(
                // error CS8630: Invalid 'nullable' value: 'True' for C# 7.3. Please use language version 8.0 or greater.
                Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "True", "7.3", "8.0").WithLocation(1, 1)
                );
            Assert.True(parsedArgs.CompilationOptions.Nullable);

4169
            parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory);
4170 4171 4172
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationOptions.Nullable);

4173
            parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory);
4174 4175 4176 4177
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationOptions.Nullable);
        }

P
Pilchie 已提交
4178 4179 4180 4181 4182
        [Fact]
        public void Usings()
        {
            CSharpCommandLineArguments parsedArgs;

J
Jared Parsons 已提交
4183 4184
            var sdkDirectory = SdkDirectory;
            parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
4185
            parsedArgs.Errors.Verify();
4186
            AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
P
Pilchie 已提交
4187

J
Jared Parsons 已提交
4188
            parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
4189
            parsedArgs.Errors.Verify();
4190
            AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
P
Pilchie 已提交
4191

J
Jared Parsons 已提交
4192
            parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
4193
            parsedArgs.Errors.Verify();
4194
            AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
P
Pilchie 已提交
4195

J
Jared Parsons 已提交
4196
            parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory);
P
Pilchie 已提交
4197 4198 4199 4200 4201
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:"));
        }

4202
        [Fact]
P
Pilchie 已提交
4203 4204
        public void WarningsErrors()
        {
J
Jared Parsons 已提交
4205
            var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4206 4207 4208 4209
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn"));

J
Jared Parsons 已提交
4210
            parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4211 4212 4213 4214
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn"));

4215 4216 4217
            // Previous versions of the compiler used to report a warning (CS1691)
            // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror.
            // We no longer generate a warning in such cases.
J
Jared Parsons 已提交
4218
            parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory);
4219 4220
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
4221
            parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory);
4222
            parsedArgs.Errors.Verify();
P
Pilchie 已提交
4223

J
Jared Parsons 已提交
4224
            parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4225 4226 4227 4228
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror"));

J
Jared Parsons 已提交
4229
            parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory);
4230 4231
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
4232
            parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory);
4233 4234
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
4235
            parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory);
4236
            parsedArgs.Errors.Verify();
P
Pilchie 已提交
4237

J
Jared Parsons 已提交
4238
            parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4239 4240 4241 4242
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+"));

J
Jared Parsons 已提交
4243
            parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4244 4245 4246 4247
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-"));

J
Jared Parsons 已提交
4248
            parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4249 4250 4251 4252
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w"));

J
Jared Parsons 已提交
4253
            parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4254 4255 4256 4257
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w"));

J
Jared Parsons 已提交
4258
            parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4259 4260 4261 4262
            parsedArgs.Errors.Verify(
                // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn"));

J
Jared Parsons 已提交
4263
            parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4264 4265 4266 4267
            parsedArgs.Errors.Verify(
                // error CS1900: Warning level must be in the range 0-4
                Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w"));

J
Jared Parsons 已提交
4268
            parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4269 4270 4271 4272
            parsedArgs.Errors.Verify(
                // error CS1900: Warning level must be in the range 0-4
                Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w"));

J
Jared Parsons 已提交
4273
            parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4274 4275 4276 4277
            parsedArgs.Errors.Verify(
                // error CS1900: Warning level must be in the range 0-4
                Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn"));

J
Jared Parsons 已提交
4278
            parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4279 4280 4281 4282
            parsedArgs.Errors.Verify(
                // error CS1900: Warning level must be in the range 0-4
                Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn"));

4283 4284 4285
            // Previous versions of the compiler used to report a warning (CS1691)
            // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror.
            // We no longer generate a warning in such cases.
J
Jared Parsons 已提交
4286
            parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory);
4287
            parsedArgs.Errors.Verify();
P
Pilchie 已提交
4288

J
Jared Parsons 已提交
4289
            parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory);
4290
            parsedArgs.Errors.Verify();
P
Pilchie 已提交
4291

J
Jared Parsons 已提交
4292
            parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory);
4293
            parsedArgs.Errors.Verify();
P
Pilchie 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
        }

        private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args)
        {
            var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key);

            AssertEx.Equal(
                expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)),
                actualOrdered.Select(entry => entry.Key));

            AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value));
        }

4307
        [Fact]
P
Pilchie 已提交
4308 4309
        public void WarningsParse()
        {
J
Jared Parsons 已提交
4310
            var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4311 4312 4313 4314 4315
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count);

J
Jared Parsons 已提交
4316
            parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4317 4318 4319 4320 4321
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);

J
Jared Parsons 已提交
4322
            parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4323 4324 4325 4326 4327
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);

J
Jared Parsons 已提交
4328
            parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4329 4330 4331 4332 4333
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);

J
Jared Parsons 已提交
4334
            parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4335 4336 4337 4338 4339
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);

J
Jared Parsons 已提交
4340
            parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4341 4342 4343 4344 4345
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);

J
Jared Parsons 已提交
4346
            parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4347 4348 4349
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
4350
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs);
P
Pilchie 已提交
4351

J
Jared Parsons 已提交
4352
            parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4353 4354 4355 4356
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(
M
manishv 已提交
4357
                new[] { 1062, 1066, 1734, 1762, 1974 },
4358
                new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default },
P
Pilchie 已提交
4359 4360
                parsedArgs);

J
Jared Parsons 已提交
4361
            parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4362 4363 4364 4365
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count);
4366
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs);
P
Pilchie 已提交
4367

J
Jared Parsons 已提交
4368
            parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4369 4370 4371
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
4372
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs);
P
Pilchie 已提交
4373

J
Jared Parsons 已提交
4374
            parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4375 4376 4377 4378 4379
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);

J
Jared Parsons 已提交
4380
            parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4381 4382 4383 4384 4385
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);

J
Jared Parsons 已提交
4386
            parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4387 4388 4389 4390 4391
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);

J
Jared Parsons 已提交
4392
            parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4393 4394 4395 4396 4397
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs);

J
Jared Parsons 已提交
4398
            parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4399 4400 4401 4402 4403
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs);

J
Jared Parsons 已提交
4404
            parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4405 4406 4407
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
M
manishv 已提交
4408
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs);
P
Pilchie 已提交
4409

J
Jared Parsons 已提交
4410
            parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4411 4412 4413
            parsedArgs.Errors.Verify();
            Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
            Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
M
manishv 已提交
4414
            AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs);
P
Pilchie 已提交
4415 4416 4417 4418 4419
        }

        [Fact]
        public void AllowUnsafe()
        {
J
Jared Parsons 已提交
4420
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4421 4422 4423
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);

J
Jared Parsons 已提交
4424
            parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4425 4426 4427
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);

J
Jared Parsons 已提交
4428
            parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4429 4430 4431
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.AllowUnsafe);

J
Jared Parsons 已提交
4432
            parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4433 4434 4435
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);

J
Jared Parsons 已提交
4436
            parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default
P
Pilchie 已提交
4437 4438 4439
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.AllowUnsafe);

J
Jared Parsons 已提交
4440
            parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4441 4442
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:"));

J
Jared Parsons 已提交
4443
            parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4444 4445
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+"));

J
Jared Parsons 已提交
4446
            parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4447 4448 4449 4450 4451 4452 4453 4454
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:"));
        }

        [Fact]
        public void DelaySign()
        {
            CSharpCommandLineArguments parsedArgs;

J
Jared Parsons 已提交
4455
            parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4456 4457 4458 4459
            parsedArgs.Errors.Verify();
            Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
            Assert.True((bool)parsedArgs.CompilationOptions.DelaySign);

J
Jared Parsons 已提交
4460
            parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4461 4462 4463 4464
            parsedArgs.Errors.Verify();
            Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
            Assert.True((bool)parsedArgs.CompilationOptions.DelaySign);

J
Jared Parsons 已提交
4465
            parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4466 4467 4468 4469
            parsedArgs.Errors.Verify();
            Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
            Assert.False((bool)parsedArgs.CompilationOptions.DelaySign);

J
Jared Parsons 已提交
4470
            parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4471 4472 4473 4474 4475 4476 4477
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/delaysign:-'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-"));

            Assert.Null(parsedArgs.CompilationOptions.DelaySign);
        }

A
Andy Gocke 已提交
4478 4479 4480
        [Fact]
        public void PublicSign()
        {
J
Jared Parsons 已提交
4481
            var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory);
A
Andy Gocke 已提交
4482 4483 4484
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.PublicSign);

J
Jared Parsons 已提交
4485
            parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory);
A
Andy Gocke 已提交
4486 4487 4488
            parsedArgs.Errors.Verify();
            Assert.True(parsedArgs.CompilationOptions.PublicSign);

J
Jared Parsons 已提交
4489
            parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory);
A
Andy Gocke 已提交
4490 4491 4492
            parsedArgs.Errors.Verify();
            Assert.False(parsedArgs.CompilationOptions.PublicSign);

J
Jared Parsons 已提交
4493
            parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory);
A
Andy Gocke 已提交
4494
            parsedArgs.Errors.Verify(
4495 4496
                // error CS2007: Unrecognized option: '/publicsign:-'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1));
A
Andy Gocke 已提交
4497 4498 4499 4500

            Assert.False(parsedArgs.CompilationOptions.PublicSign);
        }

4501 4502 4503 4504
        [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")]
        [Fact]
        public void PublicSign_KeyFileRelativePath()
        {
J
Jared Parsons 已提交
4505
            var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory);
4506
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
4507
            Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile);
4508 4509
        }

4510 4511 4512 4513
        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void PublicSignWithEmptyKeyPath()
        {
J
Jared Parsons 已提交
4514
            DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify(
4515 4516 4517 4518 4519 4520 4521 4522
                // error CS2005: Missing file specification for 'keyfile' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1));
        }

        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void PublicSignWithEmptyKeyPath2()
        {
J
Jared Parsons 已提交
4523
            DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify(
4524 4525 4526 4527
                // error CS2005: Missing file specification for 'keyfile' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1));
        }

J
Jared Parsons 已提交
4528
        [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")]
P
Pilchie 已提交
4529 4530 4531
        [Fact]
        public void SubsystemVersionTests()
        {
J
Jared Parsons 已提交
4532
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4533
            parsedArgs.Errors.Verify();
4534
            Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion);
P
Pilchie 已提交
4535 4536 4537

            // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input.
            // It is normalized at the time of emit.
J
Jared Parsons 已提交
4538
            parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4539
            parsedArgs.Errors.Verify(); // no error in Dev11
4540
            Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion);
P
Pilchie 已提交
4541

J
Jared Parsons 已提交
4542
            parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4543
            parsedArgs.Errors.Verify(); // no error in Dev11
4544
            Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion);
P
Pilchie 已提交
4545

J
Jared Parsons 已提交
4546
            parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4547
            parsedArgs.Errors.Verify(); // no error in Dev11
4548
            Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion);
P
Pilchie 已提交
4549

J
Jared Parsons 已提交
4550
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4551
            parsedArgs.Errors.Verify();
4552
            Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion);
P
Pilchie 已提交
4553

J
Jared Parsons 已提交
4554
            parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4555 4556
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));

J
Jared Parsons 已提交
4557
            parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4558 4559
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));

J
Jared Parsons 已提交
4560
            parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4561 4562
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-"));

J
Jared Parsons 已提交
4563
            parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4564 4565
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));

J
Jared Parsons 已提交
4566
            parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory);
4567
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1"));
P
Pilchie 已提交
4568

J
Jared Parsons 已提交
4569
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory);
4570
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0"));
P
Pilchie 已提交
4571

J
Jared Parsons 已提交
4572
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory);
4573
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0"));
P
Pilchie 已提交
4574

J
Jared Parsons 已提交
4575
            parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory);
4576
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("."));
P
Pilchie 已提交
4577

J
Jared Parsons 已提交
4578
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory);
4579
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4."));
P
Pilchie 已提交
4580

J
Jared Parsons 已提交
4581
            parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory);
4582
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0"));
P
Pilchie 已提交
4583

J
Jared Parsons 已提交
4584
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4585 4586
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
4587
            parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory);
4588
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536"));
P
Pilchie 已提交
4589

J
Jared Parsons 已提交
4590
            parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory);
4591
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0"));
P
Pilchie 已提交
4592

J
Jared Parsons 已提交
4593
            parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory);
4594
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0"));
P
Pilchie 已提交
4595 4596 4597 4598 4599 4600 4601

            // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer'
        }

        [Fact]
        public void MainType()
        {
J
Jared Parsons 已提交
4602
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4603 4604 4605
            parsedArgs.Errors.Verify();
            Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName);

J
Jared Parsons 已提交
4606
            parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11
P
Pilchie 已提交
4607 4608 4609 4610
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m"));
            Assert.Null(parsedArgs.CompilationOptions.MainTypeName);

            //  overriding the value
J
Jared Parsons 已提交
4611
            parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4612 4613 4614 4615
            parsedArgs.Errors.Verify();
            Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName);

            //  error
J
Jared Parsons 已提交
4616
            parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4617 4618
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main"));

J
Jared Parsons 已提交
4619
            parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4620 4621
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+"));

J
Jared Parsons 已提交
4622
            parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4623 4624 4625
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m"));

            //  incompatible values /main && /target
J
Jared Parsons 已提交
4626
            parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4627 4628
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL));

J
Jared Parsons 已提交
4629
            parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4630 4631 4632 4633 4634 4635
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL));
        }

        [Fact]
        public void Codepage()
        {
J
Jared Parsons 已提交
4636
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4637 4638 4639
            parsedArgs.Errors.Verify();
            Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName);

J
Jared Parsons 已提交
4640
            parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4641 4642 4643 4644
            parsedArgs.Errors.Verify();
            Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName);

            //  error
J
Jared Parsons 已提交
4645
            parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4646 4647
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0"));

J
Jared Parsons 已提交
4648
            parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4649 4650
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc"));

J
Jared Parsons 已提交
4651
            parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4652 4653
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5"));

J
Jared Parsons 已提交
4654
            parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4655 4656
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments(""));

J
Jared Parsons 已提交
4657
            parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4658 4659
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments(""));

J
Jared Parsons 已提交
4660
            parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4661 4662
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage"));

J
Jared Parsons 已提交
4663
            parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4664 4665 4666
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+"));
        }

4667
        [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")]
4668 4669
        public void ChecksumAlgorithm()
        {
J
Jared Parsons 已提交
4670
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory);
4671 4672
            parsedArgs.Errors.Verify();
            Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm);
4673
            Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
4674

J
Jared Parsons 已提交
4675
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory);
4676 4677
            parsedArgs.Errors.Verify();
            Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm);
4678
            Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
4679

J
Jared Parsons 已提交
4680
            parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
4681 4682
            parsedArgs.Errors.Verify();
            Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm);
4683
            Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
4684 4685

            //  error
J
Jared Parsons 已提交
4686
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory);
4687 4688
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256"));

J
Jared Parsons 已提交
4689
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory);
4690 4691
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1"));

J
Jared Parsons 已提交
4692
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory);
4693 4694
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha"));

J
Jared Parsons 已提交
4695
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory);
4696 4697
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));

J
Jared Parsons 已提交
4698
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory);
4699 4700
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));

J
Jared Parsons 已提交
4701
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory);
4702 4703
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));

J
Jared Parsons 已提交
4704
            parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory);
4705 4706 4707
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+"));
        }

P
Pilchie 已提交
4708 4709 4710
        [Fact]
        public void AddModule()
        {
J
Jared Parsons 已提交
4711
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4712 4713 4714 4715 4716
            parsedArgs.Errors.Verify();
            Assert.Equal(1, parsedArgs.MetadataReferences.Length);
            Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference);
            Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind);

J
Jared Parsons 已提交
4717
            parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4718 4719 4720 4721 4722 4723 4724 4725 4726 4727
            parsedArgs.Errors.Verify();
            Assert.Equal(3, parsedArgs.MetadataReferences.Length);
            Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference);
            Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind);
            Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference);
            Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind);
            Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference);
            Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind);

            //  error
J
Jared Parsons 已提交
4728
            parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4729 4730
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:"));

J
Jared Parsons 已提交
4731
            parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4732 4733
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+"));

J
Jared Parsons 已提交
4734
            parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4735 4736 4737
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:"));
        }

J
Jared Parsons 已提交
4738
        [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")]
P
Pilchie 已提交
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
        public void CS7061fromCS0647_ModuleWithCompilationRelaxations()
        {
            string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
public class Mod { }").Path;

            string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(4)]
public class Mod { }").Path;

            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
class Test { static void Main() {} }").Path;

            var baseDir = Path.GetDirectoryName(source);
            // === Scenario 1 ===
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4759
            int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
P
Pilchie 已提交
4760 4761 4762 4763
            Assert.Equal(0, exitCode);

            var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4764
            var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory);
P
Pilchie 已提交
4765
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
4766
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter);
P
Pilchie 已提交
4767 4768 4769 4770
            Assert.Empty(outWriter.ToString());

            // === Scenario 2 ===
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4771
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter);
P
Pilchie 已提交
4772 4773 4774 4775
            Assert.Equal(0, exitCode);

            modfile = source2.Substring(0, source2.Length - 2) + "netmodule";
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4776
            parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory);
P
Pilchie 已提交
4777
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
4778
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter);
P
Pilchie 已提交
4779 4780
            Assert.Equal(1, exitCode);
            // Dev11: CS0647 (Emit)
4781
            Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal);
4782 4783 4784 4785

            CleanupAllGeneratedFiles(source1);
            CleanupAllGeneratedFiles(source2);
            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
4786 4787
        }

J
Jared Parsons 已提交
4788
        [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")]
P
Pilchie 已提交
4789 4790 4791 4792 4793 4794 4795
        public void AddModuleWithExtensionMethod()
        {
            string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path;
            string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path;
            var baseDir = Path.GetDirectoryName(source2);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4796
            int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
P
Pilchie 已提交
4797 4798 4799 4800
            Assert.Equal(0, exitCode);

            var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4801
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter);
P
Pilchie 已提交
4802
            Assert.Equal(0, exitCode);
4803 4804 4805

            CleanupAllGeneratedFiles(source1);
            CleanupAllGeneratedFiles(source2);
P
Pilchie 已提交
4806 4807
        }

J
Jared Parsons 已提交
4808
        [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")]
P
Pilchie 已提交
4809 4810 4811 4812 4813 4814 4815
        public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes()
        {
            string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path;
            string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path;
            var baseDir = Path.GetDirectoryName(source2);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4816
            int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
P
Pilchie 已提交
4817 4818 4819 4820
            Assert.Equal(0, exitCode);

            var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
4821
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter);
P
Pilchie 已提交
4822 4823
            Assert.Equal(1, exitCode);
            // Native gives CS0013 at emit stage
4824
            Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim());
4825

4826 4827
            CleanupAllGeneratedFiles(source1);
            CleanupAllGeneratedFiles(source2);
P
Pilchie 已提交
4828 4829 4830 4831 4832
        }

        [Fact]
        public void Utf8Output()
        {
J
Jared Parsons 已提交
4833
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4834 4835 4836
            parsedArgs.Errors.Verify();
            Assert.True((bool)parsedArgs.Utf8Output);

J
Jared Parsons 已提交
4837
            parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4838 4839 4840
            parsedArgs.Errors.Verify();
            Assert.True((bool)parsedArgs.Utf8Output);

J
Jared Parsons 已提交
4841
            parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4842 4843 4844
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:"));
        }

J
Jared Parsons 已提交
4845
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
4846
        public void CscUtf8Output_WithRedirecting_Off()
P
Pilchie 已提交
4847
        {
4848
            var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path;
P
Pilchie 已提交
4849 4850 4851

            var tempOut = Temp.CreateFile();

4852
            var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1);
P
Pilchie 已提交
4853
            Assert.Equal("", output.Trim());
4854
            Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS"));
4855 4856

            CleanupAllGeneratedFiles(srcFile);
4857
            CleanupAllGeneratedFiles(tempOut.Path);
P
Pilchie 已提交
4858 4859
        }

J
Jared Parsons 已提交
4860
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
4861
        public void CscUtf8Output_WithRedirecting_On()
P
Pilchie 已提交
4862
        {
4863
            var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path;
P
Pilchie 已提交
4864 4865 4866

            var tempOut = Temp.CreateFile();

4867
            var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1);
P
Pilchie 已提交
4868
            Assert.Equal("", output.Trim());
4869
            Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS"));
4870 4871 4872

            CleanupAllGeneratedFiles(srcFile);
            CleanupAllGeneratedFiles(tempOut.Path);
P
Pilchie 已提交
4873 4874
        }

J
Jared Parsons 已提交
4875
        [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
J
Jared Parsons 已提交
4876
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
P
Pilchie 已提交
4877 4878 4879 4880 4881 4882
        public void NoSourcesWithModule()
        {
            var folder = Temp.CreateDirectory();
            var aCs = folder.CreateFile("a.cs");
            aCs.WriteAllText("public class C {}");

4883
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:module /out:a.netmodule " + aCs, startFolder: folder.ToString());
P
Pilchie 已提交
4884 4885
            Assert.Equal("", output.Trim());

4886
            output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString());
P
Pilchie 已提交
4887 4888
            Assert.Equal("", output.Trim());

4889
            output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString());
P
Pilchie 已提交
4890
            Assert.Equal("warning CS2008: No source files specified.", output.Trim());
4891 4892

            CleanupAllGeneratedFiles(aCs.Path);
P
Pilchie 已提交
4893 4894
        }

J
Jared Parsons 已提交
4895
        [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
J
Jared Parsons 已提交
4896
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
P
Pilchie 已提交
4897 4898 4899 4900 4901 4902
        public void NoSourcesWithResource()
        {
            var folder = Temp.CreateDirectory();
            var aCs = folder.CreateFile("a.cs");
            aCs.WriteAllText("public class C {}");

4903
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString());
P
Pilchie 已提交
4904
            Assert.Equal("", output.Trim());
4905 4906

            CleanupAllGeneratedFiles(aCs.Path);
P
Pilchie 已提交
4907 4908
        }

J
Jared Parsons 已提交
4909
        [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
J
Jared Parsons 已提交
4910
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
P
Pilchie 已提交
4911 4912 4913 4914 4915 4916
        public void NoSourcesWithLinkResource()
        {
            var folder = Temp.CreateDirectory();
            var aCs = folder.CreateFile("a.cs");
            aCs.WriteAllText("public class C {}");

4917
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString());
P
Pilchie 已提交
4918
            Assert.Equal("", output.Trim());
4919 4920

            CleanupAllGeneratedFiles(aCs.Path);
P
Pilchie 已提交
4921 4922 4923 4924 4925 4926
        }

        [Fact]
        public void KeyContainerAndKeyFile()
        {
            // KEYCONTAINER
J
Jared Parsons 已提交
4927
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4928 4929 4930
            parsedArgs.Errors.Verify();
            Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer);

J
Jared Parsons 已提交
4931
            parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4932 4933 4934 4935 4936
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);

J
Jared Parsons 已提交
4937
            parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4938 4939 4940 4941 4942
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/keycontainer-'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);

J
Jared Parsons 已提交
4943
            parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4944 4945 4946 4947 4948
            parsedArgs.Errors.Verify(
                // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option
                Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);

J
Jared Parsons 已提交
4949
            parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4950 4951 4952 4953
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);

            // KEYFILE
J
Jared Parsons 已提交
4954
            parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4955 4956
            parsedArgs.Errors.Verify();
            //EDMAURER let's not set the option in the event that there was an error.
4957
            //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile);
P
Pilchie 已提交
4958

J
Jared Parsons 已提交
4959
            parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4960 4961 4962 4963 4964
            parsedArgs.Errors.Verify(
                // error CS2005: Missing file specification for 'keyfile' option
                Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);

J
Jared Parsons 已提交
4965
            parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4966 4967 4968
            parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);

J
Jared Parsons 已提交
4969
            parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4970 4971 4972 4973 4974 4975
            parsedArgs.Errors.Verify(
                // error CS2007: Unrecognized option: '/keyfile-'
                Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-"));
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);

            // DEFAULTS
J
Jared Parsons 已提交
4976
            parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4977 4978 4979 4980 4981
            parsedArgs.Errors.Verify();
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);
            Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);

            // KEYFILE | KEYCONTAINER conflicts
J
Jared Parsons 已提交
4982
            parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4983 4984 4985 4986
            parsedArgs.Errors.Verify();
            Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile);
            Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer);

J
Jared Parsons 已提交
4987
            parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory);
P
Pilchie 已提交
4988 4989 4990 4991 4992
            parsedArgs.Errors.Verify();
            Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile);
            Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer);
        }

J
Jared Parsons 已提交
4993
        [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")]
P
Pilchie 已提交
4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018
        public void CS1698WRN_AssumedMatchThis()
        {
            // compile with: /target:library /keyfile:mykey.snk
            var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")]
public class CS1698_a {}
";
            // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk
            var text2 = @"public class CS1698_b : CS1698_a {}
";
            //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk
            var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")]
public class CS1698_c : CS1698_b {}
public class CS1698_a {}
";

            var folder = Temp.CreateDirectory();
            var cs1698a = folder.CreateFile("CS1698a.cs");
            cs1698a.WriteAllText(text1);

            var cs1698b = folder.CreateFile("CS1698b.cs");
            cs1698b.WriteAllText(text2);

            var cs1698 = folder.CreateFile("CS1698.cs");
            cs1698.WriteAllText(text);

5019
            var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey);
P
Pilchie 已提交
5020 5021
            var kfile = "/keyfile:" + snkFile.Path;

J
Jared Parsons 已提交
5022
            CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory);
P
Pilchie 已提交
5023 5024
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
5025
            parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory);
P
Pilchie 已提交
5026 5027
            parsedArgs.Errors.Verify();

J
Jared Parsons 已提交
5028
            parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory);
P
Pilchie 已提交
5029 5030 5031 5032

            // Roslyn no longer generates a warning for this...since this was only a warning, we're not really
            // saving anyone...does not provide high value to implement...

5033
            // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10'
P
Pilchie 已提交
5034 5035 5036
            // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'.
            // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match.
            parsedArgs.Errors.Verify();
5037 5038 5039 5040 5041

            CleanupAllGeneratedFiles(snkFile.Path);
            CleanupAllGeneratedFiles(cs1698a.Path);
            CleanupAllGeneratedFiles(cs1698b.Path);
            CleanupAllGeneratedFiles(cs1698.Path);
P
Pilchie 已提交
5042 5043
        }

T
Tomas Matousek 已提交
5044
        [ConditionalFact(typeof(ClrOnly), Reason="https://github.com/dotnet/roslyn/issues/30926")]
P
Pilchie 已提交
5045 5046
        public void BinaryFileErrorTest()
        {
5047
            var binaryPath = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.mscorlib).Path;
J
Jared Parsons 已提交
5048
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath });
P
Pilchie 已提交
5049 5050 5051 5052 5053 5054
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Equal(
                "error CS2015: '" + binaryPath + "' is a binary file instead of a text file",
                outWriter.ToString().Trim());
5055 5056

            CleanupAllGeneratedFiles(binaryPath);
P
Pilchie 已提交
5057 5058
        }

J
Jared Parsons 已提交
5059
#if !NETCOREAPP2_1
J
Jared Parsons 已提交
5060
        [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")]
5061
        [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")]
5062
        [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))]
P
Pilchie 已提交
5063 5064
        public void Bug15538()
        {
5065
            // Several Jenkins VMs are still running with local systems permissions.  This suite won't run properly
5066
            // in that environment.  Removing this check is being tracked by issue #79.
5067 5068 5069 5070 5071 5072
            using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent())
            {
                if (identity.IsSystem)
                {
                    return;
                }
J
Jared Parsons 已提交
5073 5074 5075 5076 5077 5078 5079 5080

                // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in 
                // the username. 
                // https://github.com/dotnet/roslyn/issues/28836
                if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP"))
                {
                    return;
                }
5081 5082
            }

P
Pilchie 已提交
5083 5084 5085 5086 5087
            var folder = Temp.CreateDirectory();
            var source = folder.CreateFile("src.vb").WriteAllText("").Path;
            var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path;
            try
            {
5088
                var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q");
P
Pilchie 已提交
5089 5090
                Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());

5091
                output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q");
P
Pilchie 已提交
5092 5093
                Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());

5094
                output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1);
P
Pilchie 已提交
5095 5096 5097 5098
                Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim());
            }
            finally
            {
5099
                var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q");
P
Pilchie 已提交
5100 5101 5102
                Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());
                File.Delete(_ref);
            }
5103 5104

            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
5105
        }
J
Jared Parsons 已提交
5106
#endif
P
Pilchie 已提交
5107

J
Jared Parsons 已提交
5108
        [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")]
P
Pilchie 已提交
5109 5110 5111 5112 5113
        [Fact]
        public void ResponseFilesWithEmptyAliasReference()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
// <Area> ExternAlias - command line alias</Area>
5114
// <Title>
P
Pilchie 已提交
5115 5116 5117 5118
// negative test cases: empty file name ("""")
// </Title>
// <Description>
// </Description>
5119
// <RelatedBugs></RelatedBugs>
P
Pilchie 已提交
5120 5121 5122

//<Expects Status=error>CS1680:.*myAlias=</Expects>

5123
// <Code>
P
Pilchie 已提交
5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139
class myClass
{
    static int Main()
    {
        return 1;
    }
}
// </Code>
").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/nologo
/r:myAlias=""""
").Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
5140
            // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
J
Jared Parsons 已提交
5141
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
5142 5143 5144
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim());
5145 5146 5147

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
5148 5149
        }

J
Jared Parsons 已提交
5150
        [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")]
P
Pilchie 已提交
5151 5152 5153 5154 5155
        [Fact]
        public void ResponseFilesWithEmptyAliasReference2()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
// <Area> ExternAlias - command line alias</Area>
5156
// <Title>
P
Pilchie 已提交
5157 5158 5159 5160
// negative test cases: empty file name ("""")
// </Title>
// <Description>
// </Description>
5161
// <RelatedBugs></RelatedBugs>
P
Pilchie 已提交
5162 5163 5164

//<Expects Status=error>CS1680:.*myAlias=</Expects>

5165
// <Code>
P
Pilchie 已提交
5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181
class myClass
{
    static int Main()
    {
        return 1;
    }
}
// </Code>
").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/nologo
/r:myAlias=""  ""
").Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
5182
            // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
J
Jared Parsons 已提交
5183
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
5184 5185 5186
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim());
5187 5188 5189

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
5190
        }
5191 5192

        [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")]
P
Pilchie 已提交
5193
        [Fact]
5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205
        public void QuotedDefineInRespFile()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
#if NN
class myClass
{
#endif
    static int Main()
#if DD
    {
        return 1;
#endif
5206

5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223
#if AA
    }
#endif

#if BB
}
#endif

").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/d:""DD""
/d:""AA;BB""
/d:""N""N
").Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
5224
            // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
J
Jared Parsons 已提交
5225
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
        }

        [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")]
        [Fact]
        public void QuotedDefineInRespFileErr()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
#if NN
class myClass
{
#endif
    static int Main()
#if DD
    {
        return 1;
#endif

#if AA
    }
#endif

#if BB
}
#endif

").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/d:""DD""""
/d:""AA;BB""
/d:""N"" ""N
").Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
5265
            // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
J
Jared Parsons 已提交
5266
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
5267 5268 5269 5270 5271 5272 5273 5274
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
        }

        [Fact]
5275
        public void ResponseFileSplitting()
P
Pilchie 已提交
5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311
        {
            string[] responseFile;

            responseFile = new string[] {
                @"a.cs b.cs ""c.cs e.cs""",
                @"hello world # this is a comment"
            };

            IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile);
            AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args);

            // Check comment handling; comment character only counts at beginning of argument
            responseFile = new string[] {
                @"   # ignore this",
                @"   # ignore that ""hello""",
                @"  a.cs #3.cs",
                @"  b#.cs c#d.cs #e.cs",
                @"  ""#f.cs""",
                @"  ""#g.cs #h.cs"""
            };

            args = CSharpCommandLineParser.ParseResponseLines(responseFile);
            AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args);

            // Check backslash escaping
            responseFile = new string[] {
                @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\",
            };
            args = CSharpCommandLineParser.ParseResponseLines(responseFile);
            AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args);

            // More backslash escaping and quoting
            responseFile = new string[] {
                @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""",
            };
            args = CSharpCommandLineParser.ParseResponseLines(responseFile);
5312
            AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args);
P
Pilchie 已提交
5313

5314
            // Quoting inside argument is valid.
P
Pilchie 已提交
5315
            responseFile = new string[] {
5316
                @"  /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing",
P
Pilchie 已提交
5317 5318
            };
            args = CSharpCommandLineParser.ParseResponseLines(responseFile);
5319
            AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args);
P
Pilchie 已提交
5320
        }
5321

J
jaredpar 已提交
5322
        [ConditionalFact(typeof(WindowsOnly))]
5323
        private void SourceFileQuoting()
P
Pilchie 已提交
5324 5325 5326 5327 5328
        {
            string[] responseFile = new string[] {
                @"d:\\""abc def""\baz.cs ab""c d""e.cs",
            };

5329
            CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
P
Pilchie 已提交
5330 5331 5332
            AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path));
        }

J
Jared Parsons 已提交
5333
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
        [Fact]
        public void OutputFileName1()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from first input (file, not class) name, since DLL.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:library" },
                expectedOutputName: "p.dll");
        }

J
Jared Parsons 已提交
5356
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378
        [Fact]
        public void OutputFileName2()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from command-line option.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:library", "/out:r.dll" },
                expectedOutputName: "r.dll");
        }

J
Jared Parsons 已提交
5379
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401
        [Fact]
        public void OutputFileName3()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from name of file containing entrypoint, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe" },
                expectedOutputName: "q.exe");
        }

J
Jared Parsons 已提交
5402
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424
        [Fact]
        public void OutputFileName4()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from command-line option.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe", "/out:r.exe" },
                expectedOutputName: "r.exe");
        }

J
Jared Parsons 已提交
5425
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448
        [Fact]
        public void OutputFileName5()
        {
            string source1 = @"
class A
{
    static void Main() { }
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from name of file containing entrypoint - affected by /main, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe", "/main:A" },
                expectedOutputName: "p.exe");
        }

J
Jared Parsons 已提交
5449
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472
        [Fact]
        public void OutputFileName6()
        {
            string source1 = @"
class A
{
    static void Main() { }
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from name of file containing entrypoint - affected by /main, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe", "/main:B" },
                expectedOutputName: "q.exe");
        }

J
Jared Parsons 已提交
5473
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496
        [Fact]
        public void OutputFileName7()
        {
            string source1 = @"
partial class A
{
    static partial void Main() { }
}
";
            string source2 = @"
partial class A
{
    static partial void Main();
}
";
            // Name comes from name of file containing entrypoint, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe" },
                expectedOutputName: "p.exe");
        }

J
Jared Parsons 已提交
5497
        [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
P
Pilchie 已提交
5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600
        [Fact]
        public void OutputFileName8()
        {
            string source1 = @"
partial class A
{
    static partial void Main();
}
";
            string source2 = @"
partial class A
{
    static partial void Main() { }
}
";
            // Name comes from name of file containing entrypoint, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe" },
                expectedOutputName: "q.exe");
        }

        [Fact]
        public void OutputFileName9()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from first input (file, not class) name, since winmdobj.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:winmdobj" },
                expectedOutputName: "p.winmdobj");
        }

        [Fact]
        public void OutputFileName10()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from name of file containing entrypoint, since appcontainerexe.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:appcontainerexe" },
                expectedOutputName: "q.exe");
        }

        [Fact]
        public void OutputFileName_Switch()
        {
            string source1 = @"
class A
{
}
";
            string source2 = @"
class B
{
    static void Main() { }
}
";
            // Name comes from name of file containing entrypoint, since EXE.
            CheckOutputFileName(
                source1, source2,
                inputName1: "p.cs", inputName2: "q.cs",
                commandLineArguments: new[] { "/target:exe", "/out:r.exe" },
                expectedOutputName: "r.exe");
        }

        [Fact]
        public void OutputFileName_NoEntryPoint()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5601
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" });
P
Pilchie 已提交
5602 5603 5604
            int exitCode = csc.Run(outWriter);
            Assert.NotEqual(0, exitCode);
            Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim());
5605

5606
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5607 5608
        }

J
Jared Parsons 已提交
5609
        [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")]
5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622
        public void VerifyDiagnosticSeverityNotLocalized()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5623
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" });
5624 5625 5626 5627 5628 5629
            int exitCode = csc.Run(outWriter);
            Assert.NotEqual(0, exitCode);

            // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:"
            Assert.Contains("error CS5001:", outWriter.ToString().Trim());

5630
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646
        }

        [Fact]
        public void NoLogo_1()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5647
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" });
P
Pilchie 已提交
5648 5649 5650 5651
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal(@"",
                outWriter.ToString().Trim());
5652

5653
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669
        }

        [Fact]
        public void NoLogo_2()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5670
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" });
P
Pilchie 已提交
5671 5672
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
5673 5674 5675

            var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(\\.\\d+)?", "version A.B.C.D");
            patched = ReplaceCommitHash(patched);
P
Pilchie 已提交
5676
            Assert.Equal(@"
5677
Microsoft (R) Visual C# Compiler version A.B.C.D (HASH)
P
Pilchie 已提交
5678
Copyright (C) Microsoft Corporation. All rights reserved.".Trim(),
5679
                patched);
P
Pilchie 已提交
5680 5681
            // Privately queued builds have 3-part version numbers instead of 4.  Since we're throwing away the version number,
            // making the last part optional will fix this.
5682 5683

            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5684 5685
        }

5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718
        [Theory,
            InlineData("Microsoft (R) Visual C# Compiler version A.B.C.D (<developer build>)",
                "Microsoft (R) Visual C# Compiler version A.B.C.D (HASH)"),
            InlineData("Microsoft (R) Visual C# Compiler version A.B.C.D (ABCDEF01)",
                "Microsoft (R) Visual C# Compiler version A.B.C.D (HASH)"),
            InlineData("Microsoft (R) Visual C# Compiler version A.B.C.D (abcdef90)",
                "Microsoft (R) Visual C# Compiler version A.B.C.D (HASH)"),
            InlineData("Microsoft (R) Visual C# Compiler version A.B.C.D (12345678)",
                "Microsoft (R) Visual C# Compiler version A.B.C.D (HASH)")]
        public void TestReplaceCommitHash(string orig, string expected)
        {
            Assert.Equal(expected, ReplaceCommitHash(orig));
        }

        private static string ReplaceCommitHash(string s)
        {
            // open paren, followed by either <developer build> or 8 hex, followed by close paren
            return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)");
        }

        [Fact]
        public void ExtractShortCommitHash()
        {
            Assert.Null(CommonCompiler.ExtractShortCommitHash(null));
            Assert.Equal("", CommonCompiler.ExtractShortCommitHash(""));
            Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<"));
            Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>"));
            Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1"));
            Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567"));
            Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678"));
            Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789"));
        }

P
Pilchie 已提交
5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729
        private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName)
        {
            var dir = Temp.CreateDirectory();

            var file1 = dir.CreateFile(inputName1);
            file1.WriteAllText(source1);

            var file2 = dir.CreateFile(inputName2);
            file2.WriteAllText(source2);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5730
            var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray());
P
Pilchie 已提交
5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749
            int exitCode = csc.Run(outWriter);
            if (exitCode != 0)
            {
                Console.WriteLine(outWriter.ToString());
                Assert.Equal(0, exitCode);
            }

            Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count());
            Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count());

            using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName))))
            {
                var peReader = metadata.Module.GetMetadataReader();

                Assert.True(peReader.IsAssembly);

                Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name));
                Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name));
            }
5750

5751
            if (System.IO.File.Exists(expectedOutputName))
5752
            {
5753
                System.IO.File.Delete(expectedOutputName);
5754
            }
5755 5756 5757

            CleanupAllGeneratedFiles(file1.Path);
            CleanupAllGeneratedFiles(file2.Path);
P
Pilchie 已提交
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773
        }

        [Fact]
        public void MissingReference()
        {
            string source = @"
class C
{
}
";
            var dir = Temp.CreateDirectory();

            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5774
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" });
P
Pilchie 已提交
5775 5776 5777
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim());
5778

5779
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5780 5781
        }

J
Jared Parsons 已提交
5782
        [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")]
J
jaredpar 已提交
5783
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803
        public void CompilationWithWarnAsError_01()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            // Baseline without warning options (expect success)
            int exitCode = GetExitCode(source, "a.cs", new String[] { });
            Assert.Equal(0, exitCode);

            // The case with /warnaserror (expect to be success, since there will be no warning)
            exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" });
            Assert.Equal(0, exitCode);

            // The case with /warnaserror and /nowarn:1 (expect success)
            // Note that even though the command line option has a warning, it is not going to become an error
5804
            // in order to avoid the halt of compilation.
P
Pilchie 已提交
5805 5806 5807 5808
            exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" });
            Assert.Equal(0, exitCode);
        }

J
Jared Parsons 已提交
5809
        [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")]
J
jaredpar 已提交
5810
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849
        public void CompilationWithWarnAsError_02()
        {
            string source = @"
public class C
{
    public static void Main()
    {
        int x; // CS0168
    }
}";

            // Baseline without warning options (expect success)
            int exitCode = GetExitCode(source, "a.cs", new String[] { });
            Assert.Equal(0, exitCode);

            // The case with /warnaserror (expect failure)
            exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" });
            Assert.NotEqual(0, exitCode);

            // The case with /warnaserror:168 (expect failure)
            exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" });
            Assert.NotEqual(0, exitCode);

            // The case with /warnaserror:219 (expect success)
            exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" });
            Assert.Equal(0, exitCode);

            // The case with /warnaserror and /nowarn:168 (expect success)
            exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" });
            Assert.Equal(0, exitCode);
        }

        private int GetExitCode(string source, string fileName, string[] commandLineArguments)
        {
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5850
            var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray());
P
Pilchie 已提交
5851 5852 5853 5854 5855
            int exitCode = csc.Run(outWriter);

            return exitCode;
        }

J
Jared Parsons 已提交
5856
        [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
J
jaredpar 已提交
5857
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872
        public void CompilationWithNonExistingOutPath()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5873
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" });
P
Pilchie 已提交
5874 5875 5876
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
5877
            Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal);
5878

5879
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5880 5881
        }

J
Jared Parsons 已提交
5882
        [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
P
Pilchie 已提交
5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898
        [Fact]
        public void CompilationWithWrongOutPath_01()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5899
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" });
P
Pilchie 已提交
5900 5901 5902 5903
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            var message = outWriter.ToString();
5904 5905
            Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal);
            Assert.Contains("sub", message, StringComparison.Ordinal);
5906

5907
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5908 5909
        }

J
Jared Parsons 已提交
5910
        [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
P
Pilchie 已提交
5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926
        [Fact]
        public void CompilationWithWrongOutPath_02()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5927
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " });
P
Pilchie 已提交
5928 5929 5930 5931
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            var message = outWriter.ToString();
5932 5933
            Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal);
            Assert.Contains("sub", message, StringComparison.Ordinal);
5934

5935
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5936 5937
        }

J
Jared Parsons 已提交
5938
        [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
J
Jared Parsons 已提交
5939
        [ConditionalFact(typeof(WindowsDesktopOnly))]
P
Pilchie 已提交
5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
        public void CompilationWithWrongOutPath_03()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5955
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" });
P
Pilchie 已提交
5956 5957 5958
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
5959
            Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal);
5960

5961
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5962 5963
        }

J
Jared Parsons 已提交
5964
        [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
P
Pilchie 已提交
5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980
        [Fact]
        public void CompilationWithWrongOutPath_04()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
5981
            var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " });
P
Pilchie 已提交
5982 5983 5984
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
5985
            Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal);
5986

5987
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
5988 5989 5990 5991 5992
        }

        [Fact]
        public void EmittedSubsystemVersion()
        {
5993 5994
            var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
            var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1))));
P
Pilchie 已提交
5995 5996 5997 5998
            Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion);
            Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion);
        }

J
Jared Parsons 已提交
5999
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30152")]
6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014
        public void CreateCompilationWithKeyFile()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);

J
Jared Parsons 已提交
6015
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", });
6016 6017
            var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);

A
Andy Gocke 已提交
6018
            Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider);
6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036
        }

        [Fact]
        public void CreateCompilationWithKeyContainer()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);

J
Jared Parsons 已提交
6037
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", });
6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
            var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);

            Assert.Equal(comp.Options.StrongNameProvider.GetType(), typeof(DesktopStrongNameProvider));
        }

        [Fact]
        public void CreateCompilationFallbackCommand()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);

J
Jared Parsons 已提交
6059
            var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" });
6060 6061 6062 6063 6064
            var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);

            Assert.Equal(comp.Options.StrongNameProvider.GetType(), typeof(DesktopStrongNameProvider));
        }

P
Pilchie 已提交
6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080
        [Fact]
        public void CreateCompilation_MainAndTargetIncompatibilities()
        {
            string source = @"
public class C
{
    public static void Main()
    {
    }
}";

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllText(source);

6081
            var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll);
P
Pilchie 已提交
6082 6083 6084 6085 6086 6087 6088 6089

            var options = compilation.Options;

            Assert.Equal(0, options.Errors.Length);

            options = options.WithMainTypeName("a");

            options.Errors.Verify(
S
srivatsn 已提交
6090
    // error CS2017: Cannot specify /main if building a module or library
P
Pilchie 已提交
6091 6092 6093 6094 6095 6096
    Diagnostic(ErrorCode.ERR_NoMainOnDLL)
                );

            var comp = CSharpCompilation.Create("a.dll", options: options);

            comp.GetDiagnostics().Verify(
S
srivatsn 已提交
6097
    // error CS2017: Cannot specify /main if building a module or library
P
Pilchie 已提交
6098 6099 6100 6101 6102 6103 6104 6105
    Diagnostic(ErrorCode.ERR_NoMainOnDLL)
                );

            options = options.WithOutputKind(OutputKind.WindowsApplication);
            options.Errors.Verify();

            comp = CSharpCompilation.Create("a.dll", options: options);
            comp.GetDiagnostics().Verify(
S
srivatsn 已提交
6106
    // error CS1555: Could not find 'a' specified for Main method
P
Pilchie 已提交
6107 6108 6109 6110 6111
    Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a")
                );

            options = options.WithOutputKind(OutputKind.NetModule);
            options.Errors.Verify(
S
srivatsn 已提交
6112
    // error CS2017: Cannot specify /main if building a module or library
P
Pilchie 已提交
6113 6114 6115 6116 6117
    Diagnostic(ErrorCode.ERR_NoMainOnDLL)
                );

            comp = CSharpCompilation.Create("a.dll", options: options);
            comp.GetDiagnostics().Verify(
S
srivatsn 已提交
6118
    // error CS2017: Cannot specify /main if building a module or library
P
Pilchie 已提交
6119 6120 6121 6122 6123 6124 6125 6126
    Diagnostic(ErrorCode.ERR_NoMainOnDLL)
                );

            options = options.WithMainTypeName(null);
            options.Errors.Verify();

            comp = CSharpCompilation.Create("a.dll", options: options);
            comp.GetDiagnostics().Verify();
6127

6128
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
6129 6130
        }

J
Jared Parsons 已提交
6131
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")]
P
Pilchie 已提交
6132 6133
        public void SpecifyProperCodePage()
        {
6134
            byte[] source = {
P
Pilchie 已提交
6135 6136 6137 6138 6139
                                0x63, // c
                                0x6c, // l
                                0x61, // a
                                0x73, // s
                                0x73, // s
6140 6141
                                0x20, //
                                0xd0, 0x96, // Utf-8 Cyrillic character
P
Pilchie 已提交
6142 6143 6144 6145 6146 6147 6148 6149 6150
                                0x7b, // {
                                0x7d, // }
                            };

            var fileName = "a.cs";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(fileName);
            file.WriteAllBytes(source);

6151
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library " + file, startFolder: dir.Path);
P
Pilchie 已提交
6152 6153
            Assert.Equal("", output); // Autodetected UTF8, NO ERROR

6154
            output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:library /codepage:20127 " + file, expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII
P
Pilchie 已提交
6155 6156 6157 6158 6159 6160 6161 6162
            // 0xd0, 0x96 ==> ERROR
            Assert.Equal(@"
a.cs(1,7): error CS1001: Identifier expected
a.cs(1,7): error CS1514: { expected
a.cs(1,7): error CS1513: } expected
a.cs(1,7): error CS1022: Type or namespace definition, or end-of-file expected
a.cs(1,10): error CS1022: Type or namespace definition, or end-of-file expected".Trim(),
                Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim());
6163

6164
            CleanupAllGeneratedFiles(file.Path);
P
Pilchie 已提交
6165 6166
        }

J
jaredpar 已提交
6167
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178
        public void DefaultWin32ResForExe()
        {
            var source = @"
class C
{
    static void Main() { }
}
";

            CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
6179
<ManifestResource Size=""490"">
P
Pilchie 已提交
6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194
  <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>

<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
        }

J
jaredpar 已提交
6195
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206
        public void DefaultManifestForDll()
        {
            var source = @"
class C
{
}
";

            CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null);
        }

J
jaredpar 已提交
6207
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218
        public void DefaultManifestForWinExe()
        {
            var source = @"
class C
{
    static void Main() { }
}
";

            CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
6219
<ManifestResource Size=""490"">
P
Pilchie 已提交
6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234
  <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>

<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
        }

J
jaredpar 已提交
6235
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246
        public void DefaultManifestForAppContainerExe()
        {
            var source = @"
class C
{
    static void Main() { }
}
";

            CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
6247
<ManifestResource Size=""490"">
P
Pilchie 已提交
6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262
  <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>

<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
        }

J
jaredpar 已提交
6263
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274
        public void DefaultManifestForWinMD()
        {
            var source = @"
class C
{
}
";

            CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null);
        }

J
jaredpar 已提交
6275
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286
        public void DefaultWin32ResForModule()
        {
            var source = @"
class C
{
}
";

            CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null);
        }

J
jaredpar 已提交
6287
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323
        public void ExplicitWin32ResForExe()
        {
            var source = @"
class C
{
    static void Main() { }
}
";

            var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>";

            var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest));

            var expectedManifest =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""476"">
  <Contents><![CDATA[" +
explicitManifest +
@"]]></Contents>
</ManifestResource>";

            CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest);
        }

        // DLLs don't get the default manifest, but they do respect explicitly set manifests.
J
jaredpar 已提交
6324
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359
        public void ExplicitWin32ResForDll()
        {
            var source = @"
class C
{
    static void Main() { }
}
";

            var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>";


            var expectedManifest =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""476"">
  <Contents><![CDATA[" +
explicitManifest +
@"]]></Contents>
</ManifestResource>";

            CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest);
        }

        // Modules don't have manifests, even if one is explicitly specified.
J
jaredpar 已提交
6360
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385
        public void ExplicitWin32ResForModule()
        {
            var source = @"
class C
{
}
";

            var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>";

            CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null);
        }

        [DllImport("kernel32.dll", SetLastError = true)]
6386
        private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
P
Pilchie 已提交
6387
        [DllImport("kernel32.dll", SetLastError = true)]
6388
        private static extern bool FreeLibrary([In] IntPtr hFile);
P
Pilchie 已提交
6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429

        private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest)
        {
            var dir = Temp.CreateDirectory();
            var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source);

            string outputFileName;
            string target;
            switch (outputKind)
            {
                case OutputKind.ConsoleApplication:
                    outputFileName = "Test.exe";
                    target = "exe";
                    break;
                case OutputKind.WindowsApplication:
                    outputFileName = "Test.exe";
                    target = "winexe";
                    break;
                case OutputKind.DynamicallyLinkedLibrary:
                    outputFileName = "Test.dll";
                    target = "library";
                    break;
                case OutputKind.NetModule:
                    outputFileName = "Test.netmodule";
                    target = "module";
                    break;
                case OutputKind.WindowsRuntimeMetadata:
                    outputFileName = "Test.winmdobj";
                    target = "winmdobj";
                    break;
                case OutputKind.WindowsRuntimeApplication:
                    outputFileName = "Test.exe";
                    target = "appcontainerexe";
                    break;
                default:
                    throw TestExceptionUtilities.UnexpectedValue(outputKind);
            }

            MockCSharpCompiler csc;
            if (explicitManifest == null)
            {
J
Jared Parsons 已提交
6430
                csc = CreateCSharpCompiler(null, dir.Path, new[]
P
Pilchie 已提交
6431 6432 6433 6434 6435 6436 6437 6438 6439
                {
                    string.Format("/target:{0}", target),
                    string.Format("/out:{0}", outputFileName),
                    Path.GetFileName(sourceFile.Path),
                });
            }
            else
            {
                var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest);
J
Jared Parsons 已提交
6440
                csc = CreateCSharpCompiler(null, dir.Path, new[]
P
Pilchie 已提交
6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454
                {
                    string.Format("/target:{0}", target),
                    string.Format("/out:{0}", outputFileName),
                    string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)),
                    Path.GetFileName(sourceFile.Path),
                });
            }

            int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture));

            Assert.Equal(0, actualExitCode);

            //Open as data
            IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002);
J
Jared Parsons 已提交
6455
            if (lib == IntPtr.Zero)
P
Pilchie 已提交
6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475
                throw new Win32Exception(Marshal.GetLastWin32Error());

            const string resourceType = "#24";
            var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1";

            uint manifestSize;
            if (expectedManifest == null)
            {
                Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize));
            }
            else
            {
                IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize);
                string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize);
                Assert.Equal(expectedManifest, actualManifest);
            }

            FreeLibrary(lib);
        }

J
Jared Parsons 已提交
6476
        [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
J
Jared Parsons 已提交
6477
        [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493
        public void ResponseFilesWithNoconfig_01()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
    public static void Main()
    {
        int x; // CS0168
    }
}").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/warnaserror
").Path;
            // Checks the base case without /noconfig (expect to see error)
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6494
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
6495 6496
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);
6497
            Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6498 6499 6500

            // Checks the case with /noconfig (expect to see warning, instead of error)
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6501
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" });
P
Pilchie 已提交
6502 6503
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6504
            Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6505 6506 6507

            // Checks the case with /NOCONFIG (expect to see warning, instead of error)
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6508
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" });
P
Pilchie 已提交
6509 6510
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6511
            Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6512 6513 6514

            // Checks the case with -noconfig (expect to see warning, instead of error)
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6515
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" });
P
Pilchie 已提交
6516 6517
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6518
            Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
6519 6520 6521

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
6522 6523
        }

J
Jared Parsons 已提交
6524
        [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
J
jaredpar 已提交
6525
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540
        public void ResponseFilesWithNoconfig_02()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
    public static void Main()
    {
    }
}").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/noconfig
").Path;
            // Checks the case with /noconfig inside the response file (expect to see warning)
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6541
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
6542 6543
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6544
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6545 6546 6547 6548

            // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning)
            // to verify that this warning is not suppressed by the /nowarn option (See MSDN).
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6549
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
P
Pilchie 已提交
6550 6551
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6552
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
6553 6554 6555

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
6556 6557
        }

J
Jared Parsons 已提交
6558
        [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
J
Jared Parsons 已提交
6559
        [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574
        public void ResponseFilesWithNoconfig_03()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
    public static void Main()
    {
    }
}").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
/NOCONFIG
").Path;
            // Checks the case with /noconfig inside the response file (expect to see warning)
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6575
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
6576 6577
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6578
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6579 6580 6581 6582

            // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning)
            // to verify that this warning is not suppressed by the /nowarn option (See MSDN).
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6583
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
P
Pilchie 已提交
6584 6585
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6586
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
6587

6588 6589
            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
6590 6591
        }

J
Jared Parsons 已提交
6592
        [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
J
jaredpar 已提交
6593
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608
        public void ResponseFilesWithNoconfig_04()
        {
            string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
    public static void Main()
    {
    }
}").Path;

            string rsp = Temp.CreateFile().WriteAllText(@"
-noconfig
").Path;
            // Checks the case with /noconfig inside the response file (expect to see warning)
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6609
            var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
6610 6611
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6612
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
6613 6614 6615 6616

            // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning)
            // to verify that this warning is not suppressed by the /nowarn option (See MSDN).
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6617
            csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
P
Pilchie 已提交
6618 6619
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
6620
            Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
6621 6622 6623

            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(rsp);
P
Pilchie 已提交
6624 6625
        }

J
Jared Parsons 已提交
6626
        [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")]
P
Pilchie 已提交
6627 6628 6629 6630 6631 6632 6633
        public void NoStdLib()
        {
            var src = Temp.CreateFile("a.cs");

            src.WriteAllText("public class C{}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6634
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6635 6636 6637 6638
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6639
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6640 6641 6642 6643 6644 6645 6646
            Assert.Equal(1, exitCode);
            Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported",
                         outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim());

            // Bug#15021: breaking change - empty source no error with /nostdlib
            src.WriteAllText("namespace System { }");
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
6647
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6648 6649
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
6650

6651
            CleanupAllGeneratedFiles(src.Path);
P
Pilchie 已提交
6652 6653 6654 6655
        }

        private string GetDefaultResponseFilePath()
        {
J
Jared Parsons 已提交
6656 6657
            var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp");
            return Temp.CreateFile().WriteAllBytes(cscRsp).Path;
P
Pilchie 已提交
6658 6659
        }

J
Jared Parsons 已提交
6660
        [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")]
P
Pilchie 已提交
6661 6662
        public void NoStdLib02()
        {
C
CyrusNajmabadi 已提交
6663
            #region "source"
P
Pilchie 已提交
6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708
            var source = @"
// <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title>
using System.Collections;

class O<T> where T : new()
{
    public T list = new T();
}

class C
{
    static StructCollection sc = new StructCollection { 1 };
    public static int Main()
    {
        ClassCollection cc = new ClassCollection { 2 };
        var o1 = new O<ClassCollection> { list = { 5 } };
        var o2 = new O<StructCollection> { list = sc };
        return 0;
    }
}

struct StructCollection : IEnumerable
{
    public int added;
    #region IEnumerable Members
    public void Add(int t)
    {
        added = t;
    }
    #endregion
}

class ClassCollection : IEnumerable
{
    public int added;
    #region IEnumerable Members
    public void Add(int t)
    {
        added = t;
    }
    #endregion
}

namespace System.Collections
{
6709
    public interface IEnumerable
P
Pilchie 已提交
6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781
    {
        void Add(int t);
    }
}
";
            #endregion

            #region "mslib"
            var mslib = @"
namespace System
{
    public class Object {}
    public struct Byte { }
    public struct Int16 { }
    public struct Int32 { }
    public struct Int64 { }
    public struct Single { }
    public struct Double { }
    public struct SByte { }
    public struct UInt32 { }
    public struct UInt64 { }
    public struct Char { }
    public struct Boolean { }
    public struct UInt16 { }
    public struct UIntPtr { }
    public struct IntPtr { }
    public class Delegate { }
    public class String {
        public int Length    {    get { return 10; }    }
    }
    public class MulticastDelegate { }
    public class Array { }
    public class Exception { public Exception(string s){} }
    public class Type { }
    public class ValueType { }
    public class Enum { }
    public interface IEnumerable { }
    public interface IDisposable { }
    public class Attribute { }
    public class ParamArrayAttribute { }
    public struct Void { }
    public struct RuntimeFieldHandle { }
    public struct RuntimeTypeHandle { }
    public class Activator
    {
         public static T CreateInstance<T>(){return default(T);}
    }

    namespace Collections
    {
        public interface IEnumerator { }
    }

    namespace Runtime
    {
        namespace InteropServices
        {
            public class OutAttribute { }
        }

        namespace CompilerServices
        {
            public class RuntimeHelpers { }
        }
    }

    namespace Reflection
    {
        public class DefaultMemberAttribute { }
    }
}
";
C
CyrusNajmabadi 已提交
6782
            #endregion
P
Pilchie 已提交
6783 6784 6785 6786 6787

            var src = Temp.CreateFile("NoStdLib02.cs");
            src.WriteAllText(source + mslib);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
6788
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6789 6790 6791 6792
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
6793
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6794 6795
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
6796
            string OriginalSource = src.Path;
P
Pilchie 已提交
6797 6798 6799 6800

            src = Temp.CreateFile("NoStdLib02b.cs");
            src.WriteAllText(mslib);
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
6801
            exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
P
Pilchie 已提交
6802 6803
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
6804 6805 6806

            CleanupAllGeneratedFiles(OriginalSource);
            CleanupAllGeneratedFiles(src.Path);
P
Pilchie 已提交
6807 6808
        }

J
Jared Parsons 已提交
6809
        [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")]
P
Pilchie 已提交
6810 6811 6812 6813 6814 6815 6816
        public void InvalidDefineSwitch()
        {
            var src = Temp.CreateFile("a.cs");

            src.WriteAllText("public class C{}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6817
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter);
P
Pilchie 已提交
6818 6819 6820 6821
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6822
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter);
P
Pilchie 已提交
6823
            Assert.Equal(0, exitCode);
O
Omar Tawfik 已提交
6824
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
P
Pilchie 已提交
6825 6826

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6827
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter);
P
Pilchie 已提交
6828 6829 6830 6831
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6832
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter);
P
Pilchie 已提交
6833 6834 6835 6836
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6837
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter);
P
Pilchie 已提交
6838
            Assert.Equal(0, exitCode);
O
Omar Tawfik 已提交
6839
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
P
Pilchie 已提交
6840 6841

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6842
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter);
P
Pilchie 已提交
6843
            Assert.Equal(0, exitCode);
O
Omar Tawfik 已提交
6844
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
P
Pilchie 已提交
6845 6846

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6847
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter);
P
Pilchie 已提交
6848
            Assert.Equal(0, exitCode);
6849 6850 6851
            var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]);
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]);
P
Pilchie 已提交
6852 6853

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6854
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter);
P
Pilchie 已提交
6855
            Assert.Equal(0, exitCode);
O
Omar Tawfik 已提交
6856
            Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim());
P
Pilchie 已提交
6857 6858 6859

            //Bug 531612 - Native would normally not give the 2nd warning
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
6860
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter);
P
Pilchie 已提交
6861
            Assert.Equal(0, exitCode);
6862 6863 6864
            errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]);
            Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]);
P
Pilchie 已提交
6865

6866
            CleanupAllGeneratedFiles(src.Path);
P
Pilchie 已提交
6867 6868
        }

J
Jared Parsons 已提交
6869
        [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")]
J
Jared Parsons 已提交
6870
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
P
Pilchie 已提交
6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885
        public void Bug733242()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(
@"
/// <summary>ABC...XYZ</summary>
class C {} ");

            var xml = dir.CreateFile("a.xml");
            xml.WriteAllText("EMPTY");

            using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
            {
6886
                var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" {0}", src.ToString(), xml.ToString()), startFolder: dir.ToString());
P
Pilchie 已提交
6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907
                Assert.Equal("", output.Trim());

                Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml")));

                using (var reader = new StreamReader(xmlFileHandle))
                {
                    var content = reader.ReadToEnd();
                    Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>a</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>ABC...XYZ</summary>
        </member>
    </members>
</doc>".Trim(), content.Trim());
                }
            }
6908 6909

            CleanupAllGeneratedFiles(src.Path);
6910
            CleanupAllGeneratedFiles(xml.Path);
P
Pilchie 已提交
6911 6912
        }

J
Jared Parsons 已提交
6913
        [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")]
J
Jared Parsons 已提交
6914
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
P
Pilchie 已提交
6915 6916 6917 6918 6919 6920 6921 6922
        public void Bug768605()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(
@"
/// <summary>ABC</summary>
6923
class C {}
P
Pilchie 已提交
6924
/// <summary>XYZ</summary>
6925
class E {}
P
Pilchie 已提交
6926 6927 6928 6929 6930
");

            var xml = dir.CreateFile("a.xml");
            xml.WriteAllText("EMPTY");

6931
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" {0}", src.ToString(), xml.ToString()), startFolder: dir.ToString());
P
Pilchie 已提交
6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956
            Assert.Equal("", output.Trim());

            using (var reader = new StreamReader(xml.ToString()))
            {
                var content = reader.ReadToEnd();
                Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>a</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>ABC</summary>
        </member>
        <member name=""T:E"">
            <summary>XYZ</summary>
        </member>
    </members>
</doc>".Trim(), content.Trim());
            }

            src.WriteAllText(
@"
/// <summary>ABC</summary>
6957
class C {}
P
Pilchie 已提交
6958 6959
");

6960
            output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" {0}", src.ToString(), xml.ToString()), startFolder: dir.ToString());
P
Pilchie 已提交
6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978
            Assert.Equal("", output.Trim());

            using (var reader = new StreamReader(xml.ToString()))
            {
                var content = reader.ReadToEnd();
                Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>a</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>ABC</summary>
        </member>
    </members>
</doc>".Trim(), content.Trim());
            }
6979 6980

            CleanupAllGeneratedFiles(src.Path);
6981
            CleanupAllGeneratedFiles(xml.Path);
P
Pilchie 已提交
6982 6983 6984 6985 6986
        }

        [Fact]
        public void ParseFullpaths()
        {
J
Jared Parsons 已提交
6987
            var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
6988
            Assert.False(parsedArgs.PrintFullPaths);
P
Pilchie 已提交
6989

J
Jared Parsons 已提交
6990
            parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory);
6991
            Assert.True(parsedArgs.PrintFullPaths);
P
Pilchie 已提交
6992

J
Jared Parsons 已提交
6993
            parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory);
P
Pilchie 已提交
6994 6995 6996
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
6997
            parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory);
P
Pilchie 已提交
6998 6999 7000
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
7001
            parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory);
P
Pilchie 已提交
7002 7003 7004
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
7005
            parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory);
P
Pilchie 已提交
7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);
        }

        [Fact]
        public void CheckFullpaths()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
public class C
{
    public static void Main()
    {
        string x;
    }
}").Path;

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            // Checks the base case without /fullpaths (expect to see relative path name)
T
Renames  
TomasMatousek 已提交
7026
            //      c:\temp> csc.exe c:\temp\a.cs
P
Pilchie 已提交
7027 7028
            //      a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7029
            var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
7030 7031
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7032
            Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
7033 7034

            // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name)
T
Renames  
TomasMatousek 已提交
7035
            //      c:\temp> csc.exe c:\temp\example\a.cs
P
Pilchie 已提交
7036 7037
            //      example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7038
            csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
7039 7040
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7041 7042
            Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
            Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
7043 7044

            // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name)
T
Renames  
TomasMatousek 已提交
7045
            //      c:\temp> csc.exe c:\test\a.cs
P
Pilchie 已提交
7046 7047
            //      c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7048
            csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" });
P
Pilchie 已提交
7049 7050
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7051
            Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
7052 7053

            // Checks the case with /fullpaths (expect to see the full paths)
T
Renames  
TomasMatousek 已提交
7054
            //      c:\temp> csc.exe c:\temp\a.cs /fullpaths
P
Pilchie 已提交
7055 7056
            //      c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7057
            csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" });
P
Pilchie 已提交
7058 7059
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7060
            Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
7061 7062

            // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name)
T
Renames  
TomasMatousek 已提交
7063
            //      c:\temp> csc.exe c:\temp\example\a.cs /fullpaths
P
Pilchie 已提交
7064 7065
            //      c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7066
            csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" });
P
Pilchie 已提交
7067 7068
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7069
            Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
7070 7071

            // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name)
T
Renames  
TomasMatousek 已提交
7072
            //      c:\temp> csc.exe c:\test\a.cs /fullpaths
P
Pilchie 已提交
7073 7074
            //      c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7075
            csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" });
P
Pilchie 已提交
7076 7077
            exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
7078
            Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
7079 7080

            CleanupAllGeneratedFiles(source);
7081
            CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source)));
P
Pilchie 已提交
7082 7083 7084 7085 7086
        }

        [Fact]
        public void DefaultResponseFile()
        {
J
Jared Parsons 已提交
7087 7088 7089 7090 7091
            var sdkDirectory = SdkDirectory;
            MockCSharpCompiler csc = new MockCSharpCompiler(
                GetDefaultResponseFilePath(), 
                RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory),
                new string[0]);
7092
            AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[]
P
Pilchie 已提交
7093
            {
J
Jared Parsons 已提交
7094
                MscorlibFullPath,
P
Pilchie 已提交
7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138
                "Accessibility.dll",
                "Microsoft.CSharp.dll",
                "System.Configuration.dll",
                "System.Configuration.Install.dll",
                "System.Core.dll",
                "System.Data.dll",
                "System.Data.DataSetExtensions.dll",
                "System.Data.Linq.dll",
                "System.Data.OracleClient.dll",
                "System.Deployment.dll",
                "System.Design.dll",
                "System.DirectoryServices.dll",
                "System.dll",
                "System.Drawing.Design.dll",
                "System.Drawing.dll",
                "System.EnterpriseServices.dll",
                "System.Management.dll",
                "System.Messaging.dll",
                "System.Runtime.Remoting.dll",
                "System.Runtime.Serialization.dll",
                "System.Runtime.Serialization.Formatters.Soap.dll",
                "System.Security.dll",
                "System.ServiceModel.dll",
                "System.ServiceModel.Web.dll",
                "System.ServiceProcess.dll",
                "System.Transactions.dll",
                "System.Web.dll",
                "System.Web.Extensions.Design.dll",
                "System.Web.Extensions.dll",
                "System.Web.Mobile.dll",
                "System.Web.RegularExpressions.dll",
                "System.Web.Services.dll",
                "System.Windows.Forms.dll",
                "System.Workflow.Activities.dll",
                "System.Workflow.ComponentModel.dll",
                "System.Workflow.Runtime.dll",
                "System.Xml.dll",
                "System.Xml.Linq.dll",
            }, StringComparer.OrdinalIgnoreCase);
        }

        [Fact]
        public void DefaultResponseFileNoConfig()
        {
J
Jared Parsons 已提交
7139
            MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" });
P
Pilchie 已提交
7140 7141
            Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[]
            {
J
Jared Parsons 已提交
7142
                MscorlibFullPath,
P
Pilchie 已提交
7143 7144 7145
            }, StringComparer.OrdinalIgnoreCase);
        }

J
Jared Parsons 已提交
7146
        [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")]
P
Pilchie 已提交
7147 7148 7149 7150 7151 7152 7153
        public void TestFilterParseDiagnostics()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
#pragma warning disable 440
using global = A; // CS0440
class A
{
7154
static void Main() {
P
Pilchie 已提交
7155 7156 7157 7158 7159 7160 7161 7162
#pragma warning suppress 440
}
}").Path;

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7163
            int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7164 7165 7166 7167
            Assert.Equal(0, exitCode);
            Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected disable or restore", outWriter.ToString().Trim());

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7168
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7169 7170
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
7171

P
Pilchie 已提交
7172
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7173
            exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7174 7175
            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim());
7176

7177
            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
7178 7179
        }

J
Jared Parsons 已提交
7180
        [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")]
P
Pilchie 已提交
7181 7182 7183
        public void TestNoWarnParseDiagnostics()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
7184
class Test
P
Pilchie 已提交
7185
{
7186
 static void Main()
P
Pilchie 已提交
7187 7188 7189 7190 7191
 {
  //Generates warning CS1522: Empty switch block
  switch (1)   { }

  //Generates warning CS0642: Possible mistaken empty statement
7192
  while (false) ;
P
Pilchie 已提交
7193
  {  }
7194
 }
P
Pilchie 已提交
7195 7196 7197 7198 7199 7200 7201
}
").Path;

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7202
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7203 7204
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
7205 7206

            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
7207 7208
        }

J
Jared Parsons 已提交
7209
        [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")]
P
Pilchie 已提交
7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234
        public void TestWarnAsError_CS1522()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
public class Test
{
    // CS0169 (level 3)
    private int x;
    // CS0109 (level 4)
    public new void Method() { }
    public static int Main()
    {
        int i = 5;
        // CS1522 (level 1)
        switch (i) { }
        return 0;
        // CS0162 (level 2)
        i = 6;
    }
}
").Path;

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7235
            int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7236
            Assert.Equal(1, exitCode);
7237
            Assert.Equal(fileName + "(12,20): error CS1522: Empty switch block", outWriter.ToString().Trim());
7238 7239

            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
7240 7241
        }

J
Jared Parsons 已提交
7242
        [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")]
7243
        public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01()
P
Pilchie 已提交
7244 7245
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path;
7246
            string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path;
P
Pilchie 已提交
7247 7248 7249 7250 7251

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7252
            int exitCode = CreateCSharpCompiler(null, baseDir, new[]
P
Pilchie 已提交
7253 7254
            {
                "/nologo",
7255
                "/preferreduilang:en",
P
Pilchie 已提交
7256 7257 7258 7259 7260
                "/win32res:" + badres,
                source
            }).Run(outWriter);

            Assert.Equal(1, exitCode);
A
angocke 已提交
7261
            Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim());
7262

7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276
            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(badres);
        }

        [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")]
        public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path;
            string badres = Temp.CreateFile().WriteAllBytes(new byte [] { 0, 0}).Path;

            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7277
            int exitCode = CreateCSharpCompiler(null, baseDir, new[]
7278 7279 7280 7281 7282 7283 7284 7285 7286 7287
            {
                "/nologo",
                "/preferreduilang:en",
                "/win32res:" + badres,
                source
            }).Run(outWriter);

            Assert.Equal(1, exitCode);
            Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim());

7288 7289
            CleanupAllGeneratedFiles(source);
            CleanupAllGeneratedFiles(badres);
P
Pilchie 已提交
7290 7291
        }

J
Jared Parsons 已提交
7292
        [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")]
P
Pilchie 已提交
7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303
        public void TestFilterCommandLineDiagnostics()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
class A
{
static void Main() { }
}").Path;
            var baseDir = Path.GetDirectoryName(source);
            var fileName = Path.GetFileName(source);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7304
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter);
P
Pilchie 已提交
7305 7306
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
7307

7308
            System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll"));
7309
            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
7310 7311
        }

J
Jared Parsons 已提交
7312
        [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")]
P
Pilchie 已提交
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324
        public void CS1691WRN_BadWarningNumber_Bug15905()
        {
            string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
class Program
{
#pragma warning disable 1998
        public static void Main() { }
#pragma warning restore 1998
} ").Path;
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

            // Repro case 1
J
Jared Parsons 已提交
7325
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7326 7327 7328 7329
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());

            // Repro case 2
J
Jared Parsons 已提交
7330
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter);
P
Pilchie 已提交
7331 7332
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
7333 7334

            CleanupAllGeneratedFiles(source);
P
Pilchie 已提交
7335 7336
        }

J
Jared Parsons 已提交
7337
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
7338 7339 7340 7341 7342
        public void ExistingPdb()
        {
            var dir = Temp.CreateDirectory();

            var source1 = dir.CreateFile("program1.cs").WriteAllText(@"
7343
class " + new string('a', 10000) + @"
7344
{
7345
    public static void Main()
7346
    {
7347
    }
7348 7349 7350
}");
            var source2 = dir.CreateFile("program2.cs").WriteAllText(@"
class Program2
7351 7352 7353 7354 7355
{
        public static void Main() { }
}");
            var source3 = dir.CreateFile("program3.cs").WriteAllText(@"
class Program3
7356 7357 7358 7359 7360 7361
{
        public static void Main() { }
}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377
            int oldSize = 16 * 1024;

            var exe = dir.CreateFile("Program.exe");
            using (var stream = File.OpenWrite(exe.Path))
            {
                byte[] buffer = new byte[oldSize];
                stream.Write(buffer, 0, buffer.Length);
            }

            var pdb = dir.CreateFile("Program.pdb");
            using (var stream = File.OpenWrite(pdb.Path))
            {
                byte[] buffer = new byte[oldSize];
                stream.Write(buffer, 0, buffer.Length);
            }

J
Jared Parsons 已提交
7378
            int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter);
7379 7380 7381 7382
            Assert.NotEqual(0, exitCode1);

            ValidateZeroes(exe.Path, oldSize);
            ValidateZeroes(pdb.Path, oldSize);
7383

J
Jared Parsons 已提交
7384
            int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter);
7385 7386
            Assert.Equal(0, exitCode2);

7387 7388
            using (var peFile = File.OpenRead(exe.Path))
            {
7389
                PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false);
7390 7391 7392 7393 7394
            }

            Assert.True(new FileInfo(exe.Path).Length < oldSize);
            Assert.True(new FileInfo(pdb.Path).Length < oldSize);

J
Jared Parsons 已提交
7395
            int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter);
7396 7397 7398 7399
            Assert.Equal(0, exitCode3);

            using (var peFile = File.OpenRead(exe.Path))
            {
7400
                PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false);
7401 7402
            }
        }
7403

7404 7405 7406
        private static void ValidateZeroes(string path, int count)
        {
            using (var stream = File.OpenRead(path))
7407
            {
7408 7409 7410 7411 7412 7413 7414 7415 7416 7417
                byte[] buffer = new byte[count];
                stream.Read(buffer, 0, buffer.Length);

                for (int i = 0; i < buffer.Length; i++)
                {
                    if (buffer[i] != 0)
                    {
                        Assert.True(false);
                    }
                }
7418 7419 7420
            }
        }

7421 7422
        /// <summary>
        /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/>
7423
        /// the compiler should delete the file to unblock build while allowing the reader to continue
7424 7425
        /// reading the previous snapshot of the file content.
        /// 
C
Charles Stoner 已提交
7426
        /// On Windows we can read the original data directly from the stream without creating a memory map. 
7427
        /// </summary>
J
Jared Parsons 已提交
7428
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439
        public void FileShareDeleteCompatibility_Windows()
        {
            var dir = Temp.CreateDirectory();
            var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
            var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL");
            var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB");

            var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
            var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7440
            int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter);
7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460
            if (exitCode != 0)
            {
                AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString());
            }

            Assert.Equal(0, exitCode);

            AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2));
            AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3));

            AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2));
            AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3));

            fsDll.Dispose();
            fsPdb.Dispose();

            AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());
        }

        /// <summary>
7461
        /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything.
7462 7463
        /// We need to create the actual memory map. This works on Windows as well.
        /// </summary>
J
Jared Parsons 已提交
7464 7465
        [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")]
        [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487
        public void FileShareDeleteCompatibility_Xplat()
        {
            var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01;
            var mvid = ReadMvid(new MemoryStream(bytes));

            var dir = Temp.CreateDirectory();
            var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
            var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes);
            var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes);

            var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
            var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);

            var peDll = new PEReader(fsDll);
            var pePdb = new PEReader(fsPdb);

            // creates memory map view:
            var imageDll = peDll.GetEntireImage();
            var imagePdb = pePdb.GetEntireImage();

            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable {libSrc.Path}", startFolder: dir.ToString());
            AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
7488
Microsoft (R) Visual C# Compiler version {s_compilerVersion} ({s_compilerShortCommitHash })
7489 7490
Copyright (C) Microsoft Corporation. All rights reserved.", output);

7491
            // reading original content from the memory map:
7492 7493
            Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray())));
            Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray())));
7494 7495

            // reading original content directly from the streams:
7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546
            fsDll.Position = 0;
            fsPdb.Position = 0;
            Assert.Equal(mvid, ReadMvid(fsDll));
            Assert.Equal(mvid, ReadMvid(fsPdb));

            // reading new content from the file:
            using (var fsNewDll = File.OpenRead(libDll.Path))
            {
                Assert.NotEqual(mvid, ReadMvid(fsNewDll));
            }

            // Portable PDB metadata signature:
            AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4));

            // dispose PEReaders (they dispose the underlying file streams)
            peDll.Dispose();
            pePdb.Dispose();

            AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());

            // files can be deleted now:
            File.Delete(libSrc.Path);
            File.Delete(libDll.Path);
            File.Delete(libPdb.Path);

            // directory can be deleted (should be empty):
            Directory.Delete(dir.Path, recursive: false);
        }

        private static Guid ReadMvid(Stream stream)
        {
            using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen))
            {
                var mdReader = peReader.GetMetadataReader();
                return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid);
            }
        }

        // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes).
        [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")]
        public void FileShareDeleteCompatibility_ReadOnlyFiles()
        {
            var dir = Temp.CreateDirectory();
            var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
            var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL");

            File.SetAttributes(libDll.Path, FileAttributes.ReadOnly);

            var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7547
            int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter);
7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565
            Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString());

            AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3));
            AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3));

            fsDll.Dispose();

            AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());
        }

        [Fact]
        public void FileShareDeleteCompatibility_ExistingDirectory()
        {
            var dir = Temp.CreateDirectory();
            var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
            var libDll = dir.CreateDirectory("Lib.dll");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7566
            int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter);
7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584
            Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString());
        }

        private byte[] ReadBytes(Stream stream, int count)
        {
            var buffer = new byte[count];
            stream.Read(buffer, 0, count);
            return buffer;
        }

        private byte[] ReadBytes(string path, int count)
        {
            using (var stream = File.OpenRead(path))
            {
                return ReadBytes(stream, count);
            }
        }

7585 7586 7587 7588 7589
        [Fact]
        public void IOFailure_DisposeOutputFile()
        {
            var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
            var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe");
J
Jared Parsons 已提交
7590
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath });
7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612
            csc.FileOpen = (file, mode, access, share) =>
            {
                if (file == exePath)
                {
                    return new TestStream(backingStream: new MemoryStream(),
                        dispose: () => { throw new IOException("Fake IOException"); });
                }

                return File.Open(file, mode, access, share);
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            Assert.Equal(1, csc.Run(outWriter));
            Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
        }

        [Fact]
        public void IOFailure_DisposePdbFile()
        {
            var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
            var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe");
            var pdbPath = Path.ChangeExtension(exePath, "pdb");
J
Jared Parsons 已提交
7613
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath });
7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634
            csc.FileOpen = (file, mode, access, share) =>
            {
                if (file == pdbPath)
                {
                    return new TestStream(backingStream: new MemoryStream(),
                        dispose: () => { throw new IOException("Fake IOException"); });
                }

                return File.Open(file, mode, access, share);
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            Assert.Equal(1, csc.Run(outWriter));
            Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
        }

        [Fact]
        public void IOFailure_DisposeXmlFile()
        {
            var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
            var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml");
J
Jared Parsons 已提交
7635
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath });
7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651
            csc.FileOpen = (file, mode, access, share) =>
            {
                if (file == xmlPath)
                {
                    return new TestStream(backingStream: new MemoryStream(),
                        dispose: () => { throw new IOException("Fake IOException"); });
                }

                return File.Open(file, mode, access, share);
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            Assert.Equal(1, csc.Run(outWriter));
            Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
        }

7652 7653 7654 7655
        [Theory]
        [InlineData("portable")]
        [InlineData("full")]
        public void IOFailure_DisposeSourceLinkFile(string format)
7656 7657 7658
        {
            var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
            var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json");
J
Jared Parsons 已提交
7659
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath });
7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681
            csc.FileOpen = (file, mode, access, share) =>
            {
                if (file == sourceLinkPath)
                {
                    return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@"
{
  ""documents"": {
     ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
  }
}
")),
                        dispose: () => { throw new IOException("Fake IOException"); });
                }

                return File.Open(file, mode, access, share);
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            Assert.Equal(1, csc.Run(outWriter));
            Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
        }

7682
        [Fact]
7683
        public void IOFailure_OpenOutputFile()
P
Pilchie 已提交
7684 7685
        {
            string sourcePath = MakeTrivialExe();
7686
            string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe");
J
Jared Parsons 已提交
7687
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath });
P
Pilchie 已提交
7688 7689
            csc.FileOpen = (file, mode, access, share) =>
            {
7690
                if (file == exePath)
P
Pilchie 已提交
7691 7692 7693
                {
                    throw new IOException();
                }
7694

7695
                return File.Open(file, mode, access, share);
P
Pilchie 已提交
7696 7697 7698
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
7699 7700
            Assert.Equal(1, csc.Run(outWriter));
            Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString());
7701 7702

            System.IO.File.Delete(sourcePath);
7703
            System.IO.File.Delete(exePath);
7704
            CleanupAllGeneratedFiles(sourcePath);
P
Pilchie 已提交
7705 7706 7707
        }

        [Fact]
7708
        public void IOFailure_OpenPdbFileNotCalled()
P
Pilchie 已提交
7709 7710
        {
            string sourcePath = MakeTrivialExe();
7711 7712
            string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe");
            string pdbPath = Path.ChangeExtension(exePath, ".pdb");
J
Jared Parsons 已提交
7713
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath });
7714
            csc.FileOpen = (file, mode, access, share) =>
P
Pilchie 已提交
7715
            {
7716
                if (file == pdbPath)
P
Pilchie 已提交
7717 7718 7719 7720
                {
                    throw new IOException();
                }

J
Fix ups  
Jared Parsons 已提交
7721
                return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share);
P
Pilchie 已提交
7722 7723 7724
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
7725
            Assert.Equal(0, csc.Run(outWriter));
P
Pilchie 已提交
7726

7727 7728 7729
            System.IO.File.Delete(sourcePath);
            System.IO.File.Delete(exePath);
            System.IO.File.Delete(pdbPath);
7730
            CleanupAllGeneratedFiles(sourcePath);
P
Pilchie 已提交
7731 7732 7733
        }

        [Fact]
7734
        public void IOFailure_OpenXmlFinal()
P
Pilchie 已提交
7735 7736
        {
            string sourcePath = MakeTrivialExe();
J
Jared Parsons 已提交
7737 7738
            string xmlPath = Path.Combine(WorkingDirectory, "Test.xml");
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath });
7739
            csc.FileOpen = (file, mode, access, share) =>
P
Pilchie 已提交
7740
            {
7741
                if (file == xmlPath)
P
Pilchie 已提交
7742 7743 7744 7745 7746
                {
                    throw new IOException();
                }
                else
                {
J
Fix ups  
Jared Parsons 已提交
7747
                    return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share);
P
Pilchie 已提交
7748 7749 7750 7751 7752 7753
                }
            };

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            int exitCode = csc.Run(outWriter);

7754 7755
            var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath);
            Assert.Equal(expectedOutput, outWriter.ToString().Trim());
P
Pilchie 已提交
7756

7757
            Assert.NotEqual(0, exitCode);
7758 7759 7760

            System.IO.File.Delete(xmlPath);
            System.IO.File.Delete(sourcePath);
7761 7762
            CleanupAllGeneratedFiles(sourcePath);
        }
P
Pilchie 已提交
7763

7764
        private string MakeTrivialExe(string directory = null)
P
Pilchie 已提交
7765
        {
7766
            return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@"
P
Pilchie 已提交
7767 7768 7769 7770 7771 7772
class Program
{
    public static void Main() { }
} ").Path;
        }

J
Jared Parsons 已提交
7773
        [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")]
P
Pilchie 已提交
7774 7775 7776 7777 7778 7779 7780 7781
        public void CS1691WRN_BadWarningNumber_AllErrorCodes()
        {
            const int jump = 200;
            for (int i = 0; i < 8000; i += (8000 / jump))
            {
                int startErrorCode = (int)i * jump;
                int endErrorCode = startErrorCode + jump;
                string source = ComputeSourceText(startErrorCode, endErrorCode);
7782 7783 7784 7785 7786

                // Previous versions of the compiler used to report a warning (CS1691)
                // whenever an unrecognized warning code was supplied in a #pragma directive
                // (or via /nowarn /warnaserror flags on the command line).
                // Going forward, we won't generate any warning in such cases. This will make
C
Charles Stoner 已提交
7787
                // maintenance of backwards compatibility easier (we no longer need to worry
7788 7789 7790
                // about breaking existing projects / command lines if we deprecate / remove
                // an old warning code).
                Test(source, startErrorCode, endErrorCode);
P
Pilchie 已提交
7791 7792 7793 7794 7795 7796 7797 7798 7799
            }
        }

        private static string ComputeSourceText(int startErrorCode, int endErrorCode)
        {
            string pragmaDisableWarnings = String.Empty;

            for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++)
            {
7800
                string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @"
P
Pilchie 已提交
7801
";
7802
                pragmaDisableWarnings += pragmaDisableStr;
P
Pilchie 已提交
7803 7804 7805 7806 7807 7808 7809 7810 7811
            }

            return pragmaDisableWarnings + @"
public class C
{
    public static void Main() { }
}";
        }

7812
        private void Test(string source, int startErrorCode, int endErrorCode)
P
Pilchie 已提交
7813 7814 7815 7816
        {
            string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
7817
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter);
P
Pilchie 已提交
7818 7819 7820 7821 7822
            Assert.Equal(0, exitCode);
            var cscOutput = outWriter.ToString().Trim();

            for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++)
            {
7823
                Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode);
P
Pilchie 已提交
7824
            }
7825 7826

            CleanupAllGeneratedFiles(sourcePath);
P
Pilchie 已提交
7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838
        }

        [Fact]
        public void WriteXml()
        {
            var source = @"
/// <summary>
/// A subtype of <see cref=""object""/>.
/// </summary>
public class C { }
";

J
Jared Parsons 已提交
7839 7840 7841
            var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path;
            string xmlPath = Path.Combine(WorkingDirectory, "Test.xml");
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath });
P
Pilchie 已提交
7842 7843 7844 7845 7846 7847 7848 7849

            var writer = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = csc.Run(writer);
            if (exitCode != 0)
            {
                Console.WriteLine(writer.ToString());
                Assert.Equal(0, exitCode);
            }
7850

P
Pilchie 已提交
7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868
            var bytes = File.ReadAllBytes(xmlPath);
            var actual = new string(Encoding.UTF8.GetChars(bytes));
            var expected = @"
<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>Test</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>
            A subtype of <see cref=""T:System.Object""/>.
            </summary>
        </member>
    </members>
</doc>
";
            Assert.Equal(expected.Trim(), actual.Trim());
7869 7870 7871 7872 7873 7874

            System.IO.File.Delete(xmlPath);
            System.IO.File.Delete(sourcePath);

            CleanupAllGeneratedFiles(sourcePath);
            CleanupAllGeneratedFiles(xmlPath);
P
Pilchie 已提交
7875 7876
        }

J
Jared Parsons 已提交
7877
        [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")]
J
Jared Parsons 已提交
7878
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
P
Pilchie 已提交
7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895
        public void CS2002WRN_FileAlreadyIncluded()
        {
            const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times";

            TempDirectory tempParentDir = Temp.CreateDirectory();
            TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir");
            TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }");

            // Simple case
            var commandLineArgs = new[] { "a.cs", "a.cs" };
            // warning CS2002: Source file 'a.cs' specified multiple times
            string aWrnString = String.Format(cs2002, "a.cs");
            TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString);

            // Multiple duplicates
            commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" };
            // warning CS2002: Source file 'a.cs' specified multiple times
7896
            var warnings = new[] { aWrnString };
P
Pilchie 已提交
7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936
            TestCS2002(commandLineArgs, tempDir.Path, 0, warnings);

            // Case-insensitive
            commandLineArgs = new[] { "a.cs", "A.cs" };
            // warning CS2002: Source file 'A.cs' specified multiple times
            string AWrnString = String.Format(cs2002, "A.cs");
            TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString);

            // Different extensions
            tempDir.CreateFile("a.csx");
            commandLineArgs = new[] { "a.cs", "a.csx" };
            // No errors or warnings
            TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty);

            // Absolute vs Relative
            commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path };
            // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
            string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs");
            TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);

            // Both relative
            commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" };
            // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
            TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);

            // With wild cards
            commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" };
            // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
            TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);

            // "/recurse" scenarios
            commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" };
            // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
            TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);

            commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" };
            // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
            TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);

            // Invalid file/path characters
7937
            const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}";
7938
            commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" };
P
Pilchie 已提交
7939 7940 7941 7942 7943 7944
            // error CS1504: Source file '{0}' could not be opened: Illegal characters in path.
            var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path.");
            TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str);

            commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" };
            var parseDiags = new[] {
7945
                // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
7946
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"),
7947 7948
                // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found.
                Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")};
P
Pilchie 已提交
7949 7950 7951 7952 7953
            TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags);

            char currentDrive = Directory.GetCurrentDirectory()[0];
            commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" };
            parseDiags = new[] {
7954
                // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
7955
                Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")};
P
Pilchie 已提交
7956 7957
            TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags);

7958
            commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" };
P
Pilchie 已提交
7959 7960 7961
            // error CS1504: Source file '{0}' could not be opened: {1}
            var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported.");
            TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504);
7962 7963 7964

            CleanupAllGeneratedFiles(tempFile.Path);
            System.IO.Directory.Delete(tempParentDir.Path, true);
P
Pilchie 已提交
7965 7966
        }

J
Jared Parsons 已提交
7967
        private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics)
P
Pilchie 已提交
7968 7969 7970 7971
        {
            TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics);
        }

J
Jared Parsons 已提交
7972
        private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics)
P
Pilchie 已提交
7973 7974
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
7975
            var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray();
P
Pilchie 已提交
7976 7977

            // Verify command line parser diagnostics.
7978
            DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics);
P
Pilchie 已提交
7979 7980

            // Verify compile.
J
Jared Parsons 已提交
7981
            int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter);
P
Pilchie 已提交
7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009
            Assert.Equal(expectedExitCode, exitCode);

            if (parseDiagnostics.IsEmpty())
            {
                // Verify compile diagnostics.
                string outString = String.Empty;
                for (int i = 0; i < compileDiagnostics.Length; i++)
                {
                    if (i != 0)
                    {
                        outString += @"
";
                    }

                    outString += compileDiagnostics[i];
                }

                Assert.Equal(outString, outWriter.ToString().Trim());
            }
            else
            {
                Assert.Null(compileDiagnostics);
            }
        }

        [Fact]
        public void ErrorLineEnd()
        {
8010
            var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo");
P
Pilchie 已提交
8011

J
Jared Parsons 已提交
8012
            var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" });
P
Pilchie 已提交
8013 8014 8015 8016
            var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6));
            var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc);
            var text = comp.DiagnosticFormatter.Format(diag);

8017
            string stringStart = "goo(1,7,1,8)";
P
Pilchie 已提交
8018 8019 8020 8021

            Assert.Equal(stringStart, text.Substring(0, stringStart.Length));
        }

8022 8023 8024
        [Fact]
        public void ReportAnalyzer()
        {
J
Jared Parsons 已提交
8025
            var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory);
8026 8027
            Assert.True(parsedArgs1.ReportAnalyzer);

J
Jared Parsons 已提交
8028
            var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory);
8029 8030 8031 8032 8033 8034 8035 8036 8037 8038
            Assert.False(parsedArgs2.ReportAnalyzer);
        }

        [Fact]
        public void ReportAnalyzerOutput()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8039
            var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path });
8040 8041 8042 8043 8044 8045 8046 8047
            var exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            var output = outWriter.ToString();
            Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal);
            Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal);
            CleanupAllGeneratedFiles(srcFile.Path);
        }

8048 8049 8050 8051 8052 8053 8054 8055 8056 8057
        [Fact]
        [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")]
        public void TestCompilationSuccessIfOnlySuppressedDiagnostics()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"
#pragma warning disable Warning01
class C { }
");

            var errorLog = Temp.CreateFile();
J
Jared Parsons 已提交
8058 8059
            var csc = CreateCSharpCompiler(
                null,
8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074
                workingDirectory: Path.GetDirectoryName(srcFile.Path),
                args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path },
                analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer()));

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = csc.Run(outWriter);

            // Previously, the compiler would return error code 1 without printing any diagnostics
            Assert.Empty(outWriter.ToString());
            Assert.Equal(0, exitCode);

            CleanupAllGeneratedFiles(srcFile.Path);
            CleanupAllGeneratedFiles(errorLog.Path);
        }

8075 8076 8077 8078 8079 8080 8081 8082
        [Fact]
        [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")]
        public void AnalyzerDiagnosticThrowsInGetMessage()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8083
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path },
J
Jared Parsons 已提交
8084
               analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage()));
8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099

            var exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            var output = outWriter.ToString();

            // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message.
            Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal);

            // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported.
            Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal);
            Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal);

            CleanupAllGeneratedFiles(srcFile.Path);
        }

8100 8101 8102 8103 8104 8105 8106 8107
        [Fact]
        [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")]
        public void AnalyzerExceptionDiagnosticCanBeConfigured()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8108
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path },
J
Jared Parsons 已提交
8109
               analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage()));
8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121

            var exitCode = csc.Run(outWriter);
            Assert.NotEqual(0, exitCode);
            var output = outWriter.ToString();

            // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported.
            Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal);
            Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal);

            CleanupAllGeneratedFiles(srcFile.Path);
        }

8122 8123 8124 8125 8126 8127 8128 8129
        [Fact]
        [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")]
        public void AnalyzerReportsMisformattedDiagnostic()
        {
            var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
            var srcDirectory = Path.GetDirectoryName(srcFile.Path);

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8130
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path },
J
Jared Parsons 已提交
8131
               analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic()));
8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143

            var exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);
            var output = outWriter.ToString();

            // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message.
            Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal);
            Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal);

            CleanupAllGeneratedFiles(srcFile.Path);
        }

P
Pilchie 已提交
8144 8145 8146 8147 8148 8149 8150
        [Fact]
        public void ErrorPathsFromLineDirectives()
        {
            string sampleProgram = @"
#line 10 "".."" //relative path
using System*
";
8151
            var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
J
Jared Parsons 已提交
8152
            var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { });
P
Pilchie 已提交
8153 8154
            var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
            //Pull off the last segment of the current directory.
J
Jared Parsons 已提交
8155
            var expectedPath = Path.GetDirectoryName(WorkingDirectory);
P
Pilchie 已提交
8156 8157 8158 8159 8160 8161 8162
            //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info.
            Assert.Equal('(', text[expectedPath.Length]);

            sampleProgram = @"
#line 10 "".>"" //invalid path character
using System*
";
8163
            syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
P
Pilchie 已提交
8164
            text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
8165
            Assert.True(text.StartsWith(".>", StringComparison.Ordinal));
P
Pilchie 已提交
8166 8167

            sampleProgram = @"
8168
#line 10 ""http://goo.bar/baz.aspx"" //URI
P
Pilchie 已提交
8169 8170
using System*
";
8171
            syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
P
Pilchie 已提交
8172
            text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
8173
            Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal));
P
Pilchie 已提交
8174 8175
        }

J
Jared Parsons 已提交
8176
        [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")]
8177
        [Fact]
P
Pilchie 已提交
8178 8179 8180
        public void PreferredUILang()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8181
            int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter);
P
Pilchie 已提交
8182
            Assert.Equal(1, exitCode);
8183
            Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8184 8185

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8186
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter);
P
Pilchie 已提交
8187
            Assert.Equal(1, exitCode);
8188
            Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8189 8190

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8191
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter);
P
Pilchie 已提交
8192
            Assert.Equal(1, exitCode);
8193
            Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8194 8195

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8196
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter);
P
Pilchie 已提交
8197
            Assert.Equal(1, exitCode);
8198
            Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8199 8200

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8201
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter);
P
Pilchie 已提交
8202
            Assert.Equal(1, exitCode);
8203
            Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8204 8205

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8206
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter);
P
Pilchie 已提交
8207
            Assert.Equal(1, exitCode);
8208
            Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8209 8210

            outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8211
            exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter);
P
Pilchie 已提交
8212
            Assert.Equal(1, exitCode);
8213
            Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8214 8215
        }

J
Jared Parsons 已提交
8216
        [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")]
P
Pilchie 已提交
8217 8218 8219 8220
        [Fact]
        public void EmptyFileName()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
8221
            var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter);
P
Pilchie 已提交
8222 8223 8224
            Assert.NotEqual(0, exitCode);

            // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
8225
            Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8226 8227
        }

J
Jared Parsons 已提交
8228
        [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
P
Pilchie 已提交
8229 8230 8231 8232 8233 8234
        [Fact]
        public void NoInfoDiagnostics()
        {
            string filePath = Temp.CreateFile().WriteAllText(@"
using System.Diagnostics; // Unused.
").Path;
J
Jared Parsons 已提交
8235
            var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath });
P
Pilchie 已提交
8236 8237 8238 8239
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(outWriter);
            Assert.Equal(0, exitCode);
            Assert.Equal("", outWriter.ToString().Trim());
8240 8241

            CleanupAllGeneratedFiles(filePath);
P
Pilchie 已提交
8242 8243 8244 8245 8246
        }

        [Fact]
        public void RuntimeMetadataVersion()
        {
J
Jared Parsons 已提交
8247
            var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory);
P
Pilchie 已提交
8248 8249 8250
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
8251
            parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory);
P
Pilchie 已提交
8252 8253 8254
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
8255
            parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:  " }, WorkingDirectory);
P
Pilchie 已提交
8256 8257 8258
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);

J
Jared Parsons 已提交
8259
            parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory);
P
Pilchie 已提交
8260
            Assert.Equal(0, parsedArgs.Errors.Length);
8261
            Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion);
P
Pilchie 已提交
8262

J
Jared Parsons 已提交
8263
            parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory);
P
Pilchie 已提交
8264
            Assert.Equal(0, parsedArgs.Errors.Length);
8265
            Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion);
P
Pilchie 已提交
8266

J
Jared Parsons 已提交
8267
            var comp = CreateEmptyCompilation(string.Empty);
8268
            Assert.Equal(ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion, "v4.0.30319");
P
Pilchie 已提交
8269

J
Jared Parsons 已提交
8270
            comp = CreateEmptyCompilation(string.Empty);
8271
            Assert.Equal(ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion, "_+@%#*^");
P
Pilchie 已提交
8272 8273
        }

J
Jared Parsons 已提交
8274
        [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")]
J
jaredpar 已提交
8275
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
8276 8277 8278 8279 8280 8281 8282 8283 8284
        public void WRN_InvalidSearchPathDir()
        {
            var baseDir = Temp.CreateDirectory();
            var sourceFile = baseDir.CreateFile("Source.cs");

            var invalidPath = "::";
            var nonExistentPath = "DoesNotExist";

            // lib switch
J
Jared Parsons 已提交
8285
            DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify(
P
Pilchie 已提交
8286 8287
                // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid"));
J
Jared Parsons 已提交
8288
            DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify(
P
Pilchie 已提交
8289 8290 8291 8292
                // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist"));

            // LIB environment variable
J
Jared Parsons 已提交
8293
            DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify(
P
Pilchie 已提交
8294 8295
                // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid"));
J
Jared Parsons 已提交
8296
            DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify(
P
Pilchie 已提交
8297 8298
                // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist'
                Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist"));
8299

8300
            CleanupAllGeneratedFiles(sourceFile.Path);
P
Pilchie 已提交
8301 8302
        }

J
Jared Parsons 已提交
8303
        [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")]
J
jaredpar 已提交
8304
        [ConditionalFact(typeof(WindowsOnly))]
P
Pilchie 已提交
8305 8306
        public void ReservedDeviceNameAsFileName()
        {
J
Jared Parsons 已提交
8307
            var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory);
P
Pilchie 已提交
8308 8309
            Assert.Equal(0, parsedArgs.Errors.Length);

J
Jared Parsons 已提交
8310
            parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory);
P
Pilchie 已提交
8311
            Assert.Equal(1, parsedArgs.Errors.Length);
8312
            Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code);
P
Pilchie 已提交
8313 8314


J
Jared Parsons 已提交
8315
            parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory);
P
Pilchie 已提交
8316
            Assert.Equal(1, parsedArgs.Errors.Length);
8317
            Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code);
P
Pilchie 已提交
8318

J
Jared Parsons 已提交
8319
            parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml:  " }, WorkingDirectory);
P
Pilchie 已提交
8320
            Assert.Equal(1, parsedArgs.Errors.Length);
8321
            Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code);
P
Pilchie 已提交
8322

J
Jared Parsons 已提交
8323
            parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory);
P
Pilchie 已提交
8324
            Assert.Equal(1, parsedArgs.Errors.Length);
8325
            Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code);
P
Pilchie 已提交
8326

J
Jared Parsons 已提交
8327
            parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory);
P
Pilchie 已提交
8328 8329 8330 8331 8332 8333 8334 8335
            Assert.Equal(1, parsedArgs.Errors.Length);
            Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code);
        }

        [Fact]
        public void ReservedDeviceNameAsFileName2()
        {
            string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path;
8336
            // make sure reserved device names don't
J
Jared Parsons 已提交
8337
            var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath });
P
Pilchie 已提交
8338 8339 8340
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(outWriter);
            Assert.Equal(1, exitCode);
8341
            Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8342

J
Jared Parsons 已提交
8343
            cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath });
P
Pilchie 已提交
8344 8345 8346
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
            exitCode = cmd.Run(outWriter);
            Assert.Equal(1, exitCode);
8347
            Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal);
P
Pilchie 已提交
8348

J
Jared Parsons 已提交
8349
            cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath });
P
Pilchie 已提交
8350 8351 8352
            outWriter = new StringWriter(CultureInfo.InvariantCulture);
            exitCode = cmd.Run(outWriter);
            Assert.Equal(1, exitCode);
8353
            Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal);
8354 8355

            CleanupAllGeneratedFiles(filePath);
P
Pilchie 已提交
8356
        }
8357 8358 8359

        [Fact]
        public void ParseFeatures()
8360
        {
J
Jared Parsons 已提交
8361
            var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory);
8362
            args.Errors.Verify();
8363
            Assert.Equal("Test", args.ParseOptions.Features.Single().Key);
8364

J
Jared Parsons 已提交
8365
            args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory);
8366
            args.Errors.Verify();
8367
            Assert.Equal(2, args.ParseOptions.Features.Count);
8368 8369
            Assert.True(args.ParseOptions.Features.ContainsKey("Test"));
            Assert.True(args.ParseOptions.Features.ContainsKey("Experiment"));
8370

J
Jared Parsons 已提交
8371
            args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory);
8372
            args.Errors.Verify();
8373
            Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } }));
8374

J
Jared Parsons 已提交
8375
            args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory);
8376
            args.Errors.Verify();
J
Jared Parsons 已提交
8377
            Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } }));
8378
        }
8379

J
Jared Parsons 已提交
8380
        [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
8381 8382
        public void ParseAdditionalFile()
        {
J
Jared Parsons 已提交
8383
            var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory);
8384
            args.Errors.Verify();
J
Jared Parsons 已提交
8385
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path);
8386

J
Jared Parsons 已提交
8387
            args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory);
8388
            args.Errors.Verify();
8389
            Assert.Equal(2, args.AdditionalFiles.Length);
J
Jared Parsons 已提交
8390 8391
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
            Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
8392

J
Jared Parsons 已提交
8393
            args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory);
8394
            args.Errors.Verify();
8395
            Assert.Equal(2, args.AdditionalFiles.Length);
J
Jared Parsons 已提交
8396 8397
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path);
8398

J
Jared Parsons 已提交
8399
            args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory);
8400
            args.Errors.Verify();
J
Jared Parsons 已提交
8401
            Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path);
8402 8403 8404 8405 8406 8407

            var baseDir = Temp.CreateDirectory();
            baseDir.CreateFile("web1.config");
            baseDir.CreateFile("web2.config");
            baseDir.CreateFile("web3.config");

8408
            args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path);
8409
            args.Errors.Verify();
8410 8411 8412 8413
            Assert.Equal(3, args.AdditionalFiles.Length);
            Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path);
            Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path);
            Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path);
8414

J
Jared Parsons 已提交
8415
            args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory);
8416
            args.Errors.Verify();
8417
            Assert.Equal(2, args.AdditionalFiles.Length);
J
Jared Parsons 已提交
8418 8419
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
            Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
8420

J
Jared Parsons 已提交
8421
            args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory);
8422
            args.Errors.Verify();
8423
            Assert.Equal(2, args.AdditionalFiles.Length);
J
Jared Parsons 已提交
8424 8425
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
            Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
8426

J
Jared Parsons 已提交
8427
            args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory);
8428
            args.Errors.Verify();
8429
            Assert.Equal(1, args.AdditionalFiles.Length);
J
Jared Parsons 已提交
8430
            Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path);
8431

J
Jared Parsons 已提交
8432
            args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory);
8433
            args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile"));
8434
            Assert.Equal(0, args.AdditionalFiles.Length);
8435

J
Jared Parsons 已提交
8436
            args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory);
8437
            args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile"));
8438
            Assert.Equal(0, args.AdditionalFiles.Length);
8439 8440
        }

8441
        private static int OccurrenceCount(string source, string word)
8442 8443
        {
            var n = 0;
8444
            var index = source.IndexOf(word, StringComparison.Ordinal);
8445 8446 8447
            while (index >= 0)
            {
                ++n;
8448
                index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal);
8449 8450 8451 8452
            }
            return n;
        }

J
Jared Parsons 已提交
8453
        private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile,
C
Charles Stoner 已提交
8454
                                           bool includeCurrentAssemblyAsAnalyzerReference = true,
8455 8456 8457 8458 8459 8460
                                           string[] additionalFlags = null,
                                           int expectedInfoCount = 0,
                                           int expectedWarningCount = 0,
                                           int expectedErrorCount = 0)
        {
            var args = new[] {
8461
                                "/nologo", "/preferreduilang:en", "/t:library",
8462 8463
                                sourceFile.Path
                             };
C
Charles Stoner 已提交
8464
            if (includeCurrentAssemblyAsAnalyzerReference)
8465 8466 8467 8468 8469 8470 8471 8472
            {
                args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location);
            }
            if (additionalFlags != null)
            {
                args = args.Append(additionalFlags);
            }

J
Jared Parsons 已提交
8473
            var csc = CreateCSharpCompiler(null, sourceDir.Path, args);
8474 8475
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = csc.Run(outWriter);
8476
            var output = outWriter.ToString();
8477 8478

            var expectedExitCode = expectedErrorCount > 0 ? 1 : 0;
8479
            Assert.True(
8480 8481
                expectedExitCode == exitCode,
                string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}",
8482
                expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output));
8483

8484
            Assert.DoesNotContain("hidden", output, StringComparison.Ordinal);
8485 8486 8487

            if (expectedInfoCount == 0)
            {
8488
                Assert.DoesNotContain("info", output, StringComparison.Ordinal);
8489 8490 8491
            }
            else
            {
8492
                Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info"));
8493 8494 8495 8496
            }

            if (expectedWarningCount == 0)
            {
8497
                Assert.DoesNotContain("warning", output, StringComparison.Ordinal);
8498 8499 8500
            }
            else
            {
8501
                Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning"));
8502 8503 8504 8505
            }

            if (expectedErrorCount == 0)
            {
8506
                Assert.DoesNotContain("error", output, StringComparison.Ordinal);
8507 8508 8509
            }
            else
            {
8510
                Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error"));
8511 8512 8513 8514 8515
            }

            return output;
        }

J
Jared Parsons 已提交
8516
        [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527
        [Fact]
        public void NoWarnAndWarnAsError_AnalyzerDriverWarnings()
        {
            // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause
            // compiler warning CS8032 to be produced when compilations created in this test try to load it.
            string source = @"using System;";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var output = VerifyOutput(dir, file, expectedWarningCount: 1);
8528
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8529

8530 8531
            // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
J
Jared Parsons 已提交
8532
            Assert.True(string.IsNullOrEmpty(output));
8533

8534 8535
            // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" });
J
Jared Parsons 已提交
8536
            Assert.True(string.IsNullOrEmpty(output));
8537

8538 8539
            // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
8540
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8541

8542 8543
            // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1);
8544
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8545 8546 8547 8548

            CleanupAllGeneratedFiles(file.Path);
        }

J
Jared Parsons 已提交
8549 8550 8551
        [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
        [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
        [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564
        [Fact]
        public void NoWarnAndWarnAsError_HiddenDiagnostic()
        {
            // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden
            // diagnostics for #region directives present in the compilations created in this test.
            var source = @"using System;
#region Region
#endregion";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var output = VerifyOutput(dir, file, expectedWarningCount: 1);
8565
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8566 8567

            // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
8568
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
J
Jared Parsons 已提交
8569
            Assert.True(string.IsNullOrEmpty(output));
8570 8571 8572

            // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1);
8573
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8574 8575

            // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01.
8576
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" });
J
Jared Parsons 已提交
8577
            Assert.True(string.IsNullOrEmpty(output));
8578 8579 8580

            // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1);
8581
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8582 8583 8584

            // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8585 8586
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
8587 8588 8589

            // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
8590
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8591 8592 8593

            // TEST: Verify /nowarn: overrides /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1);
8594
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8595 8596 8597

            // TEST: Verify /nowarn: overrides /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1);
8598
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8599

8600 8601
            // TEST: Verify /nowarn: overrides /warnaserror-:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1);
8602
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8603 8604 8605

            // TEST: Verify /nowarn: overrides /warnaserror-:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
8606
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8607

8608
            // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
8609
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" });
J
Jared Parsons 已提交
8610
            Assert.True(string.IsNullOrEmpty(output));
8611

8612
            // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
8613
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" });
J
Jared Parsons 已提交
8614
            Assert.True(string.IsNullOrEmpty(output));
8615 8616 8617

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
8618
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8619 8620 8621

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8622 8623
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
8624

8625
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8626
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8627 8628
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
8629

8630
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8631
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1);
8632
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8633

8634
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8635
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1);
8636
            Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
8637

8638
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8639
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" });
J
Jared Parsons 已提交
8640
            Assert.True(string.IsNullOrEmpty(output));
8641 8642 8643

            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1);
8644
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8645 8646

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8647
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" });
J
Jared Parsons 已提交
8648
            Assert.True(string.IsNullOrEmpty(output));
8649

8650 8651
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1);
8652
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8653 8654 8655

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
8656
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8657

8658 8659 8660
            CleanupAllGeneratedFiles(file.Path);
        }

J
Jared Parsons 已提交
8661 8662 8663
        [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
        [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
        [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
8664 8665 8666 8667 8668 8669 8670
        [Fact]
        public void NoWarnAndWarnAsError_InfoDiagnostic()
        {
            // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info
            // diagnostics for the #pragma warning restore directives present in the compilations created in this test.
            var source = @"using System;
#pragma warning restore";
8671 8672 8673
            var name = "a.cs";
            string output;
            output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: 1);
8674 8675
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8676

8677
            // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01.
8678
            output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" });
8679 8680

            // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:.
8681
            output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1);
8682
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8683 8684

            // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+.
8685
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: 1);
8686
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8687 8688

            // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used.
8689
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: 1);
8690 8691
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8692 8693

            // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:.
8694
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8695 8696
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8697 8698

            // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:.
8699
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: 1);
8700 8701
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8702 8703

            // TEST: Verify /nowarn overrides /warnaserror.
8704
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1);
8705
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8706 8707

            // TEST: Verify /nowarn overrides /warnaserror.
8708
            output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1);
8709
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8710

8711
            // TEST: Verify /nowarn overrides /warnaserror-.
8712
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1);
8713
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8714 8715

            // TEST: Verify /nowarn overrides /warnaserror-.
8716
            output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1);
8717
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8718

8719
            // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01.
8720
            output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" });
8721 8722

            // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01.
8723
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" });
8724 8725

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
8726
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: 1);
8727 8728
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8729 8730

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
8731
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8732 8733
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8734

8735
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8736
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1);
8737 8738
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8739

8740
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8741
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: 1);
8742
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8743 8744

            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8745
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: 1);
8746
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8747

8748
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8749
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1);
8750
            Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8751

8752
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8753
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: 1);
8754 8755
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8756 8757

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8758
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: 1);
8759
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8760

8761
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8762
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: 1);
8763 8764
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8765 8766

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8767
            output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: 1);
8768 8769
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
8770
        }
8771

8772
        private string GetOutput(
8773
            string name,
8774
            string source,
C
Charles Stoner 已提交
8775
            bool includeCurrentAssemblyAsAnalyzerReference = true,
8776 8777 8778 8779 8780 8781 8782 8783 8784
            string[] additionalFlags = null,
            int expectedInfoCount = 0,
            int expectedWarningCount = 0,
            int expectedErrorCount = 0)
        {
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile(name);
            file.WriteAllText(source);

C
Charles Stoner 已提交
8785
            var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount);
8786
            CleanupAllGeneratedFiles(file.Path);
8787
            return output;
8788 8789
        }

8790
        [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")]
J
Jared Parsons 已提交
8791 8792 8793 8794 8795
        [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
        [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
        [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")]
        [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")]
        [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814
        [Fact]
        public void NoWarnAndWarnAsError_WarningDiagnostic()
        {
            // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning
            // diagnostics for source types present in the compilations created in this test.
            string source = @"
class C
{
    static void Main()
    {
        int i;
    }
}
";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var output = VerifyOutput(dir, file, expectedWarningCount: 3);
8815 8816 8817
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
8818 8819

            // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0.
8820
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
J
Jared Parsons 已提交
8821
            Assert.True(string.IsNullOrEmpty(output));
8822 8823 8824

            // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
8825
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8826 8827 8828

            // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3);
8829 8830 8831
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8832 8833

            // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror.
C
Charles Stoner 已提交
8834 8835
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2);
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
8836
            Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
8837 8838

            // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+.
C
Charles Stoner 已提交
8839 8840
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2);
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
8841
            Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
8842 8843 8844

            // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3);
8845 8846 8847
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8848 8849 8850

            // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
8851 8852 8853
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8854 8855 8856

            // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:.
            // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069).
C
Charles Stoner 已提交
8857 8858
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1);
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
8859 8860
            Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8861 8862 8863

            // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3);
8864 8865 8866
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8867 8868

            // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:.
C
Charles Stoner 已提交
8869 8870
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2);
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
8871 8872
            Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8873 8874

            // TEST: Verify that /warn:0 overrides /warnaserror+.
8875
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" });
8876 8877

            // TEST: Verify that /warn:0 overrides /warnaserror.
8878
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" });
8879 8880

            // TEST: Verify that /warn:0 overrides /warnaserror-.
8881
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" });
8882 8883

            // TEST: Verify that /warn:0 overrides /warnaserror-.
8884
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" });
8885 8886 8887

            // TEST: Verify that /nowarn: overrides /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
8888
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8889 8890 8891

            // TEST: Verify that /nowarn: overrides /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1);
8892
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8893

8894 8895
            // TEST: Verify that /nowarn: overrides /warnaserror-:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
8896
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8897 8898 8899

            // TEST: Verify that /nowarn: overrides /warnaserror-:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1);
8900
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8901

8902
            // TEST: Verify that /nowarn: overrides /warnaserror+.
8903
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" });
8904 8905

            // TEST: Verify that /nowarn: overrides /warnaserror+.
8906
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" });
8907 8908

            // TEST: Verify that /nowarn: overrides /warnaserror-.
8909
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" });
8910 8911

            // TEST: Verify that /nowarn: overrides /warnaserror-.
8912
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" });
8913 8914

            // TEST: Verify that /warn:0 overrides /warnaserror:.
8915
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" });
8916 8917

            // TEST: Verify that /warn:0 overrides /warnaserror:.
8918
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" });
8919 8920

            // TEST: Verify that last /warnaserror[+/-] flag on command line wins.
8921
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1);
8922
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8923 8924 8925

            // TEST: Verify that last /warnaserror[+/-] flag on command line wins.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3);
8926 8927 8928
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8929 8930 8931

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
8932 8933 8934
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8935 8936 8937

            // TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3);
8938 8939 8940
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8941

8942
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8943
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1);
8944
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8945

8946
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8947
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3);
8948 8949 8950
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8951

8952
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8953
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3);
8954 8955 8956
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8957

8958
            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8959
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
8960 8961 8962
            Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8963

8964
            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8965
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1);
8966
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8967 8968

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8969
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1);
8970
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
8971 8972

            // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
8973
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3);
8974 8975 8976
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8977 8978

            // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
8979
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3);
8980 8981 8982
            Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
8983

8984 8985 8986
            CleanupAllGeneratedFiles(file.Path);
        }

J
Jared Parsons 已提交
8987 8988
        [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
        [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000
        [Fact]
        public void NoWarnAndWarnAsError_ErrorDiagnostic()
        {
            // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error
            // diagnostics for #pragma warning disable directives present in the compilations created in this test.
            string source = @"using System;
#pragma warning disable";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

            var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1);
9001 9002
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9003 9004

            // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0.
9005
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1);
9006
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9007 9008 9009

            // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1);
9010
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9011 9012

            // TEST: Verify that /nowarn: overrides /warnaserror+.
9013
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1);
9014
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
9015 9016

            // TEST: Verify that /nowarn: overrides /warnaserror.
9017
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1);
9018
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
9019 9020 9021

            // TEST: Verify that /nowarn: overrides /warnaserror+:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1);
9022
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9023 9024 9025

            // TEST: Verify that /nowarn: overrides /warnaserror:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1);
9026
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9027 9028 9029

            // TEST: Verify that /nowarn: overrides /warnaserror-.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1);
9030
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9031 9032 9033

            // TEST: Verify that /nowarn: overrides /warnaserror-.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1);
9034
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9035 9036 9037

            // TEST: Verify that /nowarn: overrides /warnaserror-.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1);
9038
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9039 9040 9041

            // TEST: Verify that /nowarn: overrides /warnaserror-.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1);
9042
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
9043 9044

            // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present.
9045
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
9046
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
9047

9048
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1);
9049
            Assert.Contains("error CS8032", output, StringComparison.Ordinal);
9050 9051

            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1);
9052 9053
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9054 9055 9056

            // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:.
            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
9057 9058
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9059 9060

            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
9061 9062
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9063 9064

            output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
9065 9066
            Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
            Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
9067 9068 9069 9070

            CleanupAllGeneratedFiles(file.Path);
        }

9071 9072 9073 9074 9075
        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void ConsistentErrorMessageWhenProvidingNoKeyFile()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9076
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
        }

        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void ConsistentErrorMessageWhenProvidingEmptyKeyFile()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9088
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
        }

        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9100
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
        }

        [Fact]
        [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
        public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign()
        {
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9112
            var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
9113 9114 9115 9116 9117 9118
            int exitCode = csc.Run(outWriter);

            Assert.Equal(1, exitCode);
            Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
        }

J
Jared Parsons 已提交
9119
        [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134
        [Fact]
        public void NoWarnAndWarnAsError_CompilerErrorDiagnostic()
        {
            string source = @"using System;
class C
{
    static void Main()
    {
        int i = new Exception();
    }
}";
            var dir = Temp.CreateDirectory();
            var file = dir.CreateFile("a.cs");
            file.WriteAllText(source);

C
Charles Stoner 已提交
9135
            var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1);
9136
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9137 9138

            // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0.
C
Charles Stoner 已提交
9139
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1);
9140
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9141 9142

            // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:.
C
Charles Stoner 已提交
9143
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1);
9144
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9145

C
Charles Stoner 已提交
9146
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1);
9147
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9148 9149

            // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present.
C
Charles Stoner 已提交
9150
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
9151
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9152

C
Charles Stoner 已提交
9153
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1);
9154
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9155

C
Charles Stoner 已提交
9156
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1);
9157
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9158 9159

            // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:.
C
Charles Stoner 已提交
9160
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1);
9161
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9162

C
Charles Stoner 已提交
9163
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1);
9164
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9165

C
Charles Stoner 已提交
9166
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1);
9167
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9168

C
Charles Stoner 已提交
9169
            output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1);
9170
            Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
9171 9172 9173

            CleanupAllGeneratedFiles(file.Path);
        }
9174

J
Jared Parsons 已提交
9175
        [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
9176 9177 9178
        [Fact]
        public void WarnAsError_LastOneWins1()
        {
9179
            var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null);
9180 9181
            var options = arguments.CompilationOptions;

J
Jared Parsons 已提交
9182
            var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)]
9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199
public class C
{
    public void M(ushort i)
    {
    }
    public static void Main(string[] args) {}
}", options: options);

            comp.VerifyDiagnostics(
                // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant
                //     public void M(ushort i)
                Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i")
                    .WithArguments("ushort")
                    .WithLocation(4, 26)
                    .WithWarningAsError(true));
        }

J
Jared Parsons 已提交
9200
        [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
9201 9202 9203
        [Fact]
        public void WarnAsError_LastOneWins2()
        {
9204
            var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null);
9205 9206
            var options = arguments.CompilationOptions;

J
Jared Parsons 已提交
9207
            var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)]
9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223
public class C
{
    public void M(ushort i)
    {
    }
    public static void Main(string[] args) {}
}", options: options);

            comp.VerifyDiagnostics(
                // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant
                //     public void M(ushort i)
                Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i")
                    .WithArguments("ushort")
                    .WithLocation(4, 26)
                    .WithWarningAsError(false));
        }
9224

J
Jared Parsons 已提交
9225
        [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")]
J
jaredpar 已提交
9226
        [WorkItem(444, "CodePlex")]
J
Jared Parsons 已提交
9227
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243
        public void Bug1091972()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(
@"
/// <summary>ABC...XYZ</summary>
class C {
    static void Main()
    {
        var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml""));
        System.Console.WriteLine(textStreamReader.ReadToEnd());
    }
} ");

9244
            var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml {0}", src.ToString()), startFolder: dir.ToString());
9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267
            Assert.Equal("", output.Trim());

            Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml")));

            var expected =
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>out</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>ABC...XYZ</summary>
        </member>
    </members>
</doc>".Trim();

            using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml")))
            {
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content.Trim());
            }

9268
            output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString());
9269 9270 9271 9272
            Assert.Equal(expected, output.Trim());

            CleanupAllGeneratedFiles(src.Path);
        }
9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313

        [ConditionalFact(typeof(WindowsOnly))]
        public void CommandLineMisc()
        {
            CSharpCommandLineArguments args = null;
            string baseDirectory = @"c:\test";
            Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory);

            args = parse(@"/out:""a.exe""");
            Assert.Equal(@"a.exe", args.OutputFileName);

            args = parse(@"/pdb:""a.pdb""");
            Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath);

            // The \ here causes " to be treated as a quote, not as an escaping construct
            args = parse(@"a\""b c""\d.cs");
            Assert.Equal(
                new[] { @"c:\test\a""b", @"c:\test\c\d.cs" },
                args.SourceFiles.Select(x => x.Path));

            args = parse(@"a\\""b c""\d.cs");
            Assert.Equal(
                new[] { @"c:\test\a\b c\d.cs" },
                args.SourceFiles.Select(x => x.Path));

            args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs");
            Assert.Equal(
                new[] { @"a.dll", @"b.dll" },
                args.MetadataReferences.Select(x => x.Reference));

            args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs");
            Assert.Equal(
                new[] { @"a-s.dll", @"b-s.dll" },
                args.MetadataReferences.Select(x => x.Reference));

            args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs");
            Assert.Equal(
                new[] { @"a,;s.dll", @"b,;s.dll" },
                args.MetadataReferences.Select(x => x.Reference));
        }

9314 9315 9316
        [Fact]
        public void CommandLine_ScriptRunner1()
        {
J
Jared Parsons 已提交
9317 9318
            var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9319 9320
            AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9321 9322
            args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path));
9323 9324
            AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9325 9326
            args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path));
9327 9328
            AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9329 9330
            args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9331 9332
            AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9333 9334
            args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9335 9336
            AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9337 9338
            args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory);
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9339 9340
            AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9341
            args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
9342
            Assert.True(args.InteractiveMode);
J
Jared Parsons 已提交
9343
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9344 9345
            AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9346
            args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
9347
            Assert.True(args.InteractiveMode);
J
Jared Parsons 已提交
9348
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
9349 9350
            AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);

J
Jared Parsons 已提交
9351
            args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory);
9352
            Assert.True(args.InteractiveMode);
J
Jared Parsons 已提交
9353
            AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path));
9354 9355
            Assert.True(args.SourceFiles[0].IsScript);
            AssertEx.Equal(new[] { "--" }, args.ScriptArguments);
T
Tomas Matousek 已提交
9356 9357 9358 9359 9360 9361 9362 9363

            // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904)
            // Result: C:\/script.csx
            //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\");
            //Assert.True(args.InteractiveMode);
            //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path));
            //Assert.True(args.SourceFiles[0].IsScript);
            //AssertEx.Equal(new[] { "--" }, args.ScriptArguments);
9364 9365
        }

J
Jared Parsons 已提交
9366
        [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")]
9367 9368 9369 9370 9371 9372 9373 9374
        [Fact]
        public void ParseSeparatedPaths_QuotedComma()
        {
            var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b""");
            Assert.Equal(
                new[] { @"a, b" },
                paths);
        }
9375

9376
        [CompilerTrait(CompilerFeature.Determinism)]
J
Jared Parsons 已提交
9377
        [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
9378 9379
        public void PathMapParser()
        {
J
Jared Parsons 已提交
9380
            var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory);
9381 9382 9383
            parsedArgs.Errors.Verify();
            Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap);

J
Jared Parsons 已提交
9384
            parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory);
9385
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9386
            Assert.Equal(KeyValuePairUtil.Create("K1\\", "V1\\"), parsedArgs.PathMap[0]);
A
Ashley Hauck 已提交
9387

J
Jared Parsons 已提交
9388
            parsedArgs = DefaultParse(new[] { "/pathmap:C:\\goo\\=/", "a.cs" }, WorkingDirectory);
A
Ashley Hauck 已提交
9389
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9390
            Assert.Equal(KeyValuePairUtil.Create("C:\\goo\\", "/"), parsedArgs.PathMap[0]);
9391

J
Jared Parsons 已提交
9392
            parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory);
9393
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9394 9395
            Assert.Equal(KeyValuePairUtil.Create("K1\\", "V1\\"), parsedArgs.PathMap[0]);
            Assert.Equal(KeyValuePairUtil.Create("K2\\", "V2\\"), parsedArgs.PathMap[1]);
9396

J
Jared Parsons 已提交
9397
            parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory);
9398 9399 9400 9401 9402
            Assert.Equal(4, parsedArgs.Errors.Count());
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code);
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[2].Code);
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[3].Code);
9403

J
Jared Parsons 已提交
9404
            parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory);
9405 9406 9407
            Assert.Equal(2, parsedArgs.Errors.Count());
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code);
9408

J
Jared Parsons 已提交
9409
            parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory);
9410 9411
            Assert.Equal(1, parsedArgs.Errors.Count());
            Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
A
Ashley Hauck 已提交
9412

J
Jared Parsons 已提交
9413
            parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory);
A
Ashley Hauck 已提交
9414
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9415
            Assert.Equal(KeyValuePairUtil.Create("supporting spaces\\", "is hard\\"), parsedArgs.PathMap[0]);
A
Ashley Hauck 已提交
9416

J
Jared Parsons 已提交
9417
            parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory);
A
Ashley Hauck 已提交
9418
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9419 9420
            Assert.Equal(KeyValuePairUtil.Create("K 1\\", "V 1\\"), parsedArgs.PathMap[0]);
            Assert.Equal(KeyValuePairUtil.Create("K 2\\", "V 2\\"), parsedArgs.PathMap[1]);
A
Ashley Hauck 已提交
9421

J
Jared Parsons 已提交
9422
            parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory);
A
Ashley Hauck 已提交
9423
            parsedArgs.Errors.Verify();
J
Jared Parsons 已提交
9424 9425
            Assert.Equal(KeyValuePairUtil.Create("K 1\\", "V 1\\"), parsedArgs.PathMap[0]);
            Assert.Equal(KeyValuePairUtil.Create("K 2\\", "V 2\\"), parsedArgs.PathMap[1]);
9426
        }
9427

J
Jared Parsons 已提交
9428
        [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
9429 9430 9431
        [CompilerTrait(CompilerFeature.Determinism)]
        public void PathMapPdbParser()
        {
J
Jared Parsons 已提交
9432 9433
            var dir = Path.Combine(WorkingDirectory, "a");
            var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory);
9434 9435 9436 9437 9438 9439 9440
            parsedArgs.Errors.Verify();
            Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath);

            // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it.
            Assert.Null(parsedArgs.EmitOptions.PdbFilePath);
        }

J
Jared Parsons 已提交
9441
        [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453
        [CompilerTrait(CompilerFeature.Determinism)]
        public void PathMapPdbEmit()
        {
            void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs)
            {
                var source = @"class Program { static void Main() { } }";
                var src = dir.CreateFile("a.cs").WriteAllText(source);
                var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" };
                var isDeterministic = extraArgs.Contains("/deterministic");
                var args = defaultArgs.Concat(extraArgs).ToArray();
                var outWriter = new StringWriter(CultureInfo.InvariantCulture);

J
Jared Parsons 已提交
9454
                var csc = CreateCSharpCompiler(null, dir.Path, args);
9455 9456 9457 9458 9459 9460 9461 9462
                int exitCode = csc.Run(outWriter);
                Assert.Equal(0, exitCode);

                var exePath = Path.Combine(dir.Path, "a.exe");
                Assert.True(File.Exists(exePath));
                Assert.True(File.Exists(pdbPath));
                using (var peStream = File.OpenRead(exePath))
                {
9463
                    PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic);
9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501
                }
            }

            // Case with no mappings
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, pdbPath);
            }

            // Simple mapping
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\");
            }

            // Simple mapping deterministic
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic");
            }

            // Partial mapping
            using (var dir = new DisposableDirectory(Temp))
            {
                dir.CreateDirectory("pdb");
                var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb");
                AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\");
            }

            // Legacy feature flag
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism");
            }
A
Ashley Hauck 已提交
9502 9503 9504 9505 9506 9507 9508

            // Unix path map
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/");
            }
A
Ashley Hauck 已提交
9509 9510 9511 9512 9513 9514 9515

            // Multi-specified path map with mixed slashes
            using (var dir = new DisposableDirectory(Temp))
            {
                var pdbPath = Path.Combine(dir.Path, "a.pdb");
                AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar");
            }
9516 9517
        }

9518
        [CompilerTrait(CompilerFeature.Determinism)]
J
Jared Parsons 已提交
9519
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538
        public void DeterministicPdbsRegardlessOfBitness()
        {
            var dir = Temp.CreateDirectory();
            var dir32 = dir.CreateDirectory("32");
            var dir64 = dir.CreateDirectory("64");

            var programExe32 = dir32.CreateFile("Program.exe");
            var programPdb32 = dir32.CreateFile("Program.pdb");
            var programExe64 = dir64.CreateFile("Program.exe");
            var programPdb64 = dir64.CreateFile("Program.pdb");

            var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@"
using System;
using System.Linq;
using System.Collections.Generic;

namespace N
{
    using I4 = System.Int32;
9539

9540 9541
    class Program
    {
9542
        public static IEnumerable<int> F()
9543
        {
9544
            I4 x = 1;
9545 9546 9547 9548
            yield return 1;
            yield return x;
        }

9549
        public static void Main(string[] args)
9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566
        {
            dynamic x = 1;
            const int a = 1;
            F().ToArray();
            Console.WriteLine(x + a);
        }
    }
}");
            var csc32src = $@"
using System;
using System.Reflection;

class Runner
{{
    static int Main(string[] args)
    {{
        var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}"");
9567
        var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program"");
9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588
        var main = program.GetMethod(""Main"");
        return (int)main.Invoke(null, new object[] {{ args }});
    }}
}}
";
            var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32");
            var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray());

            dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config");
            dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp"));

            var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:{dir32.Path}=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path);
            Assert.Equal("", output);

            output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:{dir64.Path}=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path);
            Assert.Equal("", output);

            AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes());
            AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes());
        }

9589
        [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")]
J
Jared Parsons 已提交
9590
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9591 9592 9593
        public void Version()
        {
            var folderName = Temp.CreateDirectory().ToString();
9594
            var expected = $"{FileVersionInfo.GetVersionInfo(typeof(CSharpCompiler).Assembly.Location).FileVersion} ({s_compilerShortCommitHash})";
9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609
            var argss = new[]
            {
                "/version",
                "a.cs /version /preferreduilang:en",
                "/version /nologo",
                "/version /help",
            };

            foreach (var args in argss)
            {
                var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName);
                Assert.Equal(expected, output.Trim());
            }
        }

J
Jared Parsons 已提交
9610
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9611 9612 9613
        public void RefOut()
        {
            var dir = Temp.CreateDirectory();
9614
            var refDir = dir.CreateDirectory("ref");
9615 9616 9617

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"
9618
public class C
9619 9620 9621 9622 9623 9624
{
    /// <summary>Main method</summary>
    public static void Main()
    {
        System.Console.Write(""Hello"");
    }
9625 9626 9627 9628 9629
    /// <summary>Private method</summary>
    private static void PrivateMethod()
    {
        System.Console.Write(""Private"");
    }
9630 9631 9632
}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9633
            var csc = CreateCSharpCompiler(null, dir.Path,
C
Charles Stoner 已提交
9634
                new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" });
9635 9636 9637 9638 9639 9640 9641 9642

            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            var exe = Path.Combine(dir.Path, "a.exe");
            Assert.True(File.Exists(exe));

            MetadataReaderUtils.VerifyPEMetadata(exe,
9643
                new[] { "TypeDefinition:<Module>", "TypeDefinition:C" },
9644
                new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" },
9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661
                new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" }
                );

            var doc = Path.Combine(dir.Path, "doc.xml");
            Assert.True(File.Exists(doc));

            var content = File.ReadAllText(doc);
            var expectedDoc =
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>a</name>
    </assembly>
    <members>
        <member name=""M:C.Main"">
            <summary>Main method</summary>
        </member>
9662 9663 9664
        <member name=""M:C.PrivateMethod"">
            <summary>Private method</summary>
        </member>
9665 9666 9667 9668 9669 9670 9671
    </members>
</doc>";
            Assert.Equal(expectedDoc, content.Trim());

            var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path);
            Assert.Equal("Hello", output.Trim());

9672
            var refDll = Path.Combine(refDir.Path, "a.dll");
9673 9674 9675 9676 9677
            Assert.True(File.Exists(refDll));

            // The types and members that are included needs further refinement.
            // See issue https://github.com/dotnet/roslyn/issues/17612
            MetadataReaderUtils.VerifyPEMetadata(refDll,
9678
                new[] { "TypeDefinition:<Module>", "TypeDefinition:C" },
9679
                new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" },
9680
                new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" }
9681 9682 9683 9684
                );

            // Clean up temp files
            CleanupAllGeneratedFiles(dir.Path);
9685 9686 9687
            CleanupAllGeneratedFiles(refDir.Path);
        }

9688 9689 9690 9691 9692 9693 9694 9695 9696 9697
        [Fact]
        public void RefOutWithError()
        {
            var dir = Temp.CreateDirectory();
            dir.CreateDirectory("ref");

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"class C { public static void Main() { error(); } }");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9698
            var csc = CreateCSharpCompiler(null, dir.Path,
9699
                new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" });
9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721
            int exitCode = csc.Run(outWriter);
            Assert.Equal(1, exitCode);

            var dll = Path.Combine(dir.Path, "a.dll");
            Assert.False(File.Exists(dll));

            var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll"));
            Assert.False(File.Exists(refDll));

            Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim());

            // Clean up temp files
            CleanupAllGeneratedFiles(dir.Path);
        }

        [Fact]
        public void RefOnly()
        {
            var dir = Temp.CreateDirectory();

            var src = dir.CreateFile("a.cs");
            src.WriteAllText(@"
9722
using System;
9723 9724 9725 9726 9727 9728 9729
class C
{
    /// <summary>Main method</summary>
    public static void Main()
    {
        error(); // semantic error in method body
    }
9730 9731 9732 9733 9734 9735
    private event Action E1
    {
        add { }
        remove { }
    }
    private event Action E2;
9736 9737 9738

    /// <summary>Private Class Field</summary>
    private int field;
9739

9740 9741 9742 9743 9744 9745
    /// <summary>Private Struct</summary>
    private struct S
    {
        /// <summary>Private Struct Field</summary>
        private int field;
    }
9746 9747 9748
}");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
J
Jared Parsons 已提交
9749
            var csc = CreateCSharpCompiler(null, dir.Path,
C
Charles Stoner 已提交
9750
                new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" });
9751
            int exitCode = csc.Run(outWriter);
9752
            Assert.Equal("", outWriter.ToString());
9753 9754 9755 9756 9757 9758 9759 9760
            Assert.Equal(0, exitCode);

            var refDll = Path.Combine(dir.Path, "a.dll");
            Assert.True(File.Exists(refDll));

            // The types and members that are included needs further refinement.
            // See issue https://github.com/dotnet/roslyn/issues/17612
            MetadataReaderUtils.VerifyPEMetadata(refDll,
9761
                new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" },
9762
                new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" },
9763
                new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" }
9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782
                );

            var pdb = Path.Combine(dir.Path, "a.pdb");
            Assert.False(File.Exists(pdb));

            var doc = Path.Combine(dir.Path, "doc.xml");
            Assert.True(File.Exists(doc));

            var content = File.ReadAllText(doc);
            var expectedDoc =
@"<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>a</name>
    </assembly>
    <members>
        <member name=""M:C.Main"">
            <summary>Main method</summary>
        </member>
9783 9784 9785 9786 9787 9788 9789 9790 9791
        <member name=""F:C.field"">
            <summary>Private Class Field</summary>
        </member>
        <member name=""T:C.S"">
            <summary>Private Struct</summary>
        </member>
        <member name=""F:C.S.field"">
            <summary>Private Struct Field</summary>
        </member>
9792 9793 9794 9795
    </members>
</doc>";
            Assert.Equal(expectedDoc, content.Trim());

9796

9797 9798 9799 9800
            // Clean up temp files
            CleanupAllGeneratedFiles(dir.Path);
        }

9801 9802 9803
        [Fact]
        public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics()
        {
J
Jared Parsons 已提交
9804
            var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory);
9805
            parsedArgs.Errors.Verify(
O
Omar Tawfik 已提交
9806
                // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier
9807 9808 9809 9810 9811 9812
                Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1));
        }

        [Fact]
        public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics()
        {
J
Jared Parsons 已提交
9813
            var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory);
9814
            parsedArgs.Errors.Verify(
9815
                // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values.
9816 9817 9818
                Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1));
        }

9819 9820 9821
        [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")]
        public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut()
        {
J
Jared Parsons 已提交
9822
            var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory);
9823 9824 9825 9826 9827 9828 9829 9830
            parsedArgs.Errors.Verify(
                // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier
                Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"),
                // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier
                Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"),
                // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier
                Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5"));
        }
9831 9832

        [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
J
Jared Parsons 已提交
9833
        [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9834 9835 9836
        public void MissingCompilerAssembly()
        {
            var dir = Temp.CreateDirectory();
9837
            var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path;
9838
            dir.CopyFile(typeof(Compilation).Assembly.Location);
9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854

            // Missing Microsoft.CodeAnalysis.CSharp.dll.
            var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path);
            Assert.Equal(1, result.ExitCode);
            Assert.Equal(
                $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
                result.Output.Trim());

            // Missing System.Collections.Immutable.dll.
            dir.CopyFile(typeof(CSharpCompilation).Assembly.Location);
            result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path);
            Assert.Equal(1, result.ExitCode);
            Assert.Equal(
                $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
                result.Output.Trim());
        }
T
Tomas Matousek 已提交
9855
#if NET472
9856 9857 9858 9859 9860 9861 9862
        [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
        public void LoadingAnalyzerNetStandard13()
        {
            var analyzerFileName = "AnalyzerNS13.dll";
            var srcFileName = "src.cs";

            var analyzerDir = Temp.CreateDirectory();
T
Tomas Matousek 已提交
9863
            var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(DesktopTestHelpers.CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName)));
9864 9865 9866 9867 9868 9869 9870 9871
            var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }");

            var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path);
            AssertEx.AssertEqualToleratingWhitespaceDifferences(
                $"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'.", result.Output);

            Assert.Equal(0, result.ExitCode);
        }
T
Tomas Matousek 已提交
9872
#endif
9873
        [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")]
J
Jared Parsons 已提交
9874
        [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
9875 9876 9877 9878
        public void MicrosoftDiaSymReaderNativeAltLoadPath()
        {
            var dir = Temp.CreateDirectory();
            var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable);
9879

9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912
            // copy csc and dependencies except for DSRN:
            foreach (var filePath in Directory.EnumerateFiles(cscDir))
            {
                var fileName = Path.GetFileName(filePath);

                if (fileName.StartsWith("csc") ||
                    fileName.StartsWith("System.") ||
                    fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native"))
                {
                    dir.CopyFile(filePath);
                }
            }

            dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }");

            var cscCopy = Path.Combine(dir.Path, "csc.exe");

            var arguments = "/nologo /t:library /debug:full Source.cs";

            // env variable not set (deterministic) -- DSRN is required:
            var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path);
            AssertEx.AssertEqualToleratingWhitespaceDifferences(
                "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " +
                "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim());

            // env variable not set (non-deterministic) -- globally registered SymReader is picked up:
            result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path);
            AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim());

            // env variable set:
            result = ProcessUtilities.Run(
                cscCopy,
                arguments + " /deterministic",
9913
                workingDirectory: dir.Path,
J
Jared Parsons 已提交
9914
                additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) });
9915 9916 9917 9918

            Assert.Equal("", result.Output.Trim());
        }

9919
        [ConditionalFact(typeof(WindowsOnly))]
A
Ashley Hauck 已提交
9920
        [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")]
C
Charles Stoner 已提交
9921
        public void PdbPathNotEmittedWithoutPdb()
9922 9923 9924 9925 9926 9927 9928 9929
        {
            var dir = Temp.CreateDirectory();

            var source = @"class Program { static void Main() { } }";
            var src = dir.CreateFile("a.cs").WriteAllText(source);
            var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" };
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

J
Jared Parsons 已提交
9930
            var csc = CreateCSharpCompiler(null, dir.Path, args);
9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944
            int exitCode = csc.Run(outWriter);
            Assert.Equal(0, exitCode);

            var exePath = Path.Combine(dir.Path, "a.exe");
            Assert.True(File.Exists(exePath));
            using (var peStream = File.OpenRead(exePath))
            using (var peReader = new PEReader(peStream))
            {
                var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory;
                Assert.Equal(0, debugDirectory.Size);
                Assert.Equal(0, debugDirectory.RelativeVirtualAddress);
            }
        }

9945 9946 9947 9948 9949 9950 9951
        [Fact]
        public void StrongNameProviderWithCustomTempPath()
        {
            var tempDir = Temp.CreateDirectory();
            var workingDir = Temp.CreateDirectory();
            workingDir.CreateFile("a.cs");

9952 9953
            var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path);
            var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" });
9954 9955 9956 9957 9958 9959 9960 9961
            var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null);
            var desktopProvider = Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider);
            using (var inputStream = Assert.IsType<DesktopStrongNameProvider.TempFileStream>(desktopProvider.CreateInputStream()))
            {
                Assert.Equal(tempDir.Path, Path.GetDirectoryName(inputStream.Path));
            }
        }

J
Jared Parsons 已提交
9962
        public class QuotedArgumentTests : CommandLineTestBase
9963
        {
9964 9965 9966 9967
            private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows
                ? @"c:\"
                : "/";

9968 9969
            private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue)
            {
9970
                var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath);
9971 9972 9973
                Assert.Equal(0, args.Errors.Length);
                Assert.Equal(expected, getValue(args));

9974
                args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath);
9975 9976 9977 9978 9979 9980
                Assert.Equal(0, args.Errors.Length);
                Assert.Equal(expected, getValue(args));
            }

            private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue)
            {
9981
                var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath);
9982 9983 9984
                Assert.Equal(0, args.Errors.Length);
                Assert.Equal(expected, getValue(args));

9985
                args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath);
9986 9987 9988 9989 9990 9991 9992
                Assert.True(args.Errors.Length > 0);
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
            [Fact]
            public void DebugFlag()
            {
9993 9994
                var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb;

9995 9996 9997
                var list = new List<Tuple<string, DebugInformationFormat>>()
                {
                    Tuple.Create("portable", DebugInformationFormat.PortablePdb),
9998 9999
                    Tuple.Create("full", platformPdbKind),
                    Tuple.Create("pdbonly", platformPdbKind),
10000 10001 10002 10003 10004 10005 10006 10007 10008 10009
                    Tuple.Create("embedded", DebugInformationFormat.Embedded)
                };

                foreach (var tuple in list)
                {
                    VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat);
                }
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
J
Jared Parsons 已提交
10010
            [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")]
10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069
            public void CodePage()
            {
                VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage);
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
            [Fact]
            public void Target()
            {
                var list = new List<Tuple<string, OutputKind>>()
                {
                    Tuple.Create("exe", OutputKind.ConsoleApplication),
                    Tuple.Create("winexe", OutputKind.WindowsApplication),
                    Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary),
                    Tuple.Create("module", OutputKind.NetModule),
                    Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication),
                    Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata)
                };

                foreach (var tuple in list)
                {
                    VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind);
                }
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
            [Fact]
            public void PlatformFlag()
            {
                var list = new List<Tuple<string, Platform>>()
                {
                    Tuple.Create("x86", Platform.X86),
                    Tuple.Create("x64", Platform.X64),
                    Tuple.Create("itanium", Platform.Itanium),
                    Tuple.Create("anycpu", Platform.AnyCpu),
                    Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred),
                    Tuple.Create("arm", Platform.Arm)
                };

                foreach (var tuple in list)
                {
                    VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform);
                }
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
            [Fact]
            public void WarnFlag()
            {
                VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel);
            }

            [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
            [Fact]
            public void LangVersionFlag()
            {
                VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion);
            }
        }
10070 10071 10072 10073 10074 10075

        [Fact]
        [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
        public void InvalidPathCharacterInPathMap()
        {
            string filePath = Temp.CreateFile().WriteAllText("").Path;
J
Jared Parsons 已提交
10076
            var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[]
10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091
            {
                filePath,
                "/debug:embedded",
                "/pathmap:test\\=\"",
                "/target:library",
                "/preferreduilang:en"
            });

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = compiler.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal);
        }

        [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
J
Jared Parsons 已提交
10092
        [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
10093 10094 10095
        public void InvalidPathCharacterInPdbPath()
        {
            string filePath = Temp.CreateFile().WriteAllText("").Path;
J
Jared Parsons 已提交
10096
            var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[]
10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109
            {
                filePath,
                "/debug:embedded",
                "/pdb:test\\?.pdb",
                "/target:library",
                "/preferreduilang:en"
            });

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = compiler.Run(outWriter);
            Assert.Equal(1, exitCode);
            Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal);
        }
P
Pilchie 已提交
10110 10111
    }

10112
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
10113
    internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer
P
Pilchie 已提交
10114
    {
10115 10116 10117 10118 10119 10120 10121
        public override abstract ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
        public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context);

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
        }
P
Pilchie 已提交
10122
    }
10123

10124
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
10125
    internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer
10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137
    {
        internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true);
        internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(Hidden01, Hidden02);
            }
        }

10138
        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
10139
        {
10140
            context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation()));
10141 10142
        }

10143
        public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
10144
        {
10145
            context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia);
10146 10147
        }
    }
10148

10149
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
10150
    internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer
P
Pilchie 已提交
10151
    {
10152 10153 10154 10155 10156 10157 10158 10159 10160 10161
        internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(Info01);
            }
        }

10162
        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
10163
        {
10164
            if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword))
10165
            {
10166
                context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation()));
10167 10168 10169
            }
        }

10170
        public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
10171
        {
10172
            context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia);
10173 10174
        }
    }
10175

10176
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
10177
    internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer
10178 10179
    {
        internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true);
P
Pilchie 已提交
10180 10181 10182 10183 10184

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
10185
                return ImmutableArray.Create(Warning01);
P
Pilchie 已提交
10186 10187 10188
            }
        }

10189
        public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
P
Pilchie 已提交
10190
        {
10191 10192 10193 10194 10195 10196
            context.RegisterSymbolAction(
                (symbolContext) =>
                {
                    symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First()));
                },
                SymbolKind.NamedType);
10197 10198
        }
    }
10199

10200
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
10201
    internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer
10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213
    {
        internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true);
        internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(Error01, Error02);
            }
        }

10214
        public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
10215
        {
10216 10217 10218 10219 10220 10221 10222 10223 10224 10225
            context.RegisterSyntaxNodeAction(
                (nodeContext) =>
                {
                    if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword))
                    {
                        nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation()));
                    }
                },
                SyntaxKind.PragmaWarningDirectiveTrivia
                );
10226
        }
P
Pilchie 已提交
10227 10228
    }
}