• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Emit.PEAssemblyBuilder类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Emit.PEAssemblyBuilder的典型用法代码示例。如果您正苦于以下问题:C# PEAssemblyBuilder类的具体用法?C# PEAssemblyBuilder怎么用?C# PEAssemblyBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



PEAssemblyBuilder类属于Microsoft.CodeAnalysis.CSharp.Emit命名空间,在下文中一共展示了PEAssemblyBuilder类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ParseAndBindMethodBody

        internal static BoundStatement ParseAndBindMethodBody(string program, bool lower, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                // Provide an Emit.Module so that the lowering passes will be run
                var module = new PEAssemblyBuilder(
                    (SourceAssemblySymbol)compilation.Assembly,
                    EmitOptions.Default,
                    OutputKind.ConsoleApplication,
                    GetDefaultModulePropertiesForSerialization(),
                    Enumerable.Empty<ResourceDescription>(),
                    assemblySymbolMapper: null);

                TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module);

                var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics);
                if ((block == null) || !lower)
                {
                    return block;
                }

                StateMachineTypeSymbol stateMachineTypeOpt;
                VariableSlotAllocator lazyVariableSlotAllocator = null;
                var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
                var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();

                var body = MethodCompiler.LowerBodyOrInitializer(
                    method: method,
                    methodOrdinal: 0,
                    body: block,
                    previousSubmissionFields: null,
                    compilationState: compilationState,
                    diagnostics: diagnostics,
                    lazyVariableSlotAllocator: ref lazyVariableSlotAllocator,
                    lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
                    closureDebugInfoBuilder: closureDebugInfoBuilder,
                    stateMachineTypeOpt: out stateMachineTypeOpt);

                lambdaDebugInfoBuilder.Free();
                closureDebugInfoBuilder.Free();

                return body;
            }
            finally
            {
                diagnostics.Free();
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:51,代码来源:CompilingTestBase.cs


示例2: ParseAndBindMethodBody

        internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();

            // Provide an Emit.Module so that the lowering passes will be run
            var module = new PEAssemblyBuilder(
                (SourceAssemblySymbol)compilation.Assembly,
                emitOptions: EmitOptions.Default,
                outputKind: OutputKind.ConsoleApplication,
                serializationProperties: GetDefaultModulePropertiesForSerialization(),
                manifestResources: Enumerable.Empty<ResourceDescription>());

            TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module);

            var diagnostics = DiagnosticBag.GetInstance();
            var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics);
            diagnostics.Free();
            return block;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:20,代码来源:CompilingTestBase.cs


示例3: ParseAndBindMethodBody

        internal static BoundStatement ParseAndBindMethodBody(string program, bool lower, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                var block = Compiler.BindMethodBody(method, diagnostics);
                if ((block == null) || !lower)
                {
                    return block;
                }

                // Provide an Emit.Module so that the lowering passes will be run
                var module = new PEAssemblyBuilder(
                    (SourceAssemblySymbol)compilation.Assembly,
                    null,
                    OutputKind.ConsoleApplication,
                    GetDefaultModulePropertiesForSerialization(),
                    Enumerable.Empty<ResourceDescription>(),
                    assemblySymbolMapper: null);

                TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, module);

                var body = Compiler.LowerStatement(
                    generateDebugInfo: true,
                    method: method,
                    body: block,
                    previousSubmissionFields: null,
                    compilationState: compilationState,
                    diagnostics: diagnostics);

                return body;
            }
            finally
            {
                diagnostics.Free();
            }
        }
开发者ID:riversky,项目名称:roslyn,代码行数:39,代码来源:CompilingTestBase.cs


示例4: VerifyParamArrayAttribute

        internal static void VerifyParamArrayAttribute(ParameterSymbol parameter, SourceModuleSymbol module, bool expected = true, OutputKind outputKind = OutputKind.ConsoleApplication)
        {
            Assert.Equal(expected, parameter.IsParams);

            var emitModule = new PEAssemblyBuilder(module.ContainingSourceAssembly, null, outputKind, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var paramArrayAttributeCtor = (MethodSymbol)emitModule.Compilation.GetWellKnownTypeMember(WellKnownMember.System_ParamArrayAttribute__ctor);
            bool found = false;

            var context = new EmitContext(emitModule, null, new DiagnosticBag());

            foreach (Microsoft.Cci.ICustomAttribute attr in parameter.GetSynthesizedAttributes())
            {
                if (paramArrayAttributeCtor == (MethodSymbol)attr.Constructor(context))
                {
                    Assert.False(found, "Multiple ParamArrayAttribute");
                    found = true;
                }
            }

            Assert.Equal(expected, found);
            context.Diagnostics.Verify();
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:22,代码来源:WellKnownAttributesTestBase.cs


示例5: EmitMetadataOnly_SynthesizedExplicitImplementations

        public void EmitMetadataOnly_SynthesizedExplicitImplementations()
        {
            var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;

            var libAssemblyName = "SynthesizedMethodMetadata";
            var exeAssemblyName = "CallSynthesizedMethod";

            // Setup: CppBase2 has methods that implement CppInterface1, but it doesn't declare
            // that it implements the interface.  Class1 does declare that it implements the
            // interface, but it's empty so it counts on CppBase2 to provide the implementations.
            // Since CppBase2 is not in the current source module, bridge methods are inserted
            // into Class1 to implement the interface methods by delegating to CppBase2.
            var libText = @"
public class Class1 : CppCli.CppBase2, CppCli.CppInterface1
{
}
";

            var libComp = CreateCompilationWithMscorlib(
                text: libText,
                references: new MetadataReference[] { ilAssemblyReference },
                compOptions: TestOptions.Dll,
                assemblyName: libAssemblyName);

            Assert.False(libComp.GetDiagnostics().Any());

            EmitResult emitResult;
            byte[] dllImage;
            using (var output = new MemoryStream())
            {
                emitResult = libComp.EmitMetadataOnly(output);
                dllImage = output.ToArray();
            }

            Assert.True(emitResult.Success);
            emitResult.Diagnostics.Verify();
            Assert.True(dllImage.Length > 0, "no metadata emitted");

            // NOTE: this DLL won't PEVerify because there are no method bodies.

            var class1 = libComp.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("Class1");

            // We would prefer to check that the module used by Compiler.Emit does the right thing,
            // but we don't have access to that object, so we'll create our own and manipulate it
            // in the same way.
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)class1.ContainingAssembly, null,
                OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            Compiler.CompileSynthesizedMethodMetadata(libComp, module, default(CancellationToken));

            var class1TypeDef = (Cci.ITypeDefinition)class1;

            var symbolSynthesized = class1.GetSynthesizedExplicitImplementations(CancellationToken.None);
            var context = new Microsoft.CodeAnalysis.Emit.Context(module, null, new DiagnosticBag());
            var cciExplicit = class1TypeDef.GetExplicitImplementationOverrides(context);
            var cciMethods = class1TypeDef.GetMethods(context).Where(m => ((MethodSymbol)m).MethodKind != MethodKind.Constructor);

            context.Diagnostics.Verify();
            var symbolsSynthesizedCount = symbolSynthesized.Length;
            Assert.True(symbolsSynthesizedCount > 0, "Expected more than 0 synthesized method symbols.");
            Assert.Equal(symbolsSynthesizedCount, cciExplicit.Count());
            Assert.Equal(symbolsSynthesizedCount, cciMethods.Count());

            var libAssemblyReference = new MetadataImageReference(dllImage.AsImmutableOrNull());

            var exeText = @"
class Class2
{
    public static void Main()
    {
        CppCli.CppInterface1 c = new Class1();
        c.Method1(1);
        c.Method2(2);
    }
}  
";

            var exeComp = CreateCompilationWithMscorlib(
                text: exeText,
                references: new MetadataReference[] { ilAssemblyReference, libAssemblyReference },
                assemblyName: exeAssemblyName);

            Assert.False(exeComp.GetDiagnostics().Any());

            using (var output = new MemoryStream())
            {
                emitResult = exeComp.Emit(output);

                Assert.True(emitResult.Success);
                emitResult.Diagnostics.Verify();
                output.Flush();
                Assert.True(output.Length > 0, "no metadata emitted");
            }

            // NOTE: there's no point in trying to run the EXE since it depends on a DLL with no method bodies.
        }
开发者ID:riversky,项目名称:roslyn,代码行数:95,代码来源:CompilationEmitTests.cs


示例6: IgnoreOtherDiagnosticsCompilingSynthesizedMethods

        public void IgnoreOtherDiagnosticsCompilingSynthesizedMethods()
        {
            var source =
@"class C
{
    static object F = new object(); // generate .cctor
    static System.Action M()
    {
        return () => { }; // generate lambda
    }
}";
            var compilation = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseDll.WithConcurrentBuild(false));
            var options = compilation.Options;
            var diagnostics = DiagnosticBag.GetInstance();

            var assembly = (SourceAssemblySymbol)compilation.Assembly;
            var module = new PEAssemblyBuilder(
                assembly,
                EmitOptions.Default,
                options.OutputKind,
                GetDefaultModulePropertiesForSerialization(),
                new ResourceDescription[0]);

            var methodBodyCompiler = new MethodCompiler(
                compilation: compilation,
                moduleBeingBuiltOpt: module,
                emittingPdb: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: CancellationToken.None);

            // Add diagnostic to MethodBodyCompiler bag, as if
            // code gen for an earlier method had generated an error.
            diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IntDivByZero), NoLocation.Singleton));

            // Compile all methods for type including synthesized methods.
            var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
            methodBodyCompiler.Visit(type);

            Assert.Equal(1, diagnostics.AsEnumerable().Count());
            diagnostics.Free();
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:43,代码来源:CodeGenTests.cs


示例7: MethodAccessorMethodOverriding

        public void MethodAccessorMethodOverriding()
        {
            var text = @"
public class A
{
    public virtual int get_P() { return 0; }
}

public class B : A
{
    public virtual int P { get; set; }
}

public class C : B
{
    public override int get_P() { return 0; }
}
";
            var comp = CreateCompilationWithMscorlib(text);
            comp.VerifyDiagnostics();

            var globalNamespace = comp.GlobalNamespace;

            var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
            var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
            var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");

            var methodA = classA.GetMember<MethodSymbol>("get_P");
            var methodB = classB.GetMember<PropertySymbol>("P").GetMethod;
            var methodC = classC.GetMember<MethodSymbol>("get_P");

            var typeDefC = (Cci.ITypeDefinition)classC;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(classC, explicitOverride.ContainingType);
            Assert.Equal(methodC, explicitOverride.ImplementingMethod);
            Assert.Equal(methodA, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:41,代码来源:MethodTests.cs


示例8: ExplicitInterfaceImplementationGeneric

        public void ExplicitInterfaceImplementationGeneric()
        {
            string text = @"
namespace Namespace
{
    interface I<T>
    {
        void Method(T t);
    }
}

class IC : Namespace.I<int>
{
    void Namespace.I<int>.Method(int i) { }
}
";

            var comp = CreateCompilationWithMscorlib(Parse(text));

            var globalNamespace = comp.GlobalNamespace;
            var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single();

            var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);

            var substitutedInterface = @class.Interfaces.Single();
            Assert.Equal(@interface, substitutedInterface.ConstructedFrom);

            var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single();

            var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(substitutedInterface, explicitImpl.ContainingType);
            Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);

            var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod;
            Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context));
            Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name);
            Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount);
            context.Diagnostics.Verify();
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:56,代码来源:MethodTests.cs


示例9: ExplicitInterfaceImplementationRef

        public void ExplicitInterfaceImplementationRef()
        {
            string text = @"
interface I
{
    ref int Method(ref int i);
}

class C : I
{
    ref int I.Method(ref int i) { return ref i; }
}
";

            var comp = CreateCompilationWithMscorlib45(text);

            var globalNamespace = comp.GlobalNamespace;

            var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
            Assert.Equal(RefKind.Ref, interfaceMethod.RefKind);

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);
            Assert.True(@class.Interfaces.Contains(@interface));

            var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
            Assert.Equal(RefKind.Ref, classMethod.RefKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(interfaceMethod, explicitImpl);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);
            Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:45,代码来源:MethodTests.cs


示例10: ExplicitInterfaceImplementationCorLib

        public void ExplicitInterfaceImplementationCorLib()
        {
            string text = @"
class F : System.IFormattable
{
    string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
    {
        return null;
    }
}
";

            var comp = CreateCompilationWithMscorlib(Parse(text));

            var globalNamespace = comp.GlobalNamespace;
            var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single();

            var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single();

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);
            Assert.True(@class.Interfaces.Contains(@interface));

            var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(interfaceMethod, explicitImpl);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
               GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);
            Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:42,代码来源:MethodTests.cs


示例11: ExtensionMethod_ValidateExtensionAttribute

        public void ExtensionMethod_ValidateExtensionAttribute()
        {
            var source =
@"using System;
internal static class C
{
    internal static void M1(this object o) { }
    private static void Main(string[] args) { }
}
";
            Action<ModuleSymbol> validator = module =>
            {
                var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");

                // Extension method.
                var method = type.GetMember<MethodSymbol>("M1");
                Assert.True(method.IsExtensionMethod);
                var parameter = method.Parameters[0];
                Assert.Equal(parameter.Type.SpecialType, SpecialType.System_Object);

                // Validate Extension attribute.
                var sourceModule = (SourceModuleSymbol)module;
                var emitModule = new PEAssemblyBuilder(sourceModule.ContainingSourceAssembly, EmitOptions.Default, OutputKind.ConsoleApplication, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
                var attrs = method.GetSynthesizedAttributes();
                Assert.Equal(1, attrs.Length);
                var attr = (Microsoft.Cci.ICustomAttribute)attrs.First();

                var extensionAttrCtor = (MethodSymbol)emitModule.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor);
                Assert.NotNull(extensionAttrCtor);
                var context = new EmitContext(emitModule, null, new DiagnosticBag());
                Assert.Equal(extensionAttrCtor, attr.Constructor(context));
                Assert.NotNull(extensionAttrCtor.ContainingType);
                Assert.Equal(extensionAttrCtor.ContainingType, attr.GetType(context));
                context.Diagnostics.Verify();
            };
            CompileAndVerify(source, additionalRefs: new[] { SystemCoreRef }, sourceSymbolValidator: validator, symbolValidator: null);
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:37,代码来源:ExtensionMethodTests.cs


示例12: CheckPropertyExplicitImplementation

        private static void CheckPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty)
        {
            var interfacePropertyGetter = interfaceProperty.GetMethod;
            Assert.NotNull(interfacePropertyGetter);
            var interfacePropertySetter = interfaceProperty.SetMethod;
            Assert.NotNull(interfacePropertySetter);

            Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single());

            var classPropertyGetter = classProperty.GetMethod;
            Assert.NotNull(classPropertyGetter);
            var classPropertySetter = classProperty.SetMethod;
            Assert.NotNull(classPropertySetter);

            Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single());
            Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single());

            var typeDef = (Microsoft.Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context);
            Assert.Equal(2, explicitOverrides.Count());
            Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType)));

            // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements
            var getterOverride = explicitOverrides.First();
            Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod);
            Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context));
            Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name);

            var setterOverride = explicitOverrides.Last();
            Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod);
            Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context));
            Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name);
            context.Diagnostics.Verify();
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:38,代码来源:PropertyTests.cs


示例13: CheckEnumType

        private void CheckEnumType(NamedTypeSymbol type, Accessibility declaredAccessibility, SpecialType underlyingType)
        {
            Assert.Equal(type.BaseType.SpecialType, SpecialType.System_Enum);
            Assert.Equal(type.EnumUnderlyingType.SpecialType, underlyingType);
            Assert.Equal(type.DeclaredAccessibility, declaredAccessibility);
            Assert.True(type.IsSealed);

            // value__ field should not be exposed from type, even though it is public,
            // since we want to prevent source from accessing the field directly.
            var field = type.GetMembers(WellKnownMemberNames.EnumBackingFieldName).SingleOrDefault() as FieldSymbol;
            Assert.Null(field);

            var sourceType = type as SourceNamedTypeSymbol;
            if (sourceType != null)
            {
                field = sourceType.EnumValueField;
                Assert.NotNull(field);
                Assert.Equal(field.Name, WellKnownMemberNames.EnumBackingFieldName);
                Assert.False(field.IsStatic);
                Assert.False(field.IsConst);
                Assert.False(field.IsReadOnly);
                Assert.Equal(field.DeclaredAccessibility, Accessibility.Public); // Dev10: value__ is public
                Assert.Equal(field.Type, type.EnumUnderlyingType);

                var module = new PEAssemblyBuilder((SourceAssemblySymbol)sourceType.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                    GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

                var context = new EmitContext(module, null, new DiagnosticBag());

                var typeDefinition = (Microsoft.Cci.ITypeDefinition)type;
                var fieldDefinition = typeDefinition.GetFields(context).First();
                Assert.Same(fieldDefinition, field); // Dev10: value__ field is the first field.
                Assert.True(fieldDefinition.IsSpecialName);
                Assert.True(fieldDefinition.IsRuntimeSpecial);
                context.Diagnostics.Verify();
            }
        }
开发者ID:rgani,项目名称:roslyn,代码行数:37,代码来源:EmitMetadata.cs


示例14: AssemblyRefs_DuplicateRows

        public void AssemblyRefs_DuplicateRows()
        {
            var compilation = CreateCompilationWithMscorlib(
                "class C : C1 { }; class D { }",
                new[] { TestReferences.SymbolsTests.Methods.CSMethods });

            PEAssemblyBuilder assembly = new PEAssemblyBuilder(
                (SourceAssemblySymbol)compilation.Assembly,
                EmitOptions.Default,
                compilation.Options.OutputKind,
                GetDefaultModulePropertiesForSerialization(),
                Enumerable.Empty<ResourceDescription>(),
                // map all references to a single name:
                assembylSymbol => new AssemblyIdentity("foo")
            );

            // Don't attempt to emit if there were any syntax, declaration, semantic, or emitted errors previously.
            DiagnosticBag diagnostics = new DiagnosticBag();

            MethodCompiler.CompileMethodBodies(
                compilation: compilation,
                moduleBeingBuiltOpt: assembly,
                generateDebugInfo: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: default(CancellationToken));

            diagnostics.Verify();
            var context = new EmitContext(assembly, null, new DiagnosticBag());
            ImmutableArray<byte> image;
            using (var stream = new MemoryStream())
            {
                Cci.PeWriter.WritePeToStream(
                    context,
                    compilation.MessageProvider,
                    stream,
                    nativePdbWriterOpt: null,
                    allowMissingMethodBodies: false,
                    deterministic: false,
                    cancellationToken: CancellationToken.None);

                image = stream.ToImmutable();
            }
            context.Diagnostics.Verify();

            // check that there are no duplicate rows in AssemblyRef table:
            PEAssembly emittedAssembly = AssemblyMetadata.CreateFromImage(image).GetAssembly();
            var emittedReferences = emittedAssembly.Modules[0].ReferencedAssemblies;
            Assert.Equal(1, emittedReferences.Length);
            Assert.Equal("foo", emittedReferences[0].Name);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:52,代码来源:EmitMetadata.cs


示例15: BaseInterfacesInMetadata

        public void BaseInterfacesInMetadata()
        {
            var text = @"
interface I1 { }
interface I2 : I1 { }
class C : I2 { }
";
            var comp = CreateCompilationWithMscorlib(text);
            var global = comp.GlobalNamespace;

            var baseInterface = global.GetMember<NamedTypeSymbol>("I1");
            var derivedInterface = global.GetMember<NamedTypeSymbol>("I2");
            var @class = global.GetMember<NamedTypeSymbol>("C");

            var bothInterfaces = ImmutableArray.Create<NamedTypeSymbol>(baseInterface, derivedInterface);

            Assert.Equal(baseInterface, derivedInterface.AllInterfaces.Single());
            Assert.Equal(derivedInterface, @class.Interfaces.Single());
            Assert.True(@class.AllInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var cciInterfaces = typeDef.Interfaces(context).Cast<NamedTypeSymbol>().AsImmutable();
            Assert.True(cciInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
            context.Diagnostics.Verify();
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:BaseClassTests.cs


示例16: CreateModuleBuilder

        internal CommonPEModuleBuilder CreateModuleBuilder(
            string outputName,
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            CancellationToken cancellationToken,
            CompilationTestData testData,
            DiagnosticBag diagnostics,
            bool metadataOnly,
            ImmutableArray<NamedTypeSymbol> additionalTypes)
        {
            // Do not waste a slot in the submission chain for submissions that contain no executable code
            // (they may only contain #r directives, usings, etc.)
            if (IsSubmission && !HasCodeToEmit())
            {
                return null;
            }

            string runtimeMDVersion = GetRuntimeMetadataVersion(diagnostics);
            if (runtimeMDVersion == null)
            {
                return null;
            }

            var moduleProps = ConstructModuleSerializationProperties(runtimeMDVersion);

            if (manifestResources == null)
            {
                manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
            }

            PEModuleBuilder moduleBeingBuilt;
            if (options.OutputKind.IsNetModule())
            {
                Debug.Assert(additionalTypes.IsEmpty);

                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
                    outputName,
                    moduleProps,
                    manifestResources,
                    metadataOnly);
            }
            else
            {
                var kind = options.OutputKind.IsValid() ? options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
                    outputName,
                    kind,
                    moduleProps,
                    manifestResources,
                    assemblySymbolMapper,
                    additionalTypes,
                    metadataOnly);
            }

            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:65,代码来源:CSharpCompilation.cs


示例17: CreateModuleBuilder

        internal CommonPEModuleBuilder CreateModuleBuilder(
            string outputName,
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            ImmutableArray<NamedTypeSymbol> additionalTypes,
            CancellationToken cancellationToken,
            CompilationTestData testData,
            DiagnosticBag diagnostics,
            ref bool hasDeclarationErrors,
            bool metadataOnly)
        {
            // The diagnostics should include syntax and declaration errors also. We insert these before calling Emitter.Emit, so that the emitter
            // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...)
            if (!FilterAndAppendDiagnostics(
                diagnostics,
                GetDiagnostics(CompilationStage.Declare, true, cancellationToken),
                this.options))
            {
                hasDeclarationErrors = true;
            }

            // Do not waste a slot in the submission chain for submissions that contain no executable code
            // (they may only contain #r directives, usings, etc.)
            if (IsSubmission && !HasCodeToEmit())
            {
                return null;
            }

            string runtimeMDVersion = GetRuntimeMetadataVersion(diagnostics);
            if (runtimeMDVersion == null)
            {
                return null;
            }

            var moduleProps = ConstructModuleSerializationProperties(runtimeMDVersion);

            if (manifestResources == null)
            {
                manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
            }

            PEModuleBuilder moduleBeingBuilt;
            if (options.OutputKind.IsNetModule())
            {
                Debug.Assert(additionalTypes.IsEmpty);

                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
                    outputName,
                    moduleProps,
                    manifestResources,
                    metadataOnly);
            }
            else
            {
                var kind = options.OutputKind.IsValid() ? options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
                    outputName,
                    kind,
                    moduleProps,
                    manifestResources,
                    assemblySymbolMapper,
                    additionalTypes,
                    metadataOnly);
            }

            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }
开发者ID:pheede,项目名称:roslyn,代码行数:76,代码来源:CSharpCompilation.cs



注:本文中的Microsoft.CodeAnalysis.CSharp.Emit.PEAssemblyBuilder类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ExpressionEvaluator.EENamedTypeSymbol类代码示例发布时间:2022-05-26
下一篇:
C# CSharp.TypeCompilationState类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap