コード例 #1
0
 private CompilationVerifier CompileAndVerifyRef(
     string source,
     string expectedOutput = null,
     MetadataReference[] additionalRefs = null,
     IEnumerable<ModuleData> dependencies = null,
     Action<ModuleSymbol> sourceSymbolValidator = null,
     Action<PEAssembly> assemblyValidator = null,
     Action<ModuleSymbol> symbolValidator = null,
     SignatureDescription[] expectedSignatures = null,
     CSharpCompilationOptions options = null,
     bool verify = true)
 {
     return CompileAndVerifyExperimental(
         source,
         MessageID.IDS_FeatureRefLocalsReturns,
         expectedOutput,
         additionalRefs,
         dependencies,
         sourceSymbolValidator,
         assemblyValidator,
         symbolValidator,
         expectedSignatures,
         options,
         verify);
 }
        internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null)
        {
            // The mechanism of this test is: we build the bound tree for the code passed in and then extract
            // from it the nodes that describe the method symbols. We then compare the description of
            // the symbols given to the comment that follows the call.

            var mscorlibRef = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib");
            var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray<MetadataReference>());

            var compilation = CreateCompilation(source, references, TestOptions.ReleaseDll);

            var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var diagnostics = new DiagnosticBag();
            var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics);
            var tree = BoundTreeDumperNodeProducer.MakeTree(block);
            var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value)
                .Where(x => x.Text == "method" && x.Value != null)
                .Select(x => x.Value)
                .ToArray());

            // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray();

            var expected = string.Join("\n", source
                .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries)
                .Where(x => x.Contains("//-"))
                .Select(x => x.Substring(x.IndexOf("//-") + 3))
                .ToArray());

            AssertEx.Equal(expected, results);
        }
コード例 #3
0
ファイル: CodeGenDynamicTests.cs プロジェクト: nagyist/roslyn
        private CompilationVerifier CompileAndVerifyIL(string source, string methodName, string expectedOptimizedIL = null, string expectedUnoptimizedIL = null, 
            MetadataReference[] references = null)
        {
            references = references ?? new[] { SystemCoreRef, CSharpRef };

            // verify that we emit correct optimized and unoptimized IL:
            var unoptimizedCompilation = CreateCompilationWithMscorlib45(source, references, compOptions: TestOptions.UnsafeDll.WithMetadataImportOptions(MetadataImportOptions.All).WithOptimizations(false));
            var optimizedCompilation = CreateCompilationWithMscorlib45(source, references, compOptions: TestOptions.UnsafeDll.WithMetadataImportOptions(MetadataImportOptions.All).WithOptimizations(true));

            var unoptimizedVerifier = CompileAndVerify(unoptimizedCompilation);
            var optimizedVerifier = CompileAndVerify(optimizedCompilation);

            // check what IL we emit exactly:
            if (expectedUnoptimizedIL != null)
            {
                unoptimizedVerifier.VerifyIL(methodName, expectedUnoptimizedIL, realIL: true);
            }

            if (expectedOptimizedIL != null)
            {
                optimizedVerifier.VerifyIL(methodName, expectedOptimizedIL, realIL: true);
            }

            // return null if ambiguous
            return (expectedUnoptimizedIL != null) ^ (expectedOptimizedIL != null) ? (unoptimizedVerifier ?? optimizedVerifier) : null;
        }
コード例 #4
0
ファイル: CodeGenDynamicTests.cs プロジェクト: nemec/roslyn
        private CompilationVerifier CompileAndVerifyIL(
            string source,
            string methodName,
            string expectedOptimizedIL = null,
            string expectedUnoptimizedIL = null,
            MetadataReference[] references = null,
            bool allowUnsafe = false,
            [CallerFilePath]string callerPath = null,
            [CallerLineNumber]int callerLine = 0)
        {
            references = references ?? new[] { SystemCoreRef, CSharpRef };

            // verify that we emit correct optimized and unoptimized IL:
            var unoptimizedCompilation = CreateCompilationWithMscorlib45(source, references, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe));
            var optimizedCompilation = CreateCompilationWithMscorlib45(source, references, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe));

            var unoptimizedVerifier = CompileAndVerify(unoptimizedCompilation);
            var optimizedVerifier = CompileAndVerify(optimizedCompilation);

            // check what IL we emit exactly:
            if (expectedUnoptimizedIL != null)
            {
                unoptimizedVerifier.VerifyIL(methodName, expectedUnoptimizedIL, realIL: true, sequencePoints: methodName, callerPath: callerPath, callerLine: callerLine);
            }

            if (expectedOptimizedIL != null)
            {
                optimizedVerifier.VerifyIL(methodName, expectedOptimizedIL, realIL: true, callerPath: callerPath, callerLine: callerLine);
            }

            // return null if ambiguous
            return (expectedUnoptimizedIL != null) ^ (expectedOptimizedIL != null) ? (unoptimizedVerifier ?? optimizedVerifier) : null;
        }
コード例 #5
0
        internal static AssemblySymbol[] GetSymbolsForReferences(
            CSharpCompilation[] compilations = null,
            byte[][] bytes = null,
            MetadataReference[] mrefs = null,
            CSharpCompilationOptions options = null)
        {
            var refs = new List<MetadataReference>();

            if (compilations != null)
            {
                foreach (var c in compilations)
                {
                    refs.Add(new CSharpCompilationReference(c));
                }
            }

            if (bytes != null)
            {
                foreach (var b in bytes)
                {
                    refs.Add(new MetadataImageReference(b.AsImmutableOrNull()));
                }
            }

            if (mrefs != null)
            {
                refs.AddRange(mrefs);
            }

            var tc1 = CSharpCompilation.Create(assemblyName: "Dummy", options: options ?? TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[0], references: refs);

           return (from @ref in refs select tc1.GetReferencedAssemblySymbol(@ref)).ToArray();
        }
コード例 #6
0
 internal static Compilation CreateCompilation(string source, MetadataReference[] references, string assemblyName, CSharpCompilationOptions options = null)
 {
     return CSharpCompilation.Create(
         assemblyName,
         new[] { SyntaxFactory.ParseSyntaxTree(source) },
         references,
         options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
 }
コード例 #7
0
        private static string GetMetadataReferenceFilePath(MetadataReference metadataReference)
        {
            var executabeReference = metadataReference as PortableExecutableReference;
            if (executabeReference == null)
            {
                return null;
            }

            return executabeReference.FilePath;
        }
コード例 #8
0
        public Checksum CreateChecksum(MetadataReference reference, CancellationToken cancellationToken)
        {
            var portable = reference as PortableExecutableReference;
            if (portable != null)
            {
                return CreatePortableExecutableReferenceChecksum(portable, cancellationToken);
            }

            throw ExceptionUtilities.UnexpectedValue(reference.GetType());
        }
コード例 #9
0
ファイル: ServicesTestBase.cs プロジェクト: Rickinio/roslyn
 public static Solution AddProjectWithMetadataReferences(Solution solution, string projectName, string languageName, string code, MetadataReference metadataReference, params ProjectId[] projectReferences)
 {
     var suffix = languageName == LanguageNames.CSharp ? "cs" : "vb";
     var pid = ProjectId.CreateNewId();
     var did = DocumentId.CreateNewId(pid);
     var pi = ProjectInfo.Create(
         pid,
         VersionStamp.Default,
         projectName,
         projectName,
         languageName,
         metadataReferences: new[] { metadataReference },
         projectReferences: projectReferences.Select(p => new ProjectReference(p)));
     return solution.AddProject(pi).AddDocument(did, $"{projectName}.{suffix}", SourceText.From(code));
 }
コード例 #10
0
        public void WriteTo(MetadataReference reference, ObjectWriter writer, CancellationToken cancellationToken)
        {
            var portable = reference as PortableExecutableReference;
            if (portable != null)
            {
                var supportTemporaryStorage = portable as ISupportTemporaryStorage;
                if (supportTemporaryStorage != null)
                {
                    if (TryWritePortableExecutableReferenceBackedByTemporaryStorageTo(supportTemporaryStorage, writer, cancellationToken))
                    {
                        return;
                    }
                }

                WritePortableExecutableReferenceTo(portable, writer, cancellationToken);
                return;
            }

            throw ExceptionUtilities.UnexpectedValue(reference.GetType());
        }
コード例 #11
0
        internal ModuleInstance(
            MetadataReference metadataReference,
            ModuleMetadata moduleMetadata,
            Guid moduleVersionId,
            byte[] fullImage,
            byte[] metadataOnly,
            object symReader,
            bool includeLocalSignatures)
        {
            Debug.Assert((fullImage == null) || (fullImage.Length > metadataOnly.Length));

            this.MetadataReference = metadataReference;
            this.ModuleMetadata = moduleMetadata;
            this.ModuleVersionId = moduleVersionId;
            this.FullImage = fullImage;
            this.MetadataOnly = metadataOnly;
            this.MetadataHandle = GCHandle.Alloc(metadataOnly, GCHandleType.Pinned);
            this.SymReader = symReader; // should be non-null if and only if there are symbols
            _includeLocalSignatures = includeLocalSignatures;
        }
コード例 #12
0
        public void AppConfig1()
        {
            var references = new MetadataReference[]
            {
                TestReferences.NetFx.v4_0_30319.mscorlib,
                TestReferences.NetFx.v4_0_30319.System,
                TestReferences.NetFx.silverlight_v5_0_5_0.System
            };

            var compilation = CreateCompilation(
                new[] { Parse("") },
                references,
                options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default));

            compilation.VerifyDiagnostics(
                // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references.
                Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll", "System.v5.0.5.0_silverlight.dll"));

            var appConfig = new MemoryStream(Encoding.UTF8.GetBytes(
            @"<?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>"));

            var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig);

            compilation = CreateCompilation(
                new[] { Parse("") },
                references,
                options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer));

            compilation.VerifyDiagnostics();
        }
コード例 #13
0
 public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity)
 {
     diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location,
         identity.Name,
         reference.Display ?? identity.GetDisplayName());
 }
コード例 #14
0
 bool ICompilationFactoryService.IsCompilationReference(MetadataReference reference)
 {
     return reference is CompilationReference;
 }
コード例 #15
0
        public void TestGeneratorsCantTargetNetFramework()
        {
            var directory = Temp.CreateDirectory();

            // core
            var errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETCoreApp,Version=v5.0");

            Assert.Empty(errors);

            // netstandard
            errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETStandard,Version=v2.0");
            Assert.Empty(errors);

            // no target
            errors = buildAndLoadGeneratorAndReturnAnyErrors(targetFramework: null);
            Assert.Empty(errors);

            // framework
            errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETFramework,Version=v4.7.2");
            Assert.Equal(2, errors.Count);
            Assert.Equal(
                AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework,
                errors.First().ErrorCode
                );

            List <AnalyzerLoadFailureEventArgs> buildAndLoadGeneratorAndReturnAnyErrors(
                string?targetFramework
                )
            {
                string targetFrameworkAttributeText =
                    targetFramework is object
                    ?$"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]"
                    : string.Empty;

                string generatorSource =
                    $@"
using Microsoft.CodeAnalysis;

{targetFrameworkAttributeText}

[Generator]
public class Generator : ISourceGenerator
{{
            public void Execute(GeneratorExecutionContext context) {{ }}
            public void Initialize(GeneratorInitializationContext context) {{ }}
 }}";

                var directory     = Temp.CreateDirectory();
                var generatorPath = Path.Combine(directory.Path, "generator.dll");

                var compilation = CSharpCompilation.Create(
                    $"generator_{targetFramework}",
                    new[] { CSharpSyntaxTree.ParseText(generatorSource) },
                    TargetFrameworkUtil.GetReferences(
                        TargetFramework.Standard,
                        new[]
                {
                    MetadataReference.CreateFromAssemblyInternal(
                        typeof(ISourceGenerator).Assembly
                        )
                }
                        ),
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    );

                compilation.VerifyDiagnostics();
                var result = compilation.Emit(generatorPath);

                Assert.True(result.Success);

                AnalyzerFileReference reference            = CreateAnalyzerFileReference(generatorPath);
                List <AnalyzerLoadFailureEventArgs> errors =
                    new List <AnalyzerLoadFailureEventArgs>();

                void errorHandler(object?o, AnalyzerLoadFailureEventArgs e) => errors.Add(e);

                reference.AnalyzerLoadFailed += errorHandler;
                var builder = ImmutableArray.CreateBuilder <ISourceGenerator>();

                reference.AddGenerators(builder, LanguageNames.CSharp);
                reference.AnalyzerLoadFailed -= errorHandler;

                if (errors.Count > 0)
                {
                    Assert.Empty(builder);
                }
                else
                {
                    Assert.Single(builder);
                }
                return(errors);
            }
        }
コード例 #16
0
        public override Type Generate(IInterceptor interceptor, Type baseType, Type handlerType, params Type[] additionalInterfaceTypes)
        {
            if (interceptor == null)
            {
                throw new ArgumentNullException(nameof(interceptor));
            }

            if ((handlerType != null) && (typeof(IInterceptionHandler).IsAssignableFrom(handlerType) == false))
            {
                throw new ArgumentException($"Handler type is not an {typeof(IInterceptionHandler)}", nameof(handlerType));
            }

            if ((handlerType != null) && (handlerType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, new ParameterModifier[0]) == null))
            {
                throw new ArgumentException($"Handler type {handlerType} does not have a public parameterless constructor");
            }

            if ((baseType == typeof(InterfaceProxy)) || (baseType == null))
            {
                if (additionalInterfaceTypes.Any(x => x.IsInterface == false))
                {
                    throw new ArgumentNullException("The target interface is missing", nameof(additionalInterfaceTypes));
                }
            }

            if (baseType == null)
            {
                baseType = typeof(object);
            }

            var isInterface = (baseType == interfaceProxyType);
            var types = new[] { baseType, handlerType }.Concat(additionalInterfaceTypes).Distinct();
            var typeName = ((isInterface) ? additionalInterfaceTypes.First().Name : baseType.Name) + "_Dynamic";

            var builder = new StringBuilder();

            foreach (var @namespace in types.Where(x => x != null).Select(x => x.Namespace).Distinct().OrderBy(x => x))
            {
                builder.AppendFormat("using {0};\r\n", @namespace);
            }

            //default namespaces
            builder.AppendFormat("using System;\r\n");
            builder.AppendFormat("using System.Linq;\r\n");
            builder.AppendFormat("using System.Reflection;\r\n");

            builder.AppendFormat("namespace {0} {{\r\n", baseType.Namespace);

            this.BuildClass(builder, typeName, baseType, additionalInterfaceTypes, handlerType);

            this.BuildConstructors(baseType, typeName, builder, isInterface);

            this.BuildMethods(baseType, additionalInterfaceTypes, builder, isInterface);

            this.BuildEvents(baseType, additionalInterfaceTypes, builder, isInterface);

            this.BuildProperties(baseType, additionalInterfaceTypes, builder, isInterface);

            builder.Append("}\r\n");        //class

            builder.Append("}\r\n");        //namespace

            var syntaxTree   = CSharpSyntaxTree.ParseText(builder.ToString());
            var assemblyName = Path.GetRandomFileName();

            var references = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(this.GetType().Assembly.Location),
                MetadataReference.CreateFromFile(baseType.Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Queryable).Assembly.Location),     //System.Linq.Queryable
                MetadataReference.CreateFromFile(typeof(IQueryable <>).Assembly.Location), //System.Linq.Expressions
                MetadataReference.CreateFromFile(typeof(Lazy <,>).Assembly.Location),      //System.Runtime
                MetadataReference.CreateFromFile(typeof(Object).Assembly.Location),        //System.Private.CoreLib
                MetadataReference.CreateFromFile(typeof(Console).Assembly.Location),       //System.Console
                MetadataReference.CreateFromFile(Assembly.Load("System.Linq").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.ObjectModel").Location),
                MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location)
            };

            if (handlerType != null)
            {
                references.Add(MetadataReference.CreateFromFile(handlerType.Assembly.Location));
            }

            references.AddRange((additionalInterfaceTypes ?? new Type[0]).Select(type => MetadataReference.CreateFromFile(type.GetTypeInfo().Assembly.Location)));

            var compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (result.Success == true)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    var assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
                    var type     = assembly.GetExportedTypes().First();

                    return(type);
                }
                else
                {
                    var failures     = result.Diagnostics.Where(diagnostic => (diagnostic.IsWarningAsError == true) || (diagnostic.Severity == DiagnosticSeverity.Error));
                    var errorMessage = string.Join(Environment.NewLine, failures.Select(x => x.GetMessage()));
                    throw new InvalidOperationException(errorMessage);
                }
            }
        }
コード例 #17
0
 internal static ModuleInstance ToModuleInstance(this MetadataReference reference)
 {
     return(ModuleInstance.Create((PortableExecutableReference)reference));
 }
コード例 #18
0
        private static async Task RunTest(string code, string?expectedMessage)
        {
            TextSpan?GetExpectedSpan()
            {
                var code2 = code.Replace("*", "");

                var indexOfFirstBar = code2.IndexOf("|", StringComparison.InvariantCulture);

                if (indexOfFirstBar == -1)
                {
                    return(null);
                }

                var indexOfSecondBar = code2.IndexOf("|", indexOfFirstBar + 1, StringComparison.InvariantCulture);

                if (indexOfSecondBar == -1)
                {
                    return(null);
                }

                return(TextSpan.FromBounds(indexOfFirstBar, indexOfSecondBar - 1));
            }

            var position = code.Replace("|", "").IndexOf("*");

            var expectedSpan = GetExpectedSpan();

            var workspace = new AdhocWorkspace();

            var solution = workspace.CurrentSolution;

            var projectId = ProjectId.CreateNewId();

            solution = solution.AddProject(projectId, "Project1", "Project1", LanguageNames.CSharp);

            var project = solution.GetProject(projectId);

            project = project.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));

            var document = project.AddDocument("File1.cs", code.Replace("|", "").Replace("*", ""));

            var result = await SumTypeQuickInfoSource.CalculateQuickInfo(
                document,
                position, CancellationToken.None);


            if (!expectedSpan.HasValue)
            {
                //We don't expect a quick info message

                if (result.HasValue)
                {
                    throw new Exception("Unexpectedly, a quick info message was returned: " + result.Value.message);
                }

                return;
            }

            if (expectedMessage is null)
            {
                throw new Exception("Error in test, an expected message should be specified");
            }

            if (!result.HasValue)
            {
                throw new Exception("Unexpectedly, there was no quick info message returned");
            }

            var(message, span) = result.Value;

            Assert.AreEqual(expectedSpan.Value, span);

            Assert.AreEqual(expectedMessage, message);
        }
コード例 #19
0
ファイル: ProxyGenerator.cs プロジェクト: zhangwenquan/moq
        /// <summary>
        /// Generates proxies by discovering proxy factory method invocations in the given
        /// source documents.
        /// </summary>
        /// <param name="workspace">Creating a workspace is typically a bit heavy because of the MEF discovery,
        /// so this argument allows reusing a previously created one across multiple calls.</param>
        /// <param name="languageName">The language name to generate code for, such as 'C#' or 'Visual Basic'. See <see cref="LanguageNames"/>.</param>
        /// <param name="references">The metadata references to use when analyzing the <paramref name="sources"/>.</param>
        /// <param name="sources">The source documents to analyze to discover proxy usage.</param>
        /// <param name="additionalInterfaces">Additional interfaces (by full type name) that should be implemented by generated proxies.</param>
        /// <param name="additionalProxies">Additional types (by full type name) that should be proxied.</param>
        /// <param name="cancellationToken">Cancellation token to cancel the generation process.</param>
        /// <returns>An immutable array of the generated proxies as <see cref="Document"/> instances.</returns>
        public async Task <ImmutableArray <Document> > GenerateProxiesAsync(
            AdhocWorkspace workspace,
            string languageName,
            ImmutableArray <string> references,
            ImmutableArray <string> sources,
            ImmutableArray <string> additionalInterfaces,
            ImmutableArray <string> additionalProxies,
            CancellationToken cancellationToken)
        {
            var options = languageName == LanguageNames.CSharp ?
                          (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) :
                          (CompilationOptions) new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict: OptionStrict.On);

            var project = workspace.AddProject(ProjectInfo.Create(
                                                   ProjectId.CreateNewId(),
                                                   VersionStamp.Create(),
                                                   "pgen",
                                                   "pgen.dll",
                                                   languageName,
                                                   compilationOptions: options,
                                                   metadataReferences: references
                                                   .Select(path => MetadataReference.CreateFromFile(path))));

            foreach (var source in sources)
            {
                var document = workspace.AddDocument(DocumentInfo.Create(
                                                         DocumentId.CreateNewId(project.Id),
                                                         Path.GetFileName(source),
                                                         filePath: Path.GetTempFileName(),
                                                         loader: TextLoader.From(TextAndVersion.Create(SourceText.From(File.ReadAllText(source)), VersionStamp.Create()))));

                project = document.Project;
            }

            var compilation = await project.GetCompilationAsync();

            var additionalInterfaceSymbols = new List <ITypeSymbol>();

            foreach (var additionalInterface in additionalInterfaces)
            {
                var additionalSymbol = compilation.GetTypeByMetadataName(additionalInterface) ??
                                       // TODO: improve reporting
                                       throw new ArgumentException(additionalInterface);

                additionalInterfaceSymbols.Add(additionalSymbol);
            }

            var additionalProxySymbols = new List <ITypeSymbol>();

            foreach (var additionalProxy in additionalProxies)
            {
                var additionalSymbol = compilation.GetTypeByMetadataName(additionalProxy) ??
                                       // TODO: improve reporting
                                       throw new ArgumentException(additionalProxy);

                additionalProxySymbols.Add(additionalSymbol);
            }

            var discoverer = new ProxyDiscoverer();
            var proxies    = await discoverer.DiscoverProxiesAsync(project, cancellationToken);

            if (additionalProxySymbols.Count != 0)
            {
                var set = new HashSet <ImmutableArray <ITypeSymbol> >(proxies, StructuralComparer <ImmutableArray <ITypeSymbol> > .Default);
                foreach (var additionalProxySymbol in additionalProxySymbols)
                {
                    // Adding to the set an existing item will no-op.
                    set.Add(ImmutableArray.Create(additionalProxySymbol));
                }

                // No need to ass the comparer since we've already ensured uniqueness above.
                proxies = set.ToImmutableHashSet();
            }

            var documents  = new List <Document>(proxies.Count);
            var additional = additionalInterfaceSymbols.ToImmutableArray();

            foreach (var proxy in proxies)
            {
                // NOTE: we add the additional interfaces at this point, so that they affect both the
                // originally discovered proxies, as well as the additional proxy types explicitly
                // requested.
                documents.Add(await GenerateProxyAsync(workspace, project, cancellationToken, proxy, additional));
            }

            return(documents.ToImmutableArray());
        }
コード例 #20
0
ファイル: Translator.Build.cs プロジェクト: zendbit/Bridge
        public virtual void BuildAssembly()
        {
            this.Log.Info("Building assembly...");

            var            compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var            parseOptions       = new CSharpParseOptions(LanguageVersion.CSharp7_2, Microsoft.CodeAnalysis.DocumentationMode.Parse, SourceCodeKind.Regular, this.DefineConstants);
            var            files            = this.SourceFiles;
            IList <string> referencesPathes = null;
            var            baseDir          = Path.GetDirectoryName(this.Location);

            if (!this.FolderMode)
            {
                XDocument  projDefinition = XDocument.Load(this.Location);
                XNamespace rootNs         = projDefinition.Root.Name.Namespace;
                var        helper         = new ConfigHelper <AssemblyInfo>(this.Log);
                var        tokens         = this.ProjectProperties.GetValues();

                referencesPathes = projDefinition
                                   .Element(rootNs + "Project")
                                   .Elements(rootNs + "ItemGroup")
                                   .Elements(rootNs + "Reference")
                                   .Where(el => (el.Attribute("Include")?.Value != "System") && (el.Attribute("Condition") == null || el.Attribute("Condition").Value.ToLowerInvariant() != "false"))
                                   .Select(refElem => (refElem.Element(rootNs + "HintPath") == null ? (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) : refElem.Element(rootNs + "HintPath").Value))
                                   .Select(path => helper.ApplyPathTokens(tokens, Path.IsPathRooted(path) ? path : Path.GetFullPath((new Uri(Path.Combine(baseDir, path))).LocalPath)))
                                   .ToList();

                var projectReferences = projDefinition
                                        .Element(rootNs + "Project")
                                        .Elements(rootNs + "ItemGroup")
                                        .Elements(rootNs + "ProjectReference")
                                        .Where(el => el.Attribute("Condition") == null || el.Attribute("Condition").Value.ToLowerInvariant() != "false")
                                        .Select(refElem => (refElem.Element(rootNs + "HintPath") == null ? (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) : refElem.Element(rootNs + "HintPath").Value))
                                        .Select(path => helper.ApplyPathTokens(tokens, Path.IsPathRooted(path) ? path : Path.GetFullPath((new Uri(Path.Combine(baseDir, path))).LocalPath)))
                                        .ToArray();

                if (projectReferences.Length > 0)
                {
                    if (this.ProjectProperties.BuildProjects == null)
                    {
                        this.ProjectProperties.BuildProjects = new List <string>();
                    }

                    foreach (var projectRef in projectReferences)
                    {
                        var isBuilt = this.ProjectProperties.BuildProjects.Contains(projectRef);

                        if (!isBuilt)
                        {
                            this.ProjectProperties.BuildProjects.Add(projectRef);
                        }

                        var processor = new TranslatorProcessor(new BridgeOptions
                        {
                            Rebuild           = this.Rebuild,
                            ProjectLocation   = projectRef,
                            BridgeLocation    = this.BridgeLocation,
                            ProjectProperties = new Contract.ProjectProperties
                            {
                                BuildProjects = this.ProjectProperties.BuildProjects,
                                Configuration = this.ProjectProperties.Configuration,
                                Platform      = this.ProjectProperties.Platform
                            }
                        }, new Logger(null, false, LoggerLevel.Info, true, new ConsoleLoggerWriter(), new FileLoggerWriter()));

                        processor.PreProcess();

                        var projectAssembly = processor.Translator.AssemblyLocation;

                        if (!File.Exists(projectAssembly) || this.Rebuild && !isBuilt)
                        {
                            processor.Process();
                            processor.PostProcess();
                        }

                        referencesPathes.Add(projectAssembly);
                    }
                }
            }
            else
            {
                var list = new List <string>();
                referencesPathes = list;
                if (!string.IsNullOrWhiteSpace(this.AssemblyInfo.ReferencesPath))
                {
                    var path = this.AssemblyInfo.ReferencesPath;
                    path = Path.IsPathRooted(path) ? path : Path.GetFullPath((new Uri(Path.Combine(this.Location, path))).LocalPath);

                    if (!Directory.Exists(path))
                    {
                        throw (TranslatorException)Bridge.Translator.TranslatorException.Create("ReferencesPath doesn't exist - {0}", path);
                    }

                    string[] allfiles = System.IO.Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);
                    list.AddRange(allfiles);
                }

                if (this.AssemblyInfo.References != null && this.AssemblyInfo.References.Length > 0)
                {
                    foreach (var reference in this.AssemblyInfo.References)
                    {
                        var path = Path.IsPathRooted(reference) ? reference : Path.GetFullPath((new Uri(Path.Combine(this.Location, reference))).LocalPath);
                        list.Add(path);
                    }
                }

                var packagesPath = Path.GetFullPath((new Uri(Path.Combine(this.Location, "packages"))).LocalPath);
                if (!Directory.Exists(packagesPath))
                {
                    packagesPath = Path.Combine(Directory.GetParent(this.Location).ToString(), "packages");
                }

                var packagesConfigPath = Path.Combine(this.Location, "packages.config");

                if (File.Exists(packagesConfigPath))
                {
                    var doc = new System.Xml.XmlDocument();
                    doc.LoadXml(File.ReadAllText(packagesConfigPath));
                    var nodes = doc.DocumentElement.SelectNodes($"descendant::package");

                    if (nodes.Count > 0)
                    {
                        foreach (System.Xml.XmlNode node in nodes)
                        {
                            string id      = node.Attributes["id"].Value;
                            string version = node.Attributes["version"].Value;

                            string packageDir = Path.Combine(packagesPath, id + "." + version);

                            AddPackageAssembly(list, packageDir);
                        }
                    }
                }
                else if (Directory.Exists(packagesPath))
                {
                    var packagesFolders = Directory.GetDirectories(packagesPath, "*", SearchOption.TopDirectoryOnly);
                    foreach (var packageFolder in packagesFolders)
                    {
                        var packageLib = Path.Combine(packageFolder, "lib");
                        AddPackageAssembly(list, packageLib);
                    }
                }
            }

            var arr = referencesPathes.ToArray();

            foreach (var refPath in arr)
            {
                AddNestedReferences(referencesPathes, refPath);
            }

            IList <SyntaxTree> trees = new List <SyntaxTree>(files.Count);

            foreach (var file in files)
            {
                var filePath   = Path.IsPathRooted(file) ? file : Path.GetFullPath((new Uri(Path.Combine(baseDir, file))).LocalPath);
                var syntaxTree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(filePath), parseOptions, filePath, Encoding.Default);
                trees.Add(syntaxTree);
            }

            var references = new List <MetadataReference>();
            var outputDir  = Path.GetDirectoryName(this.AssemblyLocation);
            var di         = new DirectoryInfo(outputDir);

            if (!di.Exists)
            {
                di.Create();
            }

            var updateBridgeLocation = string.IsNullOrWhiteSpace(this.BridgeLocation) || !File.Exists(this.BridgeLocation);

            foreach (var path in referencesPathes)
            {
                var newPath = Path.GetFullPath(new Uri(Path.Combine(outputDir, Path.GetFileName(path))).LocalPath);
                if (string.Compare(newPath, path, true) != 0)
                {
                    File.Copy(path, newPath, true);
                }

                if (updateBridgeLocation && string.Compare(Path.GetFileName(path), "bridge.dll", true) == 0)
                {
                    this.BridgeLocation = path;
                }

                references.Add(MetadataReference.CreateFromFile(path, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("global"))));
            }

            var compilation = CSharpCompilation.Create(this.ProjectProperties.AssemblyName ?? new DirectoryInfo(this.Location).Name, trees, references, compilationOptions);

            Microsoft.CodeAnalysis.Emit.EmitResult emitResult;

            using (var outputStream = new FileStream(this.AssemblyLocation, FileMode.Create))
            {
                emitResult = compilation.Emit(outputStream, options: new Microsoft.CodeAnalysis.Emit.EmitOptions(false, Microsoft.CodeAnalysis.Emit.DebugInformationFormat.Embedded, runtimeMetadataVersion: "v4.0.30319", includePrivateMembers: true));
            }

            if (!emitResult.Success)
            {
                StringBuilder sb = new StringBuilder("C# Compilation Failed");
                sb.AppendLine();

                baseDir = File.Exists(this.Location) ? Path.GetDirectoryName(this.Location) : Path.GetFullPath(this.Location);

                foreach (var d in emitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error))
                {
                    var filePath = d.Location?.SourceTree.FilePath ?? "";
                    if (filePath.StartsWith(baseDir))
                    {
                        filePath = filePath.Substring(baseDir.Length + 1);
                    }

                    var mapped = d.Location != null?d.Location.GetMappedLineSpan() : default(FileLinePositionSpan);

                    sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\t{4}({0},{1}): {2}: {3}", mapped.StartLinePosition.Line + 1, mapped.StartLinePosition.Character + 1, d.Id, d.GetMessage(), filePath));
                    foreach (var l in d.AdditionalLocations)
                    {
                        filePath = l.SourceTree.FilePath ?? "";
                        if (filePath.StartsWith(baseDir))
                        {
                            filePath = filePath.Substring(baseDir.Length + 1);
                        }
                        mapped = l.GetMappedLineSpan();
                        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\t{2}({0},{1}): (Related location)", mapped.StartLinePosition.Line + 1, mapped.StartLinePosition.Character + 1, filePath));
                    }
                }

                throw new Bridge.Translator.TranslatorException(sb.ToString());
            }

            this.Log.Info("Building assembly done");
        }
コード例 #21
0
 public virtual void Add(MetadataReference reference)
 => _references.Add(reference);
コード例 #22
0
            private static void CreateSharedAssemblies()
            {
                string sharedAssembliesPath = Path.Combine(ScriptRoot, "SharedAssemblies");

                if (Directory.Exists(sharedAssembliesPath))
                {
                    Directory.Delete(sharedAssembliesPath, true);
                }

                Directory.CreateDirectory(sharedAssembliesPath);

                string secondaryDependencyPath = Path.Combine(sharedAssembliesPath, "SecondaryDependency.dll");

                string      primaryReferenceSource   = @"
using SecondaryDependency;

namespace PrimaryDependency
{
    public class Primary
    {
        public string GetValue()
        {
            var secondary = new Secondary();
            return secondary.GetSecondaryValue();
        }
    }
}";
                string      secondaryReferenceSource = @"
namespace SecondaryDependency
{
    public class Secondary
    {
        public string GetSecondaryValue()
        {
            return ""secondary type value"";
        }
    }
}";
                var         secondarySyntaxTree      = CSharpSyntaxTree.ParseText(secondaryReferenceSource);
                Compilation secondaryCompilation     = CSharpCompilation.Create("SecondaryDependency", new[] { secondarySyntaxTree })
                                                       .WithReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                                       .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

                secondaryCompilation.Emit(secondaryDependencyPath);

                var         primarySyntaxTree  = CSharpSyntaxTree.ParseText(primaryReferenceSource);
                Compilation primaryCompilation = CSharpCompilation.Create("PrimaryDependency", new[] { primarySyntaxTree })
                                                 .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                                 .WithReferences(MetadataReference.CreateFromFile(secondaryDependencyPath), MetadataReference.CreateFromFile(typeof(object).Assembly.Location));

                primaryCompilation.Emit(Path.Combine(sharedAssembliesPath, "PrimaryDependency.dll"));
            }
コード例 #23
0
ファイル: CodeGeneratorTests.cs プロジェクト: exyi/coberec
        void CheckItCompiles(string code, string extension = "")
        {
            var assemblyName = System.IO.Path.GetRandomFileName();
            var references   = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ValueTuple <int, int>).Assembly.Location),
                MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("netstandard")).Location),
                MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location),
            };

            references = references.Concat(ExprCS.MetadataContext.GetReferencedPaths().Select(p => MetadataReference.CreateFromFile(p))).ToArray();

            CSharpParseOptions options = new CSharpParseOptions(LanguageVersion.Latest);
            var compilation            = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] {
                CSharpSyntaxTree.ParseText(code, options),
                CSharpSyntaxTree.ParseText(ImplicitlyIncludedCode, options),
                CSharpSyntaxTree.ParseText(extension, options)
            },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var ms     = new System.IO.MemoryStream();
            var result = compilation.Emit(ms);

            // var errors = CSharpScript.Create<int>(code, options: ScriptOptions.Default., assemblyLoader: new InteractiveAssemblyLoader()).Compile();
            Assert.True(result.Success, $"Compilation of generated code failed:\n" + string.Join("\n", result.Diagnostics) + "\n\n" + code);
        }
コード例 #24
0
        private static byte[] CompileCSharpRoslyn(CsharpFrameworkCompilationRequest request)
        {
            // Gather SyntaxTrees for compilation
            List <SourceSyntaxTree> sourceSyntaxTrees = new List <SourceSyntaxTree>();
            List <SyntaxTree>       compilationTrees  = new List <SyntaxTree>();

            if (request.SourceDirectories != null)
            {
                foreach (var sourceDirectory in request.SourceDirectories)
                {
                    List <SourceSyntaxTree> ssts = Directory.GetFiles(sourceDirectory, "*.cs", SearchOption.AllDirectories)
                                                   .Select(F => new SourceSyntaxTree {
                        FileName = F, SyntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(F), new CSharpParseOptions())
                    })
                                                   .ToList();
                    sourceSyntaxTrees.AddRange(ssts);
                    compilationTrees.AddRange(ssts.Select(S => S.SyntaxTree).ToList());
                }
            }
            SyntaxTree sourceTree = CSharpSyntaxTree.ParseText(request.Source, new CSharpParseOptions());

            compilationTrees.Add(sourceTree);

            List <PortableExecutableReference> references = request.References
                                                            .Where(R => R.Framework == request.TargetDotNetVersion)
                                                            .Where(R => R.Enabled)
                                                            .Select(R => MetadataReference.CreateFromFile(R.File))
                                                            .ToList();

            // Use specified OutputKind and Platform
            CSharpCompilationOptions options = new CSharpCompilationOptions(outputKind: request.OutputKind, optimizationLevel: OptimizationLevel.Release, platform: request.Platform, allowUnsafe: request.UnsafeCompile);
            // Compile to obtain SemanticModel
            CSharpCompilation compilation = CSharpCompilation.Create(
                request.AssemblyName == null ? Path.GetRandomFileName() : request.AssemblyName,
                compilationTrees,
                references,
                options
                );

            // Perform source code optimization, removing unused types
            if (request.Optimize)
            {
                // Find all Types used by the generated compilation
                HashSet <ITypeSymbol> usedTypes     = new HashSet <ITypeSymbol>();
                List <SyntaxTree>     searchedTrees = new List <SyntaxTree>();
                GetUsedTypesRecursively(compilation, sourceTree, ref usedTypes, ref sourceSyntaxTrees, ref searchedTrees);
                List <string> usedTypeNames = usedTypes.Select(T => GetFullyQualifiedTypeName(T)).ToList();

                // Filter SyntaxTrees to trees that define a used Type, otherwise the tree is not needed in this compilation
                compilationTrees = sourceSyntaxTrees.Where(SST => SyntaxTreeDefinesUsedType(compilation, SST.SyntaxTree, usedTypeNames))
                                   .Select(SST => SST.SyntaxTree)
                                   .ToList();

                // Removed unused Using statements from the additional entrypoint source
                List <string> usedNamespaceNames = GetUsedTypes(compilation, sourceTree)
                                                   .Select(T => GetFullyQualifiedContainingNamespaceName(T)).Distinct().ToList();
                List <SyntaxNode> unusedUsingDirectives = sourceTree.GetRoot().DescendantNodes().Where(N =>
                {
                    return(N.Kind() == SyntaxKind.UsingDirective && !((UsingDirectiveSyntax)N).Name.ToFullString().StartsWith("System.") && !usedNamespaceNames.Contains(((UsingDirectiveSyntax)N).Name.ToFullString()));
                }).ToList();
                sourceTree = sourceTree.GetRoot().RemoveNodes(unusedUsingDirectives, SyntaxRemoveOptions.KeepNoTrivia).SyntaxTree;

                // Compile again, with unused SyntaxTrees and unused using statements removed
                compilationTrees.Add(sourceTree);
                compilation = CSharpCompilation.Create(
                    request.AssemblyName == null ? Path.GetRandomFileName() : request.AssemblyName,
                    compilationTrees,
                    request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                {
                    return(MetadataReference.CreateFromFile(R.File));
                }).ToList(),
                    options
                    );
            }

            // Emit compilation
            EmitResult emitResult;

            byte[] ILbytes = null;
            using (var ms = new MemoryStream())
            {
                emitResult = compilation.Emit(
                    ms,
                    manifestResources: request.EmbeddedResources.Where(ER =>
                {
                    return(request.Platform == Platform.AnyCpu || ER.Platform == Platform.AnyCpu || ER.Platform == request.Platform);
                }).Where(ER => ER.Enabled).Select(ER =>
                {
                    return(new ResourceDescription(ER.Name, () => File.OpenRead(ER.File), true));
                }).ToList()
                    );
                if (emitResult.Success)
                {
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ILbytes = ms.ToArray();
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Diagnostic d in emitResult.Diagnostics)
                    {
                        sb.AppendLine(d.ToString());
                    }
                    throw new CompilerException("CompilationErrors: " + Environment.NewLine + sb);
                }
            }
            if (request.Confuse)
            {
                return(ConfuseAssembly(ILbytes));
            }
            return(ILbytes);
        }
コード例 #25
0
        private static Assembly CompileAssembly(FileReference OutputAssemblyPath, List <FileReference> SourceFileNames, List <string> ReferencedAssembies, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false)
        {
            CSharpParseOptions ParseOptions = new CSharpParseOptions(
                languageVersion: LanguageVersion.Latest,
                kind: SourceCodeKind.Regular,
                preprocessorSymbols: PreprocessorDefines
                );

            List <SyntaxTree> SyntaxTrees = new List <SyntaxTree>();

            foreach (FileReference SourceFileName in SourceFileNames)
            {
                SourceText Source = SourceText.From(File.ReadAllText(SourceFileName.FullName));
                SyntaxTree Tree   = CSharpSyntaxTree.ParseText(Source, ParseOptions, SourceFileName.FullName);

                IEnumerable <Diagnostic> Diagnostics = Tree.GetDiagnostics();
                if (Diagnostics.Count() > 0)
                {
                    Log.TraceWarning($"Errors generated while parsing '{SourceFileName.FullName}'");
                    LogDiagnostics(Tree.GetDiagnostics());
                    return(null);
                }

                SyntaxTrees.Add(Tree);
            }

            // Create the output directory if it doesn't exist already
            DirectoryInfo DirInfo = new DirectoryInfo(OutputAssemblyPath.Directory.FullName);

            if (!DirInfo.Exists)
            {
                try
                {
                    DirInfo.Create();
                }
                catch (Exception Ex)
                {
                    throw new BuildException(Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message);
                }
            }

            List <MetadataReference> MetadataReferences = new List <MetadataReference>();

            if (ReferencedAssembies != null)
            {
                foreach (string Reference in ReferencedAssembies)
                {
                    MetadataReferences.Add(MetadataReference.CreateFromFile(Reference));
                }
            }

            MetadataReferences.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Collections").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.IO").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.IO.FileSystem").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Console").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Runtime.Extensions").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(Assembly.Load("Microsoft.Win32.Registry").Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(typeof(UnrealBuildTool).Assembly.Location));
            MetadataReferences.Add(MetadataReference.CreateFromFile(typeof(FileReference).Assembly.Location));

            CSharpCompilationOptions CompilationOptions = new CSharpCompilationOptions(
                outputKind: OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: OptimizationLevel.Release,
                warningLevel: 4,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
                reportSuppressedDiagnostics: true
                );

            CSharpCompilation Compilation = CSharpCompilation.Create(
                assemblyName: OutputAssemblyPath.GetFileNameWithoutAnyExtensions(),
                syntaxTrees: SyntaxTrees,
                references: MetadataReferences,
                options: CompilationOptions
                );

            using (FileStream AssemblyStream = FileReference.Open(OutputAssemblyPath, FileMode.Create))
            {
                EmitOptions EmitOptions = new EmitOptions(
                    includePrivateMembers: true
                    );

                EmitResult Result = Compilation.Emit(
                    peStream: AssemblyStream,
                    options: EmitOptions);

                if (!Result.Success)
                {
                    LogDiagnostics(Result.Diagnostics);
                    return(null);
                }
            }

            return(Assembly.LoadFile(OutputAssemblyPath.FullName));
        }
コード例 #26
0
        private void recompile()
        {
            if (assemblies == null)
            {
                assemblies = new HashSet <string>();
                foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
                {
                    assemblies.Add(ass.Location);
                }
            }

            assemblies.Add(typeof(JetBrains.Annotations.NotNullAttribute).Assembly.Location);

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            // ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
            var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[]
            {
#if DEBUG
                "DEBUG",
#endif
#if TRACE
                "TRACE",
#endif
#if RELEASE
                "RELEASE",
#endif
            }, languageVersion: LanguageVersion.CSharp7_3);
            var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));

            while (!checkFileReady(lastTouchedFile))
            {
                Thread.Sleep(10);
            }

            Logger.Log($@"Recompiling {Path.GetFileName(checkpointObject.GetType().Name)}...", LoggingTarget.Runtime, LogLevel.Important);

            CompilationStarted?.Invoke();

            // ensure we don't duplicate the dynamic suffix.
            string assemblyNamespace = checkpointObject.GetType().Assembly.GetName().Name.Replace(".Dynamic", "");

            string assemblyVersion  = $"{++currentVersion}.0.*";
            string dynamicNamespace = $"{assemblyNamespace}.Dynamic";

            var compilation = CSharpCompilation.Create(
                dynamicNamespace,
                requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOptions, file))
                // Compile the assembly with a new version so that it replaces the existing one
                .Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions))
                ,
                references,
                options
                );

            using (var ms = new MemoryStream())
            {
                var compilationResult = compilation.Emit(ms);

                if (compilationResult.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    CompilationFinished?.Invoke(
                        Assembly.Load(ms.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == checkpointObject.GetType().FullName)
                        );
                }
                else
                {
                    foreach (var diagnostic in compilationResult.Diagnostics)
                    {
                        if (diagnostic.Severity < DiagnosticSeverity.Error)
                        {
                            continue;
                        }

                        CompilationFailed?.Invoke(new Exception(diagnostic.ToString()));
                    }
                }
            }
        }
コード例 #27
0
ファイル: WinMdDumpTest.cs プロジェクト: GloryChou/roslyn
        private string Dump(MetadataReference winmd, MetadataReference[] additionalRefs = null)
        {
            IEnumerable<MetadataReference> references = new[] { MscorlibRef_v4_0_30316_17626, _systemRuntimeRef, _systemObjectModelRef, _windowsRuntimeUIXamlRef, _interopServicesWindowsRuntimeRef, winmd };

            if (additionalRefs != null)
            {
                references = references.Concat(additionalRefs);
            }

            var comp = CreateCompilation("", references, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));

            var writer = new StringBuilder();
            AppendAssemblyRefs(writer, (PEAssemblySymbol)comp.GetReferencedAssemblySymbol(winmd));

            AppendMembers(writer, comp.GetReferencedAssemblySymbol(winmd).GlobalNamespace, "");
            return writer.ToString();
        }
コード例 #28
0
 public static BuildReference ByPath(string path)
 => new BuildReference(new[] { MetadataReference.CreateFromFile(path) }, path: path);
コード例 #29
0
        //public VbExpressionEditorInstance(Size initialSize) : this()
        //{
        //    this.Width = initialSize.Width;
        //    this.Height = initialSize.Height;

        //    //this.Width = 200;
        //    //this.Height = 200;
        //}


        private void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                try
                {
                    //string startString = VbExpressionEditorService.Instance.UsingNamespaces
                    //    + "using System; using System.Collections.Generic; using System.Text; namespace SomeNamespace { public class NotAProgram { private void SomeMethod() { "
                    //    + variableDeclarations + "var blah = ";
                    //string endString = " ; } } }";
                    //string codeString = startString + this.Text.Substring(0, this.CaretOffset) + endString;
                    string startString = VbExpressionEditorService.Instance.UsingNamespaces + "Imports System \n Imports System.Collections.Generic \n Imports System.Text \n Imports System.Data \n Namespace SomeNamespace \n Class NotAProgram \n Sub SomeMethod()  \n  "
                                         + variableDeclarations + "Dim blah = ";
                    string endString  = "\n End Sub \n End Class \n End Namespace ";
                    string codeString = startString + this.Text.Substring(0, this.CaretOffset) + endString;

                    var tree = VisualBasicSyntaxTree.ParseText(codeString);

                    var root = (Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax)tree.GetRoot();

                    var compilation = VisualBasicCompilation.Create("CustomIntellisense")
                                      .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                      .AddReferences(MetadataReference.CreateFromFile(typeof(System.Data.DataTable).Assembly.Location))
                                      .AddReferences(MetadataReference.CreateFromFile(typeof(System.Collections.IDictionary).Assembly.Location))
                                      .AddSyntaxTrees(tree);

                    var model = compilation.GetSemanticModel(tree);

                    var exprString = root.FindToken(codeString.LastIndexOf('.') - 1).Parent;

                    var literalInfo = model.GetTypeInfo(exprString);

                    var             stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type;
                    IList <ISymbol> symbols          = new List <ISymbol>()
                    {
                    };
                    foreach (var s in (from method in stringTypeSymbol.GetMembers() where method.DeclaredAccessibility == Accessibility.Public select method).Distinct())
                    {
                        symbols.Add(s);
                    }

                    if (symbols != null && symbols.Count > 0)
                    {
                        completionWindow = new CompletionWindow(this.TextArea);
                        IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                        data.Clear();
                        var distinctSymbols = from s in symbols group s by s.Name into g select new { Name = g.Key, Symbols = g };
                        foreach (var g in distinctSymbols.OrderBy(s => s.Name))
                        {
                            data.Add(new QueryCompletionData(g.Name, g.Symbols.ToArray()));
                        }

                        completionWindow.Show();
                        completionWindow.Closed += delegate
                        {
                            completionWindow = null;
                        };
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
コード例 #30
0
 private static IEnumerable <MetadataReference> Create(string assemblyName) =>
 ImmutableArray.Create((MetadataReference)MetadataReference.CreateFromFile(
                           Path.Combine(systemAssembliesFolder, assemblyName)));
コード例 #31
0
        public (XDocument, IEnumerable <IDiagnosticItem>) Extract(string source)
        {
            var options = new CSharpParseOptions();
            var tree    = CSharpSyntaxTree.ParseText(source, options);

            var trees = new[] { tree };

            var referenceList = new MetadataReference[]
            {
                // Add mscorlib
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                // Add System
                MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                // Add System.Core
                MetadataReference.CreateFromFile(typeof(PipeDirection).Assembly.Location),
            };

            var compilation = CSharpCompilation.Create("MyAssembly.dll", trees,
                                                       references: referenceList,
                                                       options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            IList <IDiagnosticItem> diagnostics = new List <IDiagnosticItem>();

            foreach (var diagnostic in compilation.GetDiagnostics())
            {
                var item = new DiagnosticItem(diagnostic);
                diagnostics.Add(item);
            }

            var document           = new XDocument();
            var compilationElement = new XElement("Compilation",
                                                  new XAttribute("Version", "0.1"),
                                                  new XAttribute("Language", "C#"),
                                                  new XAttribute("Assembly", compilation.AssemblyName));

            document.Add(compilationElement);
            var diagnosticsElement = new XElement("Diagnostics");

            compilationElement.Add(diagnosticsElement);

            // Add nodes with the diagnostics
            foreach (var diagnostic in compilation.GetDiagnostics())
            {
                var item = new DiagnosticItem(diagnostic);
                diagnosticsElement.Add(new XElement("Diagnostic",
                                                    new XAttribute("Message", item.Message),
                                                    new XAttribute("Id", item.Id),
                                                    new XAttribute("Severity", item.Severity),
                                                    new XAttribute("StartLine", item.Line),
                                                    new XAttribute("StartCol", item.Column),
                                                    new XAttribute("EndLine", item.EndLine),
                                                    new XAttribute("EndCol", item.EndColumn)));
            }

            // Add Options element. Individual options are attributes.
            var optionsElement = new XElement("Options");

            compilationElement.Add(optionsElement);
            CSharpCompilationOptions compOptions = compilation.Options;

            string[,] optionData =
            {
                { "AllowUnsafe",                    compOptions.AllowUnsafe.ToString()                                                                        },
                { "AssemblyIdentityComparer",       compOptions.AssemblyIdentityComparer.ToString()                                                           },
                { "CheckOverflow",                  compOptions.CheckOverflow.ToString()                                                                      },
                { "ConcurrentBuild",                compOptions.ConcurrentBuild.ToString()                                                                    },
                { "CryptoKeyContainer",             compOptions.CryptoKeyContainer == null ? "null" : compOptions.CryptoKeyContainer                          },
                { "CryptoKeyFile",                  compOptions.CryptoKeyFile == null ? "null" : compOptions.CryptoKeyFile                                    },
                { "CryptoPublicKeyLength",          compOptions.CryptoPublicKey.Length.ToString()                                                             },
                { "DelaySign",                      compOptions.DelaySign.ToString()                                                                          },
                { "Deterministic",                  compOptions.Deterministic.ToString()                                                                      },
                { "Errors",                         compOptions.Errors.Count().ToString()                                                                     },
                { "GeneralDiagnosticOption",        compOptions.GeneralDiagnosticOption.ToString()                                                            },
                { "Language",                       compOptions.Language                                                                                      },
                { "MainTypeName",                   compOptions.MainTypeName == null ? "null" : compOptions.MainTypeName                                      },
                { "MetadataImportOptions",          compOptions.MetadataImportOptions.ToString()                                                              },
                { "MetadataReferenceResolver",      compOptions.MetadataReferenceResolver == null ? "null" : compOptions.MetadataReferenceResolver.ToString() },
                { "ModuleName",                     compOptions.ModuleName == null ? "null" : compOptions.ModuleName                                          },
                { "NullableContextOptions",         compOptions.NullableContextOptions.ToString()                                                             },
                { "OptimizationLevel",              compOptions.OptimizationLevel.ToString()                                                                  },
                { "OutputKind",                     compOptions.OutputKind.ToString()                                                                         },
                { "Platform",                       compOptions.Platform.ToString()                                                                           },
                { "PublicSign",                     compOptions.PublicSign.ToString()                                                                         },
                { "ReportSuppressedDiagnostics",    compOptions.ReportSuppressedDiagnostics.ToString()                                                        },
                { "SourceReferenceResolver",        compOptions.SourceReferenceResolver == null ? "null" : compOptions.SourceReferenceResolver.ToString()     },
                { "SpecificDiagnosticOptionsCount", compOptions.SpecificDiagnosticOptions.Count().ToString()                                                  },
                { "StrongNameProvider",             compOptions.StrongNameProvider == null ? "null" : compOptions.StrongNameProvider.ToString()               },
                { "UsingsCount",                    compOptions.Usings.Count().ToString()                                                                     },
                { "WarningLevel",                   compOptions.WarningLevel.ToString()                                                                       }
            };

            for (int item = 0; item < optionData.GetLength(0); item++)
            {
                optionsElement.Add(new XAttribute(optionData[item, 0], optionData[item, 1]));
            }

            // Add the SpecificDiagnosticOptions
            if (compOptions.SpecificDiagnosticOptions.Count() > 0)
            {
                var specificElement = new XElement("SpecificDiagnosticOptions");
                optionsElement.Add(specificElement);
                foreach (var item in compOptions.SpecificDiagnosticOptions)
                {
                    specificElement.Add(new XElement("SpecificDiagnosticOption",
                                                     new XAttribute("name", item.Key),
                                                     new XAttribute("value", item.Value.ToString())));
                }
            }

            // Add the Usings
            if (compOptions.Usings.Count() > 0)
            {
                var usingElement = new XElement("Usings");
                optionsElement.Add(usingElement);
                foreach (var item in compOptions.Usings)
                {
                    usingElement.Add(new XElement("Using", new XAttribute("value", item)));
                }
            }

            // Add the references to the compilation.
            var referencesElement = new XElement("References");

            compilationElement.Add(referencesElement);
            foreach (var reference in compilation.ReferencedAssemblyNames)
            {
                referencesElement.Add(new XElement("Reference", new XAttribute("DisplayName", reference.GetDisplayName())));
            }

            // Add each of the trees (i.e. compilation units) to the compilation node.
            foreach (var atree in trees)
            {
                var walker = new CSharpConceptWalker(compilation, atree, document);
                walker.Visit(atree.GetRoot());
            }

            return(document, diagnostics);
        }
コード例 #32
0
        public static Assembly CreateImplementationOf(params Type[] types)
        {
            if (types.Length <= 0)
            {
                throw new ArgumentException("At least one interface must be specified");
            }
            if (types.Distinct().Count() != types.Length)
            {
                throw new ArgumentException("Types must be unique");
            }
            if (types.Any(t => !t.IsInterface))
            {
                throw new NotSupportedException("Only interfaces are supported");
            }
            if (types.Any(t => t.GetProperties().Any()))
            {
                throw new NotSupportedException("Properties are not supported");
            }

            // Create classes
            var classes = types
                          .Select(CreateClass)
                          .ToArray();

            // Create namespace
            var namespaceName = types.First().Namespace;
            var ns            = SyntaxFactory
                                .NamespaceDeclaration(SyntaxFactory.ParseName(namespaceName))
                                .AddMembers(classes);

            // Create compilation unit
            var defaultNamespaces = new[]
            {
                "System",
                "System.Collections.Generic"
            };

            var cu = SyntaxFactory
                     .CompilationUnit()
                     .AddUsings(defaultNamespaces.Select(CreateUsingDirective).ToArray())
                     .AddMembers(ns);

            var defaultCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                            .WithOverflowChecks(true)
                                            .WithOptimizationLevel(OptimizationLevel.Release)
                                            .WithUsings(defaultNamespaces);

            var refs = DependencyContext.Default.CompileLibraries
                       .SelectMany(libs => libs.ResolveReferencePaths())
                       .Concat(new [] { Assembly.GetEntryAssembly()?.Location ?? Assembly.GetExecutingAssembly().Location })
                       .Select(asm => MetadataReference.CreateFromFile(asm))
                       .ToList();

            var syntaxTree = SyntaxFactory.SyntaxTree(cu, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3));

            var compilation = CSharpCompilation.Create(namespaceName, new[] { syntaxTree }, null, defaultCompilationOptions)
                              .WithReferences(refs);

            // write code to Trace
            Trace.WriteLine(cu.SyntaxTree.GetRoot().NormalizeWhitespace().ToFullString());

            // create assembly
            using (var st = new MemoryStream())
            {
                var emit = compilation.Emit(st);
                if (!emit.Success)
                {
                    throw new InvalidProgramException("Could not compile the generated type");
                }

                var assembly = Assembly.Load(st.GetBuffer());
                if (assembly.GetTypes().Length != types.Length)
                {
                    throw new InvalidOperationException("Number of implementations does not match the number of provided types");
                }

                return(assembly);
            }
        }
コード例 #33
0
 protected override IEnumerable <MetadataReference> GetAdditionnalReferences()
 {
     return(new[] { MetadataReference.CreateFromFile(typeof(System.Data.SqlClient.SqlCommand).Assembly.Location) });
 }
コード例 #34
0
        CodeCompilerResult CompileFileInternal(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            CSharpCommandLineArguments args = null;

            if (arguments.AdditionalArguments != null)
            {
                var splitArgs = CommandLineParser.SplitCommandLineIntoArguments(arguments.AdditionalArguments, false);
                if (splitArgs.Any())
                {
                    args = CSharpCommandLineParser.Default.Parse(splitArgs, arguments.TempDirectory, null, null);
                }
            }

            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in AssemblyResolver.GetResolvedReferences(runtime, arguments.AssemblyReferences))
            {
                references.Add(MetadataReference.CreateFromFile(assemblyReference));
            }

            var parseOptions = args?.ParseOptions ?? new CSharpParseOptions();

            if (arguments.LangVersion != null)
            {
                if (LanguageVersionFacts.TryParse(arguments.LangVersion, out var langVersion))
                {
                    parseOptions = parseOptions.WithLanguageVersion(langVersion);
                }
                else
                {
                    throw new System.Exception($"Unknown value '{arguments.LangVersion}' for langversion");
                }
            }
            else
            {
                // need to update this when updating referenced roslyn binaries
                CSharpLangVersionHelper.GetBestSupportedLangVersion(runtime, CSharpLangVersion.v9_0);
            }

            var syntaxTrees = new List <SyntaxTree> ();

            foreach (var sourceFile in arguments.SourceFiles)
            {
                using var stream = File.OpenRead(sourceFile);
                var sourceText = SourceText.From(stream, Encoding.UTF8);
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText, parseOptions, cancellationToken: token));
            }

            var compilationOptions = (args?.CompilationOptions ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                     .WithOutputKind(OutputKind.DynamicallyLinkedLibrary);

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                syntaxTrees,
                references,
                compilationOptions
                );


            EmitOptions emitOptions = args?.EmitOptions ?? new EmitOptions();

            if (arguments.Debug)
            {
                var embeddedTexts = syntaxTrees.Select(st => EmbeddedText.FromSource(st.FilePath, st.GetText())).ToList();
                emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
            }

            using var fs = File.OpenWrite(arguments.OutputPath);
            EmitResult result = compilation.Emit(fs, options: emitOptions, cancellationToken: token);

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
            var errors   = failures.Select(x => {
                var location          = x.Location.GetMappedLineSpan();
                var startLinePosition = location.StartLinePosition;
                var endLinePosition   = location.EndLinePosition;
                return(new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = startLinePosition.Character,
                    Line = startLinePosition.Line,
                    EndLine = endLinePosition.Line,
                    EndColumn = endLinePosition.Character,
                    IsError = x.Severity == DiagnosticSeverity.Error,
                    Origin = location.Path
                });
            }).ToList();

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = errors
            });
        }
コード例 #35
0
        private Compilation GetCompilation(string source, string language)
        {
            if (language == LanguageNames.CSharp)
            {
                var tree = CSharp.SyntaxFactory.ParseSyntaxTree(source);
                return(CSharp.CSharpCompilation.Create("Test", syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }));
            }
            else if (language == LanguageNames.VisualBasic)
            {
                var tree = VisualBasic.SyntaxFactory.ParseSyntaxTree(source);
                return(VisualBasic.VisualBasicCompilation.Create("Test", syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }));
            }

            throw new NotSupportedException();
        }
コード例 #36
0
 private static void VerifyAssemblyReferences(
     MetadataReference target,
     ImmutableArray<MetadataReference> references,
     ImmutableArray<AssemblyIdentity> expectedIdentities)
 {
     Assert.True(references.Contains(target));
     var modules = references.SelectAsArray(r => r.ToModuleInstance());
     using (var runtime = new RuntimeInstance(modules))
     {
         var moduleVersionId = target.GetModuleVersionId();
         var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock);
         var actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer);
         // Verify identities.
         var actualIdentities = actualReferences.SelectAsArray(r => r.GetAssemblyIdentity());
         AssertEx.Equal(expectedIdentities, actualIdentities);
         // Verify identities are unique.
         var uniqueIdentities = actualIdentities.Distinct();
         Assert.Equal(actualIdentities.Length, uniqueIdentities.Length);
     }
 }
コード例 #37
0
 Compilation ICompilationFactoryService.GetCompilationFromCompilationReference(MetadataReference reference)
 {
     var compilationRef = reference as CompilationReference;
     return (compilationRef != null) ? compilationRef.Compilation : null;
 }
コード例 #38
0
ファイル: RazorCompilationService.cs プロジェクト: gep13/Wyam
        // Wyam - Use the Roslyn scripting engine for compilation
        // In MVC, this part is done in RoslynCompilationService
        private Type Compile([NotNull] RelativeFileInfo file, [NotNull] string compilationContent)
        {
            HashSet <Assembly> assemblies = new HashSet <Assembly>(new AssemblyEqualityComparer())
            {
                Assembly.GetAssembly(typeof(Modules.Razor.Razor))   // Wyam.Modules.Razor
            };

            if (_executionContext.Assemblies != null)
            {
                assemblies.UnionWith(_executionContext.Assemblies);
            }

            var assemblyName       = Path.GetRandomFileName();
            var parseOptions       = new CSharpParseOptions();
            var syntaxTree         = CSharpSyntaxTree.ParseText(SourceText.From(compilationContent, Encoding.UTF8), parseOptions, assemblyName);
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var assemblyPath       = Path.GetDirectoryName(typeof(object).Assembly.Location);
            var compilation        = CSharpCompilation.Create(assemblyName, new[] { syntaxTree },
                                                              assemblies.Select(x => _metadataReferences.GetOrAdd(x.Location, y => MetadataReference.CreateFromFile(y))), compilationOptions)
                                     .AddReferences(
                // For some reason, Roslyn really wants these added by filename
                // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime
                _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "mscorlib.dll"), x => MetadataReference.CreateFromFile(x)),
                _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.dll"), x => MetadataReference.CreateFromFile(x)),
                _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.Core.dll"), x => MetadataReference.CreateFromFile(x)),
                _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.Runtime.dll"), x => MetadataReference.CreateFromFile(x))
                );

            foreach (byte[] rawAssembly in _executionContext.RawAssemblies)
            {
                using (MemoryStream memoryStream = new MemoryStream(rawAssembly))
                {
                    compilation = compilation.AddReferences(MetadataReference.CreateFromStream(memoryStream));
                }
            }

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    Trace.Error("{0} errors compiling {1}:{2}{3}", result.Diagnostics.Length, file.RelativePath, Environment.NewLine, string.Join(Environment.NewLine, result.Diagnostics));
                    throw new AggregateException(result.Diagnostics.Select(x => new Exception(x.ToString())));
                }

                ms.Seek(0, SeekOrigin.Begin);
                byte[]   assemblyBytes = ms.ToArray();
                Assembly assembly      = Assembly.Load(assemblyBytes);

                var type = assembly.GetExportedTypes()
                           .First(t => t.Name.StartsWith(_razorHost.MainClassNamePrefix, StringComparison.Ordinal));

                return(type);
            }
        }
コード例 #39
0
ファイル: Serializer_Asset.cs プロジェクト: jkotas/roslyn
 public void SerializeMetadataReference(MetadataReference reference, ObjectWriter writer, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     _hostSerializationService.WriteTo(reference, writer, cancellationToken);
 }
コード例 #40
0
        public void TestMixedPropertyAccessorModifiers_OverrideSetters()
        {
            var text1 = @"
class Derived : AccessorModifierMismatch // CS0534 (didn't implement AbstractAbstract.get)
{
    public override int NoneNone { set { } } // CS0506 (not virtual)
    public override int NoneAbstract { set { } }
    public override int NoneVirtual { set { } }
    public override int NoneOverride { set { } } // CS1545 (bogus)
    public override int NoneSealed { set { } } // CS1545 (bogus)

    public override int AbstractNone { set { } } // CS0506 (not virtual)
    public override int AbstractAbstract { set { } }
    public override int AbstractVirtual { set { } }
    public override int AbstractOverride { set { } } // CS1545 (bogus)
    public override int AbstractSealed { set { } } // CS1545 (bogus)

    public override int VirtualNone { set { } }
    public override int VirtualAbstract { set { } }
    public override int VirtualVirtual { set { } }
    public override int VirtualOverride { set { } } // CS1545 (bogus)
    public override int VirtualSealed { set { } } // CS1545 (bogus)

    public override int OverrideNone { set { } } // CS1545 (bogus)
    public override int OverrideAbstract { set { } } // CS1545 (bogus)
    public override int OverrideVirtual { set { } } // CS1545 (bogus)
    public override int OverrideOverride { set { } }
    public override int OverrideSealed { set { } } // CS1545 (bogus)

    public override int SealedNone { set { } } // CS1545 (bogus)
    public override int SealedAbstract { set { } } // CS1545 (bogus)
    public override int SealedVirtual { set { } } // CS1545 (bogus)
    public override int SealedOverride { set { } } // CS1545 (bogus)
    public override int SealedSealed { set { } } // CS0239 (sealed)
}
";
            var refs = new MetadataReference[] { TestReferences.SymbolsTests.Properties };
            CreateCompilationWithMscorlib(text1, references: refs, compOptions: TestOptions.Dll).VerifyDiagnostics(
                // (4,25): error CS0506: 'Derived.NoneNone': cannot override inherited member 'AccessorModifierMismatch.NoneNone' because it is not marked virtual, abstract, or override
                //     public override int NoneNone { set { } } // CS0506 (not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "NoneNone").WithArguments("Derived.NoneNone", "AccessorModifierMismatch.NoneNone"),
                // (7,25): error CS0569: 'Derived.NoneOverride': cannot override 'AccessorModifierMismatch.NoneOverride' because it is not supported by the language
                //     public override int NoneOverride { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "NoneOverride").WithArguments("Derived.NoneOverride", "AccessorModifierMismatch.NoneOverride"),
                // (8,25): error CS0569: 'Derived.NoneSealed': cannot override 'AccessorModifierMismatch.NoneSealed' because it is not supported by the language
                //     public override int NoneSealed { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "NoneSealed").WithArguments("Derived.NoneSealed", "AccessorModifierMismatch.NoneSealed"),
                // (10,40): error CS0506: 'Derived.AbstractNone.set': cannot override inherited member 'AccessorModifierMismatch.NoneNone.set' because it is not marked virtual, abstract, or override
                //     public override int AbstractNone { set { } } // CS0506 (not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived.AbstractNone.set", "AccessorModifierMismatch.NoneNone.set"),
                // (13,25): error CS0569: 'Derived.AbstractOverride': cannot override 'AccessorModifierMismatch.AbstractOverride' because it is not supported by the language
                //     public override int AbstractOverride { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "AbstractOverride").WithArguments("Derived.AbstractOverride", "AccessorModifierMismatch.AbstractOverride"),
                // (14,25): error CS0569: 'Derived.AbstractSealed': cannot override 'AccessorModifierMismatch.AbstractSealed' because it is not supported by the language
                //     public override int AbstractSealed { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "AbstractSealed").WithArguments("Derived.AbstractSealed", "AccessorModifierMismatch.AbstractSealed"),
                // (16,39): error CS0506: 'Derived.VirtualNone.set': cannot override inherited member 'AccessorModifierMismatch.NoneNone.set' because it is not marked virtual, abstract, or override
                //     public override int VirtualNone { set { } }
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived.VirtualNone.set", "AccessorModifierMismatch.NoneNone.set"),
                // (19,25): error CS0569: 'Derived.VirtualOverride': cannot override 'AccessorModifierMismatch.VirtualOverride' because it is not supported by the language
                //     public override int VirtualOverride { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "VirtualOverride").WithArguments("Derived.VirtualOverride", "AccessorModifierMismatch.VirtualOverride"),
                // (20,25): error CS0569: 'Derived.VirtualSealed': cannot override 'AccessorModifierMismatch.VirtualSealed' because it is not supported by the language
                //     public override int VirtualSealed { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "VirtualSealed").WithArguments("Derived.VirtualSealed", "AccessorModifierMismatch.VirtualSealed"),
                // (22,25): error CS0569: 'Derived.OverrideNone': cannot override 'AccessorModifierMismatch.OverrideNone' because it is not supported by the language
                //     public override int OverrideNone { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "OverrideNone").WithArguments("Derived.OverrideNone", "AccessorModifierMismatch.OverrideNone"),
                // (23,25): error CS0569: 'Derived.OverrideAbstract': cannot override 'AccessorModifierMismatch.OverrideAbstract' because it is not supported by the language
                //     public override int OverrideAbstract { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "OverrideAbstract").WithArguments("Derived.OverrideAbstract", "AccessorModifierMismatch.OverrideAbstract"),
                // (24,25): error CS0569: 'Derived.OverrideVirtual': cannot override 'AccessorModifierMismatch.OverrideVirtual' because it is not supported by the language
                //     public override int OverrideVirtual { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "OverrideVirtual").WithArguments("Derived.OverrideVirtual", "AccessorModifierMismatch.OverrideVirtual"),
                // (26,25): error CS0569: 'Derived.OverrideSealed': cannot override 'AccessorModifierMismatch.OverrideSealed' because it is not supported by the language
                //     public override int OverrideSealed { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "OverrideSealed").WithArguments("Derived.OverrideSealed", "AccessorModifierMismatch.OverrideSealed"),
                // (28,25): error CS0569: 'Derived.SealedNone': cannot override 'AccessorModifierMismatch.SealedNone' because it is not supported by the language
                //     public override int SealedNone { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "SealedNone").WithArguments("Derived.SealedNone", "AccessorModifierMismatch.SealedNone"),
                // (29,25): error CS0569: 'Derived.SealedAbstract': cannot override 'AccessorModifierMismatch.SealedAbstract' because it is not supported by the language
                //     public override int SealedAbstract { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "SealedAbstract").WithArguments("Derived.SealedAbstract", "AccessorModifierMismatch.SealedAbstract"),
                // (30,25): error CS0569: 'Derived.SealedVirtual': cannot override 'AccessorModifierMismatch.SealedVirtual' because it is not supported by the language
                //     public override int SealedVirtual { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "SealedVirtual").WithArguments("Derived.SealedVirtual", "AccessorModifierMismatch.SealedVirtual"),
                // (31,25): error CS0569: 'Derived.SealedOverride': cannot override 'AccessorModifierMismatch.SealedOverride' because it is not supported by the language
                //     public override int SealedOverride { set { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "SealedOverride").WithArguments("Derived.SealedOverride", "AccessorModifierMismatch.SealedOverride"),
                // (32,25): error CS0239: 'Derived.SealedSealed': cannot override inherited member 'AccessorModifierMismatch.SealedSealed' because it is sealed
                //     public override int SealedSealed { set { } } // CS0239 (sealed)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedSealed").WithArguments("Derived.SealedSealed", "AccessorModifierMismatch.SealedSealed"),
                // (2,7): error CS0534: 'Derived' does not implement inherited abstract member 'AccessorModifierMismatch.AbstractNone.get'
                // class Derived : AccessorModifierMismatch // CS0534 (didn't implement AbstractAbstract.get)
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "AccessorModifierMismatch.AbstractNone.get"));
        }
コード例 #41
0
		private void WriteObject (BinaryWriter writer, long id, object obj)
		{
			object data;
			TypeMetadata metadata;

			GetObjectData (obj, out metadata, out data);
			MetadataReference metadataReference = (MetadataReference)_cachedMetadata [metadata.InstanceTypeName];

			if (metadataReference != null && metadata.IsCompatible (metadataReference.Metadata))
			{
				// An object of the same type has already been serialized
				// It is not necessary to write again type metadata

				writer.Write ((byte) BinaryElement.RefTypeObject);
				writer.Write ((int)id);

				writer.Write ((int)metadataReference.ObjectID);
				metadata.WriteObjectData (this, writer, data);
				return;
			}

			if (metadataReference == null)
			{
				metadataReference = new MetadataReference (metadata, id);
				_cachedMetadata [metadata.InstanceTypeName] = metadataReference;
			}
			
			bool writeTypes = metadata.RequiresTypes || _typeFormat == FormatterTypeStyle.TypesAlways;

			BinaryElement objectTag;

			int assemblyId;
			if (metadata.TypeAssemblyName == CorlibAssemblyName)
			{
				// A corlib type
				objectTag = writeTypes ? BinaryElement.RuntimeObject : BinaryElement.UntypedRuntimeObject;
				assemblyId = -1;
			}
			else
			{
				objectTag = writeTypes ? BinaryElement.ExternalObject : BinaryElement.UntypedExternalObject;
				assemblyId = WriteAssemblyName (writer, metadata.TypeAssemblyName);
			}

			// Registers the assemblies needed for each field
			// If there are assemblies that where not registered before this object,
			// write them now

			metadata.WriteAssemblies (this, writer);

			// Writes the object

			writer.Write ((byte) objectTag);
			writer.Write ((int)id);
			writer.Write (metadata.InstanceTypeName);
			
			metadata.WriteTypeData (this, writer, writeTypes);
			if (assemblyId != -1) writer.Write (assemblyId);
			
			metadata.WriteObjectData (this, writer, data);
		}
コード例 #42
0
        public void TestMixedEventAccessorModifiers_OverrideAccessors()
        {
            var text1 = @"
class Derived : AccessorModifierMismatch
{
    public override event System.Action NoneNone { add { } remove { } } // CS0506 (not virtual)
    public override event System.Action NoneAbstract { add { } remove { } } // CS0506 (add not virtual)
    public override event System.Action NoneVirtual { add { } remove { } } // CS0506 (add not virtual)
    public override event System.Action NoneOverride { add { } remove { } } // CS0506 (add not virtual)
    public override event System.Action NoneSealed { add { } remove { } } // CS1545 (bogus)

    public override event System.Action AbstractNone { add { } remove { } } // CS0506 (remove not virtual)
    public override event System.Action AbstractAbstract { add { } remove { } }
    public override event System.Action AbstractVirtual { add { } remove { } }
    public override event System.Action AbstractOverride { add { } remove { } }
    public override event System.Action AbstractSealed { add { } remove { } } // CS1545 (bogus)

    public override event System.Action VirtualNone { add { } remove { } } // CS0506 (remove not virtual)
    public override event System.Action VirtualAbstract { add { } remove { } }
    public override event System.Action VirtualVirtual { add { } remove { } }
    public override event System.Action VirtualOverride { add { } remove { } }
    public override event System.Action VirtualSealed { add { } remove { } } // CS1545 (bogus)

    public override event System.Action OverrideNone { add { } remove { } } // CS0506 (remove not virtual)
    public override event System.Action OverrideAbstract { add { } remove { } }
    public override event System.Action OverrideVirtual { add { } remove { } }
    public override event System.Action OverrideOverride { add { } remove { } }
    public override event System.Action OverrideSealed { add { } remove { } } // CS1545 (bogus)

    public override event System.Action SealedNone { add { } remove { } } // CS1545 (bogus)
    public override event System.Action SealedAbstract { add { } remove { } } // CS1545 (bogus)
    public override event System.Action SealedVirtual { add { } remove { } } // CS1545 (bogus)
    public override event System.Action SealedOverride { add { } remove { } } // CS1545 (bogus)
    public override event System.Action SealedSealed { add { } remove { } } // CS0239 (sealed)
}
";
            // ACASEY: these are not exactly the errors that Dev10 produces, but they seem sensible.
            var refs = new MetadataReference[] { TestReferences.SymbolsTests.Events };
            CreateCompilationWithMscorlib(text1, references: refs, compOptions: TestOptions.Dll).VerifyDiagnostics(
                // (4,41): error CS0506: 'Derived.NoneNone': cannot override inherited member 'AccessorModifierMismatch.NoneNone' because it is not marked virtual, abstract, or override
                //     public override event System.Action NoneNone { add { } remove { } } // CS0506 (not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "NoneNone").WithArguments("Derived.NoneNone", "AccessorModifierMismatch.NoneNone"),
                // (5,56): error CS0506: 'Derived.NoneAbstract.add': cannot override inherited member 'AccessorModifierMismatch.NoneNone.add' because it is not marked virtual, abstract, or override
                //     public override event System.Action NoneAbstract { add { } remove { } } // CS0506 (add not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "add").WithArguments("Derived.NoneAbstract.add", "AccessorModifierMismatch.NoneNone.add"),
                // (6,55): error CS0506: 'Derived.NoneVirtual.add': cannot override inherited member 'AccessorModifierMismatch.NoneNone.add' because it is not marked virtual, abstract, or override
                //     public override event System.Action NoneVirtual { add { } remove { } } // CS0506 (add not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "add").WithArguments("Derived.NoneVirtual.add", "AccessorModifierMismatch.NoneNone.add"),
                // (7,56): error CS0506: 'Derived.NoneOverride.add': cannot override inherited member 'AccessorModifierMismatch.NoneNone.add' because it is not marked virtual, abstract, or override
                //     public override event System.Action NoneOverride { add { } remove { } } // CS0506 (add not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "add").WithArguments("Derived.NoneOverride.add", "AccessorModifierMismatch.NoneNone.add"),
                // (8,41): error CS0239: 'Derived.NoneSealed': cannot override inherited member 'AccessorModifierMismatch.NoneSealed' because it is sealed
                //     public override event System.Action NoneSealed { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "NoneSealed").WithArguments("Derived.NoneSealed", "AccessorModifierMismatch.NoneSealed"),
                
                // (10,64): error CS0506: 'Derived.AbstractNone.remove': cannot override inherited member 'AccessorModifierMismatch.NoneNone.remove' because it is not marked virtual, abstract, or override
                //     public override event System.Action AbstractNone { add { } remove { } } // CS0506 (remove not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "remove").WithArguments("Derived.AbstractNone.remove", "AccessorModifierMismatch.NoneNone.remove"),
                // (14,41): error CS0239: 'Derived.AbstractSealed': cannot override inherited member 'AccessorModifierMismatch.AbstractSealed' because it is sealed
                //     public override event System.Action AbstractSealed { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "AbstractSealed").WithArguments("Derived.AbstractSealed", "AccessorModifierMismatch.AbstractSealed"),
                
                // (16,63): error CS0506: 'Derived.VirtualNone.remove': cannot override inherited member 'AccessorModifierMismatch.NoneNone.remove' because it is not marked virtual, abstract, or override
                //     public override event System.Action VirtualNone { add { } remove { } } // CS0506 (remove not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "remove").WithArguments("Derived.VirtualNone.remove", "AccessorModifierMismatch.NoneNone.remove"),
                // (20,41): error CS0239: 'Derived.VirtualSealed': cannot override inherited member 'AccessorModifierMismatch.VirtualSealed' because it is sealed
                //     public override event System.Action VirtualSealed { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "VirtualSealed").WithArguments("Derived.VirtualSealed", "AccessorModifierMismatch.VirtualSealed"),
                
                // (22,64): error CS0506: 'Derived.OverrideNone.remove': cannot override inherited member 'AccessorModifierMismatch.NoneNone.remove' because it is not marked virtual, abstract, or override
                //     public override event System.Action OverrideNone { add { } remove { } } // CS0506 (remove not virtual)
                Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "remove").WithArguments("Derived.OverrideNone.remove", "AccessorModifierMismatch.NoneNone.remove"),
                // (26,41): error CS0239: 'Derived.OverrideSealed': cannot override inherited member 'AccessorModifierMismatch.OverrideSealed' because it is sealed
                //     public override event System.Action OverrideSealed { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "OverrideSealed").WithArguments("Derived.OverrideSealed", "AccessorModifierMismatch.OverrideSealed"),
                
                // (28,41): error CS0239: 'Derived.SealedNone': cannot override inherited member 'AccessorModifierMismatch.SealedNone' because it is sealed
                //     public override event System.Action SealedNone { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedNone").WithArguments("Derived.SealedNone", "AccessorModifierMismatch.SealedNone"),
                // (29,41): error CS0239: 'Derived.SealedAbstract': cannot override inherited member 'AccessorModifierMismatch.SealedAbstract' because it is sealed
                //     public override event System.Action SealedAbstract { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedAbstract").WithArguments("Derived.SealedAbstract", "AccessorModifierMismatch.SealedAbstract"),
                // (30,41): error CS0239: 'Derived.SealedVirtual': cannot override inherited member 'AccessorModifierMismatch.SealedVirtual' because it is sealed
                //     public override event System.Action SealedVirtual { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedVirtual").WithArguments("Derived.SealedVirtual", "AccessorModifierMismatch.SealedVirtual"),
                // (31,41): error CS0239: 'Derived.SealedOverride': cannot override inherited member 'AccessorModifierMismatch.SealedOverride' because it is sealed
                //     public override event System.Action SealedOverride { add { } remove { } } // CS1545 (bogus)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedOverride").WithArguments("Derived.SealedOverride", "AccessorModifierMismatch.SealedOverride"),
                // (32,41): error CS0239: 'Derived.SealedSealed': cannot override inherited member 'AccessorModifierMismatch.SealedSealed' because it is sealed
                //     public override event System.Action SealedSealed { add { } remove { } } // CS0239 (sealed)
                Diagnostic(ErrorCode.ERR_CantOverrideSealed, "SealedSealed").WithArguments("Derived.SealedSealed", "AccessorModifierMismatch.SealedSealed"));
        }
コード例 #43
0
ファイル: NoPiaEmbedTypes.cs プロジェクト: Rickinio/roslyn
        public void Bug611578()
        {
            string IEvent_cs = @"
using System;
using System.Runtime.InteropServices;

[assembly: ImportedFromTypeLib(""NoPiaTest"")]
[assembly: Guid(""ECED788D-2448-447A-B786-1646D2DBEEEE"")]

public delegate void EventDelegate01(ref bool p);
public delegate string EventDelegate02(string p);

/// <summary>
/// Source Interface
/// </summary>
[ComImport, Guid(""904458F3-005B-4DFD-8581-E9832DDFA433"")]
public interface IEventsBase
{
    [DispId(101), PreserveSig]
    void MyEvent01(ref bool p);
}

[ComImport, Guid(""904458F3-005B-4DFD-8581-E9832D7DA433"")]
public interface IEventsDerived : IEventsBase
{
    [DispId(102), PreserveSig]
    string MyEvent02(string p);
}

/// <summary>
/// Event Interface
/// </summary>
[ComEventInterface(typeof(IEventsDerived), typeof(int))]
[ComVisible(false)]
public interface IEventsDerived_Event
{
    event EventDelegate01 MyEvent01;
    event EventDelegate02 MyEvent02;
}
";

            var IEvent_Compilation = CreateCompilationWithMscorlib(IEvent_cs, options: TestOptions.ReleaseDll, assemblyName: "IEvent");

            CompileAndVerify(IEvent_Compilation);
            var IEvent_Metadata = AssemblyMetadata.CreateFromImage(IEvent_Compilation.EmitToArray());

            string NetImpl_cs = @"
using System;
using System.Collections;
using System.Collections.Generic;

public class NetImpl : IEventsDerived_Event
{
    // Unique keys for events
    static readonly object[] myEventKeyList = new object[] { new object(), new object() };
    Hashtable eventTable = new Hashtable();

    #region Shared Func
    // return event handle associated with the key
    protected Delegate GetEventHandlerDelegate(int index)
    {
        object key = myEventKeyList[index];
        return eventTable[key] as Delegate;
    }

    // add event handle associated with the key
    protected void AddEventHandlerDelegate(int index, Delegate handler)
    {
        lock (eventTable)
        {
            object key = myEventKeyList[index];
            switch (index)
            {
                case 0:
                    eventTable[key] = (EventDelegate01)eventTable[key] + (EventDelegate01)handler;
                    break;
                case 1:
                    eventTable[key] = (EventDelegate02)eventTable[key] + (EventDelegate02)handler;
                    break;
            }
        }
    }

    // remove event handle associated with the key
    protected void RemoveEventHandlerDelegate(int index, Delegate handler)
    {
        lock (eventTable)
        {
            object key = myEventKeyList[index];
            switch (index)
            {
                case 0:
                    eventTable[key] = (EventDelegate01)eventTable[key] - (EventDelegate01)handler;
                    break;
                case 1:
                    eventTable[key] = (EventDelegate02)eventTable[key] - (EventDelegate02)handler;
                    break;
            }
        }
    }
    #endregion

    #region Impl Event
    event EventDelegate01 IEventsDerived_Event.MyEvent01
    {
        add { AddEventHandlerDelegate(0, value); }
        remove { RemoveEventHandlerDelegate(0, value); }
    }

    event EventDelegate02 IEventsDerived_Event.MyEvent02
    {
        add { AddEventHandlerDelegate(1, value); }
        remove { RemoveEventHandlerDelegate(1, value); }
    }

    #endregion

    #region Fire Event

    public void Fire01(ref bool arg, int idx = 0)
    {
        EventDelegate01 e = GetEventHandlerDelegate(idx) as EventDelegate01;
        if (null != e)
            e(ref arg);
    }

    public string Fire02(string arg, int idx = 1)
    {
        EventDelegate02 e = GetEventHandlerDelegate(idx) as EventDelegate02;
        if (null != e)
            return e(arg);
        return String.Empty;
    }

    #endregion
}
";

            System.Action<ModuleSymbol> metadataValidator =
                delegate (ModuleSymbol module)
                {
                    ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes();

                    var IEventsBase = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("IEventsBase").Single();
                    Assert.Equal(1, IEventsBase.GetMembers("MyEvent01").Length);
                };

            var NetImpl_1_Compilation = CreateCompilationWithMscorlib(NetImpl_cs, new[] { new CSharpCompilationReference(IEvent_Compilation, embedInteropTypes: true) }, options: TestOptions.ReleaseDll, assemblyName: "NetImpl");

            CompileAndVerify(NetImpl_1_Compilation, symbolValidator: metadataValidator);
            var NetImpl_1_Image = NetImpl_1_Compilation.EmitToStream();

            var NetImpl_2_Compilation = CreateCompilationWithMscorlib(NetImpl_cs, new[] { IEvent_Metadata.GetReference(embedInteropTypes: true) }, options: TestOptions.ReleaseDll, assemblyName: "NetImpl");

            CompileAndVerify(NetImpl_2_Compilation, symbolValidator: metadataValidator);
            var NetImpl_2_Image = NetImpl_2_Compilation.EmitToStream();

            string App_cs = @"
using System;

class Test
{
    public static void Main()
    {
        var obj = new NetImpl();
        var d1 = false;
        dynamic d2 = ""123"";
        // cast to interface
        IEventsDerived_Event iobj = obj;

        // Event 1
        iobj.MyEvent01 += new EventDelegate01(MyEvent01Handler);
        obj.Fire01(ref d1);

        // Event 2
        iobj.MyEvent02 += new EventDelegate02(MyEvent02Handler);
        obj.Fire02(d2);
    }

    #region Event Handlers

    static void MyEvent01Handler(ref bool arg)
    {
        Console.WriteLine(""E01"");
        arg = true;
    }

    static string MyEvent02Handler(string arg)
    {
        Console.WriteLine(""E02"");
        return arg;
    }

    #endregion
}
";

            MetadataReference[] NetImpl_refs = new MetadataReference[] { new CSharpCompilationReference(NetImpl_1_Compilation),
                                                                         new CSharpCompilationReference(NetImpl_2_Compilation),
                                                                         MetadataReference.CreateFromStream(NetImpl_1_Image),
                                                                         MetadataReference.CreateFromStream(NetImpl_2_Image)};

            MetadataReference[] IEvent_refs = new MetadataReference[] { new CSharpCompilationReference(IEvent_Compilation),
                                                                        new CSharpCompilationReference(IEvent_Compilation, embedInteropTypes: true),
                                                                        IEvent_Metadata.GetReference(),
                                                                        IEvent_Metadata.GetReference(embedInteropTypes: true)};

            foreach (var NetImpl_ref in NetImpl_refs)
            {
                foreach (var IEvent_ref in IEvent_refs)
                {
                    var app_compilation = CreateCompilationWithMscorlib(App_cs, new[] { NetImpl_ref, IEvent_ref, CSharpRef, SystemCoreRef }, options: TestOptions.ReleaseExe, assemblyName: "App");

                    CompileAndVerify(app_compilation, symbolValidator: IEvent_ref.Properties.EmbedInteropTypes ? metadataValidator : null,
                        expectedOutput: @"E01
E02");
                }
            }
        }
コード例 #44
0
 private Metadata GetMetadata(MetadataReference mref)
 {
     var fnGetMetadata = mref.GetType().GetMethod("GetMetadata", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
     return fnGetMetadata?.Invoke(mref, null) as Metadata;
 }
コード例 #45
0
 public void SerializeMetadataReference(MetadataReference reference, ObjectWriter writer, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     _hostSerializationService.WriteTo(reference, writer, cancellationToken);
 }
コード例 #46
0
        /// <summary>
        /// Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation.
        /// </summary>
        /// <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or null if there is none.</returns>
        /// <remarks>
        /// Uses object identity when comparing two references. 
        /// </remarks>
        internal new Symbol GetAssemblyOrModuleSymbol(MetadataReference reference)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            if (reference.Properties.Kind == MetadataImageKind.Assembly)
            {
                return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference);
            }
            else
            {
                Debug.Assert(reference.Properties.Kind == MetadataImageKind.Module);
                int index = GetBoundReferenceManager().GetReferencedModuleIndex(reference);
                return index < 0 ? null : this.Assembly.Modules[index];
            }
        }
コード例 #47
0
 private static PortableExecutableReference GetReference <T>()
 {
     return(MetadataReference.CreateFromFile(typeof(T).GetTypeInfo().Assembly.Location));
 }
コード例 #48
0
ファイル: PrivateProtected.cs プロジェクト: namse/Roslyn-CSX
        public void AccessibleWhereRequired_02()
        {
            string source1 =
                @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
public class Base
{
    private protected const int Constant = 3;
    private protected int Field1;
    protected private int Field2;
    private protected void Method() { }
    private protected event System.Action Event1;
    private protected int Property1 { set {} }
    public int Property2 { private protected set {} get { return 4; } }
    private protected int this[int x] { set { } get { return 6; } }
    public int this[string x] { private protected set { } get { return 5; } }
    private protected Base() { Event1?.Invoke(); }
}";
            var baseCompilation = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2,
                                                    options: TestOptions.SigningReleaseDll,
                                                    assemblyName: "Paul");
            var bb = (INamedTypeSymbol)baseCompilation.GlobalNamespace.GetMember("Base");

            foreach (var member in bb.GetMembers())
            {
                switch (member.Name)
                {
                case "Property2":
                case "get_Property2":
                case "this[]":
                case "get_Item":
                    break;

                default:
                    Assert.Equal(Accessibility.ProtectedAndInternal, member.DeclaredAccessibility);
                    break;
                }
            }

            string source2 =
                @"public class Derived : Base
{
    void M()
    {
        Field1 = Constant;
        Field2 = Constant;
        Method();
        Event1 += null;
        Property1 = Constant;
        Property2 = Constant;
        this[1] = 2;
        this[string.Empty] = 4;
    }
    Derived(int x) : base() {}
    Derived(long x) {} // implicit base()
}
";

            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                              references: new[] { new CSharpCompilationReference(baseCompilation) },
                              assemblyName: "WantsIVTAccessButCantHave",
                              options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                // (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
                // (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
                // (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
                // (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
                // (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
                //         Method();
                Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
                // (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
                // (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
                // (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
                // (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
                // (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
                // (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
                // (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
                //         this[1] = 2;
                Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
                // (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
                //         this[string.Empty] = 4;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
                // (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(int x) : base() {}
                Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
                // (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(long x) {} // implicit base()
                Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
                );
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                              references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
                              assemblyName: "WantsIVTAccessButCantHave",
                              options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                // (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
                // (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
                // (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
                // (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
                // (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
                //         Method();
                Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
                // (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
                // (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
                // (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
                // (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
                // (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
                // (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
                // (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
                //         this[1] = 2;
                Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
                // (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
                //         this[string.Empty] = 4;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
                // (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(int x) : base() {}
                Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
                // (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(long x) {} // implicit base()
                Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
                );

            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                              references: new[] { new CSharpCompilationReference(baseCompilation) },
                              assemblyName: "WantsIVTAccess",
                              options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                );
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                              references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
                              assemblyName: "WantsIVTAccess",
                              options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                );
        }
コード例 #49
0
ファイル: CodeGenDynamicTests.cs プロジェクト: nemec/roslyn
        private MetadataReference MakeCSharpRuntime(string excludeBinder = null, bool excludeBinderFlags = false, bool excludeArgumentInfoFlags = false, MetadataReference systemCore = null)
        {
            var sb = new StringBuilder();

            sb.AppendLine(excludeBinderFlags ? "public enum CSharpBinderFlags { A }" : CSharpBinderFlagsSource);
            sb.AppendLine(excludeArgumentInfoFlags ? "public enum CSharpArgumentInfoFlags { A }" : CSharpArgumentInfoFlagsSource);
            sb.AppendLine(CSharpArgumentInfoSource);

            foreach (var src in excludeBinder == null ? _binderFactoriesSource : _binderFactoriesSource.Where(src => src.IndexOf(excludeBinder, StringComparison.Ordinal) == -1))
            {
                sb.AppendFormat("public partial class Binder {{ public static {0} {{ return null; }} }}", src);
                sb.AppendLine();
            }

            string source = string.Format(CSharpBinderTemplate, sb.ToString());
            return CreateCompilationWithMscorlib(source, new[] { systemCore ?? SystemCoreRef }, assemblyName: GetUniqueName()).EmitToImageReference();
        }
コード例 #50
0
        /// <summary>
        /// Creates the assembly for an app.
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="app">Application identifier which is unique within an organisation.</param>
        /// <param name="startAppFlag">Flag to determine if the app should run/re-run.</param>
        /// <param name="outputLocation">The directory where the resulting assembly should be saved.</param>
        /// <param name="loadAssemblyContext">Defines if assembly should be loaded in context.</param>
        /// <returns>The assembly name.</returns>
        public CodeCompilationResult CreateServiceAssembly(string org, string app, bool startAppFlag, string outputLocation = null, bool loadAssemblyContext = true)
        {
            CodeCompilationResult compilationResult = new CodeCompilationResult()
            {
                CompileStarted = DateTime.Now
            };
            string assemblykey = org + "_" + CompileHelper.GetCSharpValidAppId(app);
            List <AltinnCoreFile> implementationFiles = _repository.GetImplementationFiles(org, app);

            DateTime lastChanged = new DateTime(2000, 01, 01);

            foreach (AltinnCoreFile file in implementationFiles)
            {
                if (file.LastChanged > lastChanged)
                {
                    lastChanged = file.LastChanged;
                }
            }

            SyntaxTree[]             syntaxTrees = GetSyntaxTrees(org, app);
            List <MetadataReference> references  = new List <MetadataReference>();
            Assembly root = Assembly.GetEntryAssembly();

            string assemblyName = Path.GetRandomFileName();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            List <string> assembliesPath = new List <string>();

            for (int i = 0; i < assemblies.Count(); i++)
            {
                if (!assemblies[i].IsDynamic)
                {
                    if (!string.IsNullOrEmpty(assemblies[i].FullName) && !string.IsNullOrEmpty(assemblies[i].Location))
                    {
                        assembliesPath.Add(assemblies[i].Location);
                    }
                }
            }

            var refFeature = new MetadataReference[assembliesPath.Count];

            for (int i = 0; i < assembliesPath.Count(); i++)
            {
                if (!string.IsNullOrEmpty(assembliesPath[i]))
                {
                    if (MetadataReference.CreateFromFile(assembliesPath[i]) != null)
                    {
                        refFeature[i] = MetadataReference.CreateFromFile(assembliesPath[i]);
                    }
                }
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: syntaxTrees,
                references: refFeature,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var pdbMs = new MemoryStream())
                using (var ms = new MemoryStream())
                {
                    EmitResult result;
                    Stopwatch  stopWatch = new Stopwatch();
                    stopWatch.Start();
                    if (!string.IsNullOrEmpty(outputLocation))
                    {
                        result = compilation.Emit(outputLocation + assemblyName + ".dll", outputLocation + assemblyName + ".pdb");
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbMs);
                    }

                    stopWatch.Stop();
                    compilationResult.TimeUsed = stopWatch.Elapsed;

                    compilationResult.CompilationInfo = new List <CompilationInfo>();
                    foreach (Diagnostic diag in result.Diagnostics)
                    {
                        // TODO: Decide how to handle this special CS1701 we get
                        if (!diag.Id.Equals("CS1701"))
                        {
                            var compInfo = new CompilationInfo
                            {
                                Info         = diag.GetMessage(),
                                FilePath     = diag.Location.SourceTree.FilePath,
                                FileName     = System.IO.Path.GetFileName(diag.Location.SourceTree.FilePath),
                                Severity     = diag.Severity.ToString(),
                                Code         = diag.Id,
                                WarningLevel = diag.WarningLevel,
                                LineNumber   = diag.Location.GetLineSpan().StartLinePosition.Line + 1,
                            };

                            if (diag.Severity.Equals(DiagnosticSeverity.Warning))
                            {
                                compilationResult.Warnings++;
                            }
                            else if (diag.Severity.Equals(DiagnosticSeverity.Error))
                            {
                                compilationResult.Errors++;
                            }

                            compilationResult.CompilationInfo.Add(compInfo);
                        }
                    }

                    if (!result.Success)
                    {
                        LogEmitResult(result);
                    }
                    else
                    {
                        compilationResult.AssemblyName = compilation.AssemblyName;
                        compilationResult.Succeeded    = true;

                        if (string.IsNullOrEmpty(outputLocation) && loadAssemblyContext)
                        {
                            ms.Seek(0, SeekOrigin.Begin);
                            pdbMs.Seek(0, SeekOrigin.Begin);
                            AssemblyLoadContext.Default.LoadFromStream(ms, pdbMs);
                            ms.Seek(0, SeekOrigin.Begin);
                            MetadataReference newReference = MetadataReference.CreateFromStream(ms);
                            if (_roslynCompilation.ServiceReferences.ContainsKey(assemblykey))
                            {
                                _roslynCompilation.ServiceReferences.Remove(assemblykey);
                            }

                            _roslynCompilation.ServiceReferences.Add(assemblykey, newReference);

                            if (_assemblyNames.ContainsKey(assemblykey))
                            {
                                _assemblyNames.Remove(assemblykey);
                            }

                            _assemblyNames.Add(assemblykey, compilationResult);
                        }

                        return(compilationResult);
                    }
                }

            return(compilationResult);
        }
コード例 #51
0
        public void TestMixedPropertyAccessorModifiers_EmptyAbstract()
        {
            var text1 = @"
abstract class Derived : AccessorModifierMismatch
{
    // Not overriding anything.
}
";
            var refs = new MetadataReference[] { TestReferences.SymbolsTests.Properties };
            CreateCompilationWithMscorlib(text1, references: refs, compOptions: TestOptions.Dll).VerifyDiagnostics();
        }
コード例 #52
0
 static MetadataReference CreateMetadataReference(string path) => MetadataReference.CreateFromFile(path);
コード例 #53
0
        public void TestMixedEventAccessorModifiers_EmptyConcrete()
        {
            var text1 = @"
class Derived : AccessorModifierMismatch
{
    // Not overriding anything.
}
";
            var refs = new MetadataReference[] { TestReferences.SymbolsTests.Events };
            CreateCompilationWithMscorlib(text1, references: refs, compOptions: TestOptions.Dll).VerifyDiagnostics(
                // (2,7): error CS0534: 'Derived' does not implement inherited abstract member 'AccessorModifierMismatch.NoneAbstract.remove'
                // class Derived : AccessorModifierMismatch
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "AccessorModifierMismatch.NoneAbstract.remove"),
                // (2,7): error CS0534: 'Derived' does not implement inherited abstract member 'AccessorModifierMismatch.AbstractNone.add'
                // class Derived : AccessorModifierMismatch
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "AccessorModifierMismatch.AbstractNone.add"));
        }
コード例 #54
0
        public void SeparateCompilation()
        {
            // Here we test round tripping - emitting a fixed-size buffer into metadata, and then reimporting that
            // fixed-size buffer from metadata and using it in another compilation.
            var s1 =
                @"public unsafe struct S
{
    public fixed int x[10];
}";
            var s2 =
                @"using System;
class Program
{
    static void Main()
    {
        S s;
        unsafe
        {
            int* p = s.x;
            s.x[0] = 12;
            p[1] = p[0];
            Console.WriteLine(s.x[1]);
        }
        S t = s;
    }
}";
            var comp1 = CompileAndVerify(s1, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).Compilation;

            var comp2 = (CSharpCompilation)CompileAndVerify(s2,
                                                            options: TestOptions.UnsafeReleaseExe,
                                                            references: new MetadataReference[] { MetadataReference.CreateFromStream(comp1.EmitToStream()) },
                                                            expectedOutput: "12", verify: Verification.Fails).Compilation;

            var f = (FieldSymbol)comp2.GlobalNamespace.GetTypeMembers("S")[0].GetMembers("x")[0];

            Assert.Equal("x", f.Name);
            Assert.True(f.IsFixedSizeBuffer);
            Assert.Equal("int*", f.TypeWithAnnotations.ToString());
            Assert.Equal(10, f.FixedSize);
        }
コード例 #55
0
 protected override Compilation GetCompilationForEmit(IEnumerable<string> source, MetadataReference[] additionalRefs, CompilationOptions options)
 {
     throw new NotImplementedException();
 }
コード例 #56
0
        public byte[] Compile(string[] text, string[] extraReferences = null)
        {
            List <Microsoft.CodeAnalysis.SyntaxTree> syntaxTrees = new List <Microsoft.CodeAnalysis.SyntaxTree>();

            for (int i = 0; i < text.Length; ++i)
            {
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(text[i]));
            }

            string           assemblyName = Path.GetRandomFileName();
            HashSet <string> references   = new HashSet <string>
            {
                typeof(object).Assembly.Location,
                typeof(Enumerable).Assembly.Location,
                typeof(Object).Assembly.Location,
                typeof(Input).Assembly.Location,
                typeof(Rigidbody).Assembly.Location,
                typeof(AudioSource).Assembly.Location,
                typeof(Animator).Assembly.Location,
                typeof(ParticleSystem).Assembly.Location,
                typeof(Text).Assembly.Location,
                typeof(Canvas).Assembly.Location,
                Assembly.GetCallingAssembly().Location
            };

            if (extraReferences != null)
            {
                for (int i = 0; i < extraReferences.Length; ++i)
                {
                    if (!references.Contains(extraReferences[i]))
                    {
                        references.Add(extraReferences[i]);
                    }
                }
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: syntaxTrees,
                references: references.Select(r => MetadataReference.CreateFromFile(r)),
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Debug.LogErrorFormat("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                    return(null);
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(ms.ToArray());
            }
        }
コード例 #57
0
 protected override ISymbol CommonGetAssemblyOrModuleSymbol(MetadataReference reference)
 {
     return this.GetAssemblyOrModuleSymbol(reference);
 }
コード例 #58
0
        public static ClangSharpSourceCompilation Create(
            string sourceDirectory,
            string interopFileName,
            Dictionary <string, string> remaps,
            Dictionary <string, string> typeImports,
            Dictionary <string, string> requiredNamespaces)
        {
            sourceDirectory = Path.GetFullPath(sourceDirectory);

            var netstandardPath = FindNetstandardDllPath();

            if (!File.Exists(netstandardPath))
            {
                throw new FileNotFoundException("Failed to find the netstandard DLL.");
            }

            List <MetadataReference> refs = new List <MetadataReference>();

            refs.Add(MetadataReference.CreateFromFile(interopFileName));
            refs.Add(MetadataReference.CreateFromFile(netstandardPath));

            List <SyntaxTree> syntaxTrees = new List <SyntaxTree>();
            var sourceFiles = Directory.GetFiles(sourceDirectory, "*.cs", SearchOption.AllDirectories);

            System.Threading.Tasks.ParallelOptions opt = new System.Threading.Tasks.ParallelOptions()
            {
                MaxDegreeOfParallelism = Environment.ProcessorCount * 2
            };
            System.Threading.Tasks.Parallel.ForEach(sourceFiles, opt, (sourceFile) =>
            {
                if (sourceFile.EndsWith("modified.cs"))
                {
                    return;
                }

                string fileToRead = Path.GetFullPath(sourceFile);
                var tree          = CSharpSyntaxTree.ParseText(File.ReadAllText(fileToRead), null, fileToRead);

                lock (syntaxTrees)
                {
                    syntaxTrees.Add(tree);
                }
            });

            syntaxTrees = NamesToCorrectNamespacesMover.MoveNamesToCorrectNamespaces(syntaxTrees, requiredNamespaces);

            HashSet <string> foundNonEmptyStructs = GetNonEmptyStructs(syntaxTrees);

#if MakeSingleThreaded
            opt.MaxDegreeOfParallelism = 1;
#endif

            string objDir = Path.Combine(sourceDirectory, "obj");
            Directory.CreateDirectory(objDir);

            List <SyntaxTree> cleanedTrees = new List <SyntaxTree>();
            System.Threading.Tasks.Parallel.ForEach(syntaxTrees, opt, (tree) =>
            {
                // Turn c:\dir\generated\foo.cs into c:\dir\generated\obj\foo.modified.cs

                string modifiedFile   = Path.ChangeExtension(tree.FilePath, ".modified.cs");
                string fileWithSubDir = modifiedFile.Substring(sourceDirectory.Length);
                if (fileWithSubDir.StartsWith('\\'))
                {
                    fileWithSubDir = fileWithSubDir.Substring(1);
                }

                modifiedFile = Path.Combine(objDir, fileWithSubDir);

                // e.g. c:\dir\generated\obj
                string newSubDir = Path.GetDirectoryName(modifiedFile);
                if (!Directory.Exists(newSubDir))
                {
                    Directory.CreateDirectory(newSubDir);
                }

                var cleanedTree = MetadataSyntaxTreeCleaner.CleanSyntaxTree(tree, remaps, requiredNamespaces, foundNonEmptyStructs, modifiedFile);
                File.WriteAllText(modifiedFile, cleanedTree.GetText().ToString());

                lock (cleanedTrees)
                {
                    cleanedTrees.Add(cleanedTree);
                }
            });

            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, allowUnsafe: true);
            var comp =
                CSharpCompilation.Create(
                    null,
                    cleanedTrees,
                    refs,
                    compilationOptions);

            return(new ClangSharpSourceCompilation(comp, typeImports));
        }
コード例 #59
0
 /// <summary>
 /// Creates a new compilation with an old metadata reference replaced with a new metadata reference.
 /// </summary>
 public new CSharpCompilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference)
 {
     return (CSharpCompilation)base.ReplaceReference(oldReference, newReference);
 }
コード例 #60
0
 public MetadataReference GetMetadataReference(string path)
 {
     return(cache.GetOrAdd(path, filePath => {
         return MetadataReference.CreateFromFile(filePath);
     }));
 }