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

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
V
Vladimir Reshetnikov 已提交
8
using System.IO.Compression;
P
Pilchie 已提交
9 10 11
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
V
Vladimir Reshetnikov 已提交
12
using System.Runtime.Remoting.Metadata.W3cXsd2001;
P
Pilchie 已提交
13 14
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeGen;
15
using Microsoft.CodeAnalysis.Emit;
P
Pilchie 已提交
16 17 18 19 20 21 22 23 24 25
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Test.Utilities
{
    /// <summary>
    /// Base class for all language specific tests.
    /// </summary>
    public abstract partial class CommonTestBase : TestBase
    {
J
jaredpar 已提交
26
        private static ImmutableArray<Emitter> LoadEmitters()
P
Pilchie 已提交
27 28
        {
            var configFileName = Path.GetFileName(Assembly.GetExecutingAssembly().Location) + ".config";
29
            var configFilePath = Path.Combine(Directory.GetCurrentDirectory(), configFileName);
B
beep boop 已提交
30

P
Pilchie 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43
            if (File.Exists(configFilePath))
            {
                var assemblyConfig = XDocument.Load(configFilePath);

                var roslynUnitTestsSection = assemblyConfig.Root.Element("roslyn.unittests");

                if (roslynUnitTestsSection != null)
                {
                    var emitSection = roslynUnitTestsSection.Element("emit");

                    if (emitSection != null)
                    {
                        var methodElements = emitSection.Elements("method");
44
                        var builder = ImmutableArray.CreateBuilder<Emitter>(methodElements.Count());
P
Pilchie 已提交
45 46 47

                        foreach (var method in methodElements)
                        {
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
                            Emitter emitter;
                            try
                            {
                                var asm = Assembly.Load(method.Attribute("assembly").Value);
                                emitter = (Emitter)Delegate.CreateDelegate(typeof(Emitter),
                                    asm.GetType(method.Attribute("type").Value),
                                    method.Attribute("name").Value);
                            }
                            catch
                            {
                                // It is possible and OK for an emitter to fail to load.  This is in fact expected
                                // when only the Open directory is built (as is the case in Github).  When this happens
                                // the ReflectionEmitter won't be present.  In that case we use the single available
                                // Emitter
                                continue;
                            }

                            builder.Add(emitter);
                        }
P
Pilchie 已提交
67

68 69 70
                        if (builder.Count == 0)
                        {
                            throw new Exception("Unable to load any emitter");
P
Pilchie 已提交
71
                        }
72

J
jaredpar 已提交
73
                        return builder.ToImmutableArray();
P
Pilchie 已提交
74 75 76
                    }
                }
            }
J
jaredpar 已提交
77 78

            return ImmutableArray<Emitter>.Empty;
P
Pilchie 已提交
79 80 81 82 83
        }

        internal abstract IEnumerable<IModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public);

        #region Emit
B
beep boop 已提交
84

P
Pilchie 已提交
85 86
        protected abstract Compilation GetCompilationForEmit(
            IEnumerable<string> source,
87
            IEnumerable<MetadataReference> additionalRefs,
88 89
            CompilationOptions options,
            ParseOptions parseOptions);
P
Pilchie 已提交
90

91
        protected abstract CompilationOptions CompilationOptionsReleaseDll { get; }
P
Pilchie 已提交
92 93 94 95 96

        internal delegate CompilationVerifier Emitter(
            CommonTestBase test,
            Compilation compilation,
            IEnumerable<ModuleData> dependencies,
97
            TestEmitters emitters,
P
Pilchie 已提交
98 99 100
            IEnumerable<ResourceDescription> manifestResources,
            SignatureDescription[] expectedSignatures,
            string expectedOutput,
101 102
            Action<PEAssembly, TestEmitters> assemblyValidator,
            Action<IModuleSymbol, TestEmitters> symbolValidator,
P
Pilchie 已提交
103 104 105
            bool collectEmittedAssembly,
            bool verify);

J
jaredpar 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119
        private static ImmutableArray<Emitter> s_emitters;

        private static ImmutableArray<Emitter> Emitters
        {
            get
            {
                if (s_emitters.IsDefault)
                {
                    s_emitters = LoadEmitters();
                }

                return s_emitters;
            }
        }
P
Pilchie 已提交
120 121 122

        internal CompilationVerifier CompileAndVerify(
            string source,
123
            IEnumerable<MetadataReference> additionalRefs = null,
P
Pilchie 已提交
124
            IEnumerable<ModuleData> dependencies = null,
125
            TestEmitters emitters = TestEmitters.All,
126 127 128
            Action<IModuleSymbol, TestEmitters> sourceSymbolValidator = null,
            Action<PEAssembly, TestEmitters> assemblyValidator = null,
            Action<IModuleSymbol, TestEmitters> symbolValidator = null,
P
Pilchie 已提交
129 130 131
            SignatureDescription[] expectedSignatures = null,
            string expectedOutput = null,
            CompilationOptions options = null,
132
            ParseOptions parseOptions = null,
P
Pilchie 已提交
133 134 135 136 137 138 139
            bool collectEmittedAssembly = true,
            bool verify = true)
        {
            return CompileAndVerify(
                sources: new string[] { source },
                additionalRefs: additionalRefs,
                dependencies: dependencies,
140
                emitters: emitters,
P
Pilchie 已提交
141 142 143 144 145 146
                sourceSymbolValidator: sourceSymbolValidator,
                assemblyValidator: assemblyValidator,
                symbolValidator: symbolValidator,
                expectedSignatures: expectedSignatures,
                expectedOutput: expectedOutput,
                options: options,
147
                parseOptions: parseOptions,
P
Pilchie 已提交
148 149 150 151 152 153
                collectEmittedAssembly: collectEmittedAssembly,
                verify: verify);
        }

        internal CompilationVerifier CompileAndVerify(
            string[] sources,
154
            IEnumerable<MetadataReference> additionalRefs = null,
P
Pilchie 已提交
155
            IEnumerable<ModuleData> dependencies = null,
156
            TestEmitters emitters = TestEmitters.All,
157 158 159
            Action<IModuleSymbol, TestEmitters> sourceSymbolValidator = null,
            Action<PEAssembly, TestEmitters> assemblyValidator = null,
            Action<IModuleSymbol, TestEmitters> symbolValidator = null,
P
Pilchie 已提交
160 161 162
            SignatureDescription[] expectedSignatures = null,
            string expectedOutput = null,
            CompilationOptions options = null,
163
            ParseOptions parseOptions = null,
P
Pilchie 已提交
164 165 166 167 168
            bool collectEmittedAssembly = true,
            bool verify = true)
        {
            if (options == null)
            {
169
                options = CompilationOptionsReleaseDll.WithOutputKind((expectedOutput != null) ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary);
P
Pilchie 已提交
170 171
            }

172
            var compilation = GetCompilationForEmit(sources, additionalRefs, options, parseOptions);
P
Pilchie 已提交
173 174 175 176 177

            return this.CompileAndVerify(
                compilation,
                null,
                dependencies,
178
                emitters,
P
Pilchie 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
                sourceSymbolValidator,
                assemblyValidator,
                symbolValidator,
                expectedSignatures,
                expectedOutput,
                collectEmittedAssembly,
                verify);
        }

        internal CompilationVerifier CompileAndVerify(
            Compilation compilation,
            IEnumerable<ResourceDescription> manifestResources = null,
            IEnumerable<ModuleData> dependencies = null,
192
            TestEmitters emitters = TestEmitters.All,
193 194 195
            Action<IModuleSymbol, TestEmitters> sourceSymbolValidator = null,
            Action<PEAssembly, TestEmitters> assemblyValidator = null,
            Action<IModuleSymbol, TestEmitters> symbolValidator = null,
P
Pilchie 已提交
196 197 198 199 200 201 202
            SignatureDescription[] expectedSignatures = null,
            string expectedOutput = null,
            bool collectEmittedAssembly = true,
            bool verify = true)
        {
            Assert.NotNull(compilation);

B
beep boop 已提交
203
            Assert.True(expectedOutput == null ||
P
Pilchie 已提交
204 205 206 207 208 209
                (compilation.Options.OutputKind == OutputKind.ConsoleApplication || compilation.Options.OutputKind == OutputKind.WindowsApplication),
                "Compilation must be executable if output is expected.");

            if (verify)
            {
                // Unsafe code might not verify, so don't try.
210
                var csharpOptions = compilation.Options as CSharp.CSharpCompilationOptions;
P
Pilchie 已提交
211 212 213 214 215 216
                verify = (csharpOptions == null || !csharpOptions.AllowUnsafe);
            }

            if (sourceSymbolValidator != null)
            {
                var module = compilation.Assembly.Modules.First();
217
                sourceSymbolValidator(module, emitters);
P
Pilchie 已提交
218 219
            }

J
jaredpar 已提交
220
            if (Emitters.IsDefaultOrEmpty)
P
Pilchie 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            {
                throw new InvalidOperationException(
                    @"You must specify at least one Emitter.

Example app.config:

<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <roslyn.unittests>
    <emit>
      <method assembly=""SomeAssembly"" type=""SomeClass"" name= ""SomeEmitMethod"" />
    </emit>
  </roslyn.unittests>
</configuration>");
            }

            CompilationVerifier result = null;

J
jaredpar 已提交
239
            foreach (var emit in Emitters)
P
Pilchie 已提交
240 241 242 243
            {
                var verifier = emit(this,
                                    compilation,
                                    dependencies,
244
                                    emitters,
P
Pilchie 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
                                    manifestResources,
                                    expectedSignatures,
                                    expectedOutput,
                                    assemblyValidator,
                                    symbolValidator,
                                    collectEmittedAssembly,
                                    verify);

                if (result == null)
                {
                    result = verifier;
                }
                else
                {
                    // only one emitter should return a verifier
                    Assert.Null(verifier);
                }
            }

J
jaredpar 已提交
264
            // If this fails, it means that more that all emitters failed to return a validator
P
Pilchie 已提交
265 266 267 268 269 270
            // (i.e. none thought that they were applicable for the given input parameters).
            Assert.NotNull(result);

            return result;
        }

271
        private static Action<T, TestEmitters> Translate<T>(Action<T> action)
P
Pilchie 已提交
272 273 274 275 276 277 278 279 280 281
        {
            if (action != null)
            {
                return (module, _) => action(module);
            }
            else
            {
                return null;
            }
        }
B
beep boop 已提交
282

283
        internal CompilationVerifier CompileAndVerifyFieldMarshal(string source, Dictionary<string, byte[]> expectedBlobs, bool isField = true, TestEmitters emitters = TestEmitters.All)
P
Pilchie 已提交
284 285
        {
            return CompileAndVerifyFieldMarshal(
B
beep boop 已提交
286 287 288
                source,
                (s, _omitted1, _omitted2) =>
                {
P
Pilchie 已提交
289
                    Assert.True(expectedBlobs.ContainsKey(s), "Expecting marshalling blob for " + (isField ? "field " : "parameter ") + s);
B
beep boop 已提交
290 291
                    return expectedBlobs[s];
                },
P
Pilchie 已提交
292
                isField,
293
                emitters);
P
Pilchie 已提交
294 295
        }

296
        internal CompilationVerifier CompileAndVerifyFieldMarshal(string source, Func<string, PEAssembly, TestEmitters, byte[]> getExpectedBlob, bool isField = true, TestEmitters emitters = TestEmitters.All)
P
Pilchie 已提交
297
        {
298
            return CompileAndVerify(source, emitters: emitters, options: CompilationOptionsReleaseDll, assemblyValidator: (assembly, options) => MarshalAsMetadataValidator(assembly, getExpectedBlob, options, isField));
P
Pilchie 已提交
299 300
        }

301
        static internal void RunValidators(CompilationVerifier verifier, TestEmitters emitters, Action<PEAssembly, TestEmitters> assemblyValidator, Action<IModuleSymbol, TestEmitters> symbolValidator)
P
Pilchie 已提交
302 303 304 305 306
        {
            if (assemblyValidator != null)
            {
                using (var emittedMetadata = AssemblyMetadata.Create(verifier.GetAllModuleMetadata()))
                {
307
                    assemblyValidator(emittedMetadata.GetAssembly(), emitters);
P
Pilchie 已提交
308 309 310 311 312 313 314
                }
            }

            if (symbolValidator != null)
            {
                var peModuleSymbol = verifier.GetModuleSymbolForEmittedImage();
                Debug.Assert(peModuleSymbol != null);
315
                symbolValidator(peModuleSymbol, emitters);
P
Pilchie 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            }
        }

        // The purpose of this method is simply to check that the signature of the 'Emit' method 
        // matches the 'Emitter' delegate type that it will be dynamically assigned to...
        // That is, we will catch mismatches due to changes in the signatures at compile time instead
        // of getting an opaque ArgumentException from the call to CreateDelegate.
        private static void TestEmitSignature()
        {
            Emitter emitter = Emit;
        }

        static internal CompilationVerifier Emit(
            CommonTestBase test,
            Compilation compilation,
            IEnumerable<ModuleData> dependencies,
332
            TestEmitters emitters,
P
Pilchie 已提交
333 334 335
            IEnumerable<ResourceDescription> manifestResources,
            SignatureDescription[] expectedSignatures,
            string expectedOutput,
336 337
            Action<PEAssembly, TestEmitters> assemblyValidator,
            Action<IModuleSymbol, TestEmitters> symbolValidator,
P
Pilchie 已提交
338 339 340 341 342 343
            bool collectEmittedAssembly,
            bool verify)
        {
            CompilationVerifier verifier = null;

            // We only handle CCI emit here for now...
344
            if (emitters != TestEmitters.RefEmit)
P
Pilchie 已提交
345 346 347
            {
                verifier = new CompilationVerifier(test, compilation, dependencies);

348
                verifier.Emit(expectedOutput, manifestResources, verify, expectedSignatures);
P
Pilchie 已提交
349

350
                // We're dual-purposing emitters here.  In this context, it
P
Pilchie 已提交
351
                // tells the validator the version of Emit that is calling it. 
352
                RunValidators(verifier, TestEmitters.CCI, assemblyValidator, symbolValidator);
P
Pilchie 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
            }

            return verifier;
        }

        /// <summary>
        /// Reads content of the specified file.
        /// </summary>
        /// <param name="path">The path to the file.</param>
        /// <returns>Read-only binary data read from the file.</returns>
        public static ImmutableArray<byte> ReadFromFile(string path)
        {
            return ImmutableArray.Create<byte>(File.ReadAllBytes(path));
        }

        internal static void EmitILToArray(
            string ilSource,
            bool appendDefaultHeader,
            bool includePdb,
            out ImmutableArray<byte> assemblyBytes,
            out ImmutableArray<byte> pdbBytes)
        {
            string assemblyPath;
            string pdbPath;
            SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader, includePdb, out assemblyPath, out pdbPath);

            Assert.NotNull(assemblyPath);
            Assert.Equal(pdbPath != null, includePdb);

            using (new DisposableFile(assemblyPath))
            {
                assemblyBytes = ReadFromFile(assemblyPath);
            }

            if (pdbPath != null)
            {
                using (new DisposableFile(pdbPath))
                {
                    pdbBytes = ReadFromFile(pdbPath);
                }
            }
            else
            {
                pdbBytes = default(ImmutableArray<byte>);
            }
        }

        internal static MetadataReference CompileIL(string ilSource, bool appendDefaultHeader = true, bool embedInteropTypes = false)
        {
            ImmutableArray<byte> assemblyBytes;
            ImmutableArray<byte> pdbBytes;
            EmitILToArray(ilSource, appendDefaultHeader, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
405
            return AssemblyMetadata.CreateFromImage(assemblyBytes).GetReference(embedInteropTypes: embedInteropTypes);
P
Pilchie 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419
        }

        internal static MetadataReference CreateReflectionEmitAssembly(Action<ModuleBuilder> create)
        {
            using (var file = new DisposableFile(extension: ".dll"))
            {
                var name = Path.GetFileName(file.Path);
                var appDomain = AppDomain.CurrentDomain;
                var assembly = appDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Save, Path.GetDirectoryName(file.Path));
                var module = assembly.DefineDynamicModule(CommonTestBase.GetUniqueName(), name);
                create(module);
                assembly.Save(name);

                var image = CommonTestBase.ReadFromFile(file.Path);
420
                return MetadataReference.CreateFromImage(image);
P
Pilchie 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
            }
        }

        #endregion

        #region Compilation Creation Helpers

        protected CSharp.CSharpCompilation CreateCSharpCompilation(
            XCData code,
            CSharp.CSharpParseOptions parseOptions = null,
            CSharp.CSharpCompilationOptions compilationOptions = null,
            string assemblyName = null,
            IEnumerable<MetadataReference> referencedAssemblies = null)
        {
            return CreateCSharpCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null);
        }

        protected CSharp.CSharpCompilation CreateCSharpCompilation(
            string assemblyName,
            XCData code,
            CSharp.CSharpParseOptions parseOptions = null,
            CSharp.CSharpCompilationOptions compilationOptions = null,
            IEnumerable<MetadataReference> referencedAssemblies = null,
            IEnumerable<Compilation> referencedCompilations = null)
        {
            return CreateCSharpCompilation(
                assemblyName,
                code.Value,
                parseOptions,
                compilationOptions,
                referencedAssemblies,
                referencedCompilations);
        }

A
angocke 已提交
455
        protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation(
P
Pilchie 已提交
456
            XCData code,
A
angocke 已提交
457 458
            VisualBasic.VisualBasicParseOptions parseOptions = null,
            VisualBasic.VisualBasicCompilationOptions compilationOptions = null,
P
Pilchie 已提交
459 460 461 462 463 464
            string assemblyName = null,
            IEnumerable<MetadataReference> referencedAssemblies = null)
        {
            return CreateVisualBasicCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null);
        }

A
angocke 已提交
465
        protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation(
P
Pilchie 已提交
466 467
            string assemblyName,
            XCData code,
A
angocke 已提交
468 469
            VisualBasic.VisualBasicParseOptions parseOptions = null,
            VisualBasic.VisualBasicCompilationOptions compilationOptions = null,
P
Pilchie 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
            IEnumerable<MetadataReference> referencedAssemblies = null,
            IEnumerable<Compilation> referencedCompilations = null)
        {
            return CreateVisualBasicCompilation(
                assemblyName,
                code.Value,
                parseOptions,
                compilationOptions,
                referencedAssemblies,
                referencedCompilations);
        }

        protected CSharp.CSharpCompilation CreateCSharpCompilation(
            string code,
            CSharp.CSharpParseOptions parseOptions = null,
            CSharp.CSharpCompilationOptions compilationOptions = null,
            string assemblyName = null,
            IEnumerable<MetadataReference> referencedAssemblies = null)
        {
            return CreateCSharpCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null);
        }

        protected CSharp.CSharpCompilation CreateCSharpCompilation(
            string assemblyName,
            string code,
            CSharp.CSharpParseOptions parseOptions = null,
            CSharp.CSharpCompilationOptions compilationOptions = null,
            IEnumerable<MetadataReference> referencedAssemblies = null,
            IEnumerable<Compilation> referencedCompilations = null)
        {
            if (assemblyName == null)
            {
                assemblyName = GetUniqueName();
            }
B
beep boop 已提交
504

P
Pilchie 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
            if (parseOptions == null)
            {
                parseOptions = CSharp.CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None);
            }

            if (compilationOptions == null)
            {
                compilationOptions = new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            }

            var references = new List<MetadataReference>();
            if (referencedAssemblies == null)
            {
                references.Add(MscorlibRef);
                references.Add(SystemRef);
                references.Add(SystemCoreRef);
                //TODO: references.Add(MsCSRef);
                references.Add(SystemXmlRef);
                references.Add(SystemXmlLinqRef);
            }
            else
            {
                references.AddRange(referencedAssemblies);
            }

            AddReferencedCompilations(referencedCompilations, references);

            var tree = CSharp.SyntaxFactory.ParseSyntaxTree(code, options: parseOptions);

            return CSharp.CSharpCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions);
        }

A
angocke 已提交
537
        protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation(
P
Pilchie 已提交
538
            string code,
A
angocke 已提交
539 540
            VisualBasic.VisualBasicParseOptions parseOptions = null,
            VisualBasic.VisualBasicCompilationOptions compilationOptions = null,
P
Pilchie 已提交
541 542 543 544 545 546
            string assemblyName = null,
            IEnumerable<MetadataReference> referencedAssemblies = null)
        {
            return CreateVisualBasicCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null);
        }

A
angocke 已提交
547
        protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation(
P
Pilchie 已提交
548 549
            string assemblyName,
            string code,
A
angocke 已提交
550 551
            VisualBasic.VisualBasicParseOptions parseOptions = null,
            VisualBasic.VisualBasicCompilationOptions compilationOptions = null,
P
Pilchie 已提交
552 553 554 555 556 557 558
            IEnumerable<MetadataReference> referencedAssemblies = null,
            IEnumerable<Compilation> referencedCompilations = null)
        {
            if (assemblyName == null)
            {
                assemblyName = GetUniqueName();
            }
B
beep boop 已提交
559

P
Pilchie 已提交
560 561
            if (parseOptions == null)
            {
A
angocke 已提交
562
                parseOptions = VisualBasic.VisualBasicParseOptions.Default;
P
Pilchie 已提交
563 564 565 566
            }

            if (compilationOptions == null)
            {
A
angocke 已提交
567
                compilationOptions = new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
P
Pilchie 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
            }

            var references = new List<MetadataReference>();
            if (referencedAssemblies == null)
            {
                references.Add(MscorlibRef);
                references.Add(SystemRef);
                references.Add(SystemCoreRef);
                references.Add(MsvbRef);
                references.Add(SystemXmlRef);
                references.Add(SystemXmlLinqRef);
            }
            else
            {
                references.AddRange(referencedAssemblies);
            }

            AddReferencedCompilations(referencedCompilations, references);

A
angocke 已提交
587
            var tree = VisualBasic.VisualBasicSyntaxTree.ParseText(code, options: parseOptions);
P
Pilchie 已提交
588

A
angocke 已提交
589
            return VisualBasic.VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions);
P
Pilchie 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602
        }

        private void AddReferencedCompilations(IEnumerable<Compilation> referencedCompilations, List<MetadataReference> references)
        {
            if (referencedCompilations != null)
            {
                foreach (var referencedCompilation in referencedCompilations)
                {
                    references.Add(referencedCompilation.EmitToImageReference());
                }
            }
        }

V
Vladimir Reshetnikov 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        /// <summary>
        /// Creates a reference to a single-module assembly or a standalone module stored in memory
        /// from a hex-encoded byte stream representing a gzipped assembly image.
        /// </summary>
        /// <param name="image">
        /// A string containing a hex-encoded byte stream representing a gzipped assembly image. 
        /// Hex digits are case-insensitive and can be separated by spaces or newlines.
        /// Cannot be null.
        /// </param>
        /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param>
        /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param>
        /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param>
        protected internal PortableExecutableReference CreateMetadataReferenceFromHexGZipImage(
            string image,
            MetadataReferenceProperties properties = default(MetadataReferenceProperties),
            DocumentationProvider documentation = null,
            string filePath = null)
        {
B
beep boop 已提交
621
            if (image == null)
V
Vladimir Reshetnikov 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635
            {
                throw new ArgumentNullException(nameof(image));
            }

            using (var compressed = new MemoryStream(SoapHexBinary.Parse(image).Value))
            using (var gzipStream = new GZipStream(compressed, CompressionMode.Decompress))
            using (var uncompressed = new MemoryStream())
            {
                gzipStream.CopyTo(uncompressed);
                uncompressed.Position = 0;
                return MetadataReference.CreateFromStream(uncompressed, properties, documentation, filePath);
            }
        }

P
Pilchie 已提交
636 637 638 639
        #endregion

        #region IL Verification

640
        internal abstract string VisualizeRealIL(IModuleSymbol peModule, CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers);
P
Pilchie 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

        #endregion

        #region Other Helpers
        internal static ModulePropertiesForSerialization GetDefaultModulePropertiesForSerialization()
        {
            return new ModulePropertiesForSerialization(
                persistentIdentifier: default(Guid),
                fileAlignment: ModulePropertiesForSerialization.DefaultFileAlignment32Bit,
                targetRuntimeVersion: "v4.0.30319",
                platform: Platform.AnyCpu,
                trackDebugData: false,
                baseAddress: ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit,
                sizeOfHeapReserve: ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit,
                sizeOfHeapCommit: ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit,
                sizeOfStackReserve: ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit,
                sizeOfStackCommit: ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit,
                enableHighEntropyVA: true,
                strongNameSigned: false,
                configureToExecuteInAppContainer: false,
                subsystemVersion: default(SubsystemVersion));
        }
        #endregion
    }
}