コード例 #1
0
        public PartialTypeDocumentationCommentTests()
        {
            var tree1 = Parse(
                @"
/// <summary>Summary on first file's Foo.</summary>
partial class Foo
{
    /// <summary>Summary on MethodWithNoImplementation.</summary>
    partial void MethodWithNoImplementation();

    /// <summary>Summary in file one which should be shadowed.</summary>
    partial void ImplementedMethodWithNoSummaryOnImpl();

    partial void ImplementedMethod();
}", options: TestOptions.RegularWithDocumentationComments);

            var tree2 = Parse(
                @"
/// <summary>Summary on second file's Foo.</summary>
partial class Foo
{
    /// <remarks>Foo.</remarks>
    partial void ImplementedMethodWithNoSummaryOnImpl() { }

    /// <summary>Implemented method.</summary>
    partial void ImplementedMethod() { }
}", options: TestOptions.RegularWithDocumentationComments);

            _compilation = CreateCompilationWithMscorlib(new[] { tree1, tree2 });

            _fooClass = _compilation.GlobalNamespace.GetTypeMembers("Foo").Single();
        }
コード例 #2
0
        internal static BoundNode Rewrite(CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, BoundNode node)
        {
            var builder = ArrayBuilder<BoundStatement>.GetInstance();
            bool hasChanged;

            // Rewrite top-level declarations only.
            switch (node.Kind)
            {
                case BoundKind.LocalDeclaration:
                    RewriteLocalDeclaration(compilation, container, declaredLocals, builder, (BoundLocalDeclaration)node);
                    hasChanged = true;
                    break;
                case BoundKind.MultipleLocalDeclarations:
                    foreach (var declaration in ((BoundMultipleLocalDeclarations)node).LocalDeclarations)
                    {
                        RewriteLocalDeclaration(compilation, container, declaredLocals, builder, declaration);
                    }
                    hasChanged = true;
                    break;
                default:
                    hasChanged = false;
                    break;
            }

            if (hasChanged)
            {
                node = new BoundBlock(node.Syntax, ImmutableArray<LocalSymbol>.Empty, builder.ToImmutable()) { WasCompilerGenerated = true };
            }

            builder.Free();
            return node;
        }
コード例 #3
0
        public TypeDocumentationCommentTests()
        {
            _compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"enum Color { Red, Blue, Green }
namespace Acme
{
	interface IProcess {...}
	struct ValueType {...}
	class Widget: IProcess
	{
        /// <summary>
        /// Hello! Nested Class.
        /// </summary>
		public class NestedClass {...}
		public interface IMenuItem {...}
		public delegate void Del(int i);
		public enum Direction { North, South, East, West }
	}
	class MyList<T>
	{
		class Helper<U,V> {...}
	}
}");

            _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single();
            _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single();
        }
コード例 #4
0
 internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax)
 {
     var method = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetObjectAtAddressMethodName,
         (c, n, s) =>
         {
             var parameterType = compilation.GetSpecialType(SpecialType.System_UInt64);
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 this.Type,
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)));
         });
     var argument = new BoundLiteral(
         syntax,
         Microsoft.CodeAnalysis.ConstantValue.Create(_address),
         method.Parameters[0].Type);
     var call = BoundCall.Synthesized(
         syntax,
         receiverOpt: null,
         method: method,
         arguments: ImmutableArray.Create<BoundExpression>(argument));
     Debug.Assert(call.Type == this.Type);
     return call;
 }
コード例 #5
0
 private PlaceholderLocalRewriter(CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, DiagnosticBag diagnostics)
 {
     _compilation = compilation;
     _container = container;
     _declaredLocals = declaredLocals;
     _diagnostics = diagnostics;
 }
コード例 #6
0
        private static void CheckCompilationSyntaxTrees(CSharpCompilation compilation, params SyntaxTree[] expectedSyntaxTrees)
        {
            ImmutableArray<SyntaxTree> actualSyntaxTrees = compilation.SyntaxTrees;

            int numTrees = expectedSyntaxTrees.Length;

            Assert.Equal(numTrees, actualSyntaxTrees.Length);
            for (int i = 0; i < numTrees; i++)
            {
                Assert.Equal(expectedSyntaxTrees[i], actualSyntaxTrees[i]);
            }

            for (int i = 0; i < numTrees; i++)
            {
                for (int j = 0; j < numTrees; j++)
                {
                    Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees[i], expectedSyntaxTrees[j])), Math.Sign(i.CompareTo(j)));
                }
            }

            var types = expectedSyntaxTrees.Select(tree => compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray();
            for (int i = 0; i < numTrees; i++)
            {
                for (int j = 0; j < numTrees; j++)
                {
                    Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types[i].Locations[0], types[j].Locations[0])), Math.Sign(i.CompareTo(j)));
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Determine the effective base type, effective interface set, and set of type
        /// parameters (excluding cycles) from the type parameter constraints. Conflicts
        /// within the constraints and constraint types are returned as diagnostics.
        /// 'inherited' should be true if the type parameters are from an overridden
        /// generic method. In those cases, additional constraint checks are applied.
        /// </summary>
        public static TypeParameterBounds ResolveBounds(
            this TypeParameterSymbol typeParameter,
            AssemblySymbol corLibrary,
            ConsList<TypeParameterSymbol> inProgress,
            ImmutableArray<TypeSymbol> constraintTypes,
            bool inherited,
            CSharpCompilation currentCompilation,
            DiagnosticBag diagnostics)
        {
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);

            if (useSiteDiagnosticsBuilder != null)
            {
                diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder);
            }

            foreach (var pair in diagnosticsBuilder)
            {
                diagnostics.Add(new CSDiagnostic(pair.DiagnosticInfo, pair.TypeParameter.Locations[0]));
            }

            diagnosticsBuilder.Free();
            return bounds;
        }
コード例 #8
0
 private static BoundExpression RewriteLocalInternal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax, LocalSymbol local)
 {
     var parameterType = compilation.GetSpecialType(SpecialType.System_String);
     var getValueMethod = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetVariableValueMethodName,
         (c, n, s) =>
         {
             var returnType = compilation.GetSpecialType(SpecialType.System_Object);
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 returnType,
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)));
         });
     var getAddressMethod = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetVariableAddressMethodName,
         (c, n, s) =>
         {
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 m => ImmutableArray.Create<TypeParameterSymbol>(new SimpleTypeParameterSymbol(m, 0, "<>T")),
                 m => m.TypeParameters[0], // return type is <>T&
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)),
                 returnValueIsByRef: true);
         });
     return new BoundPseudoVariable(
         syntax,
         local,
         new ObjectIdExpressions(compilation, getValueMethod, getAddressMethod),
         local.Type);
 }
コード例 #9
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();
        }
コード例 #10
0
ファイル: CompilationContext.cs プロジェクト: rgani/roslyn
        /// <summary>
        /// Create a context to compile expressions within a method scope.
        /// </summary>
        internal CompilationContext(
            CSharpCompilation compilation,
            MethodSymbol currentFrame,
            ImmutableArray<LocalSymbol> locals,
            InScopeHoistedLocals inScopeHoistedLocals,
            MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo,
            CSharpSyntaxNode syntax)
        {
            Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));

            // TODO: syntax.SyntaxTree should probably be added to the compilation,
            // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
            _currentFrame = currentFrame;
            _syntax = syntax;
            _methodNotType = !locals.IsDefault;

            // NOTE: Since this is done within CompilationContext, it will not be cached.
            // CONSIDER: The values should be the same everywhere in the module, so they
            // could be cached.  
            // (Catch: what happens in a type context without a method def?)
            this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);

            // Each expression compile should use a unique compilation
            // to ensure expression-specific synthesized members can be
            // added (anonymous types, for instance).
            Debug.Assert(this.Compilation != compilation);

            this.NamespaceBinder = CreateBinderChain(
                this.Compilation,
                (PEModuleSymbol)currentFrame.ContainingModule,
                currentFrame.ContainingNamespace,
                methodDebugInfo.ImportRecordGroups);

            if (_methodNotType)
            {
                _locals = locals;
                ImmutableArray<string> displayClassVariableNamesInOrder;
                GetDisplayClassVariables(
                    currentFrame,
                    _locals,
                    inScopeHoistedLocals,
                    out displayClassVariableNamesInOrder,
                    out _displayClassVariables,
                    out _hoistedParameterNames);
                Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
                _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
            }
            else
            {
                _locals = ImmutableArray<LocalSymbol>.Empty;
                _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
                _localsForBinding = ImmutableArray<LocalSymbol>.Empty;
            }

            // Assert that the cheap check for "this" is equivalent to the expensive check for "this".
            Debug.Assert(
                _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
                _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
        }
コード例 #11
0
 private static BoundExpression RewriteLocalInternal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax, LocalSymbol local)
 {
     return new BoundPseudoVariable(
         syntax,
         local,
         new ObjectIdExpressions(compilation),
         local.Type);
 }
コード例 #12
0
 private AwaitExpressionInfo GetAwaitExpressionInfo(string text, out CSharpCompilation compilation, params DiagnosticDescription[] diagnostics)
 {
     var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
     var comp = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }, new MetadataReference[] { SystemRef });
     comp.VerifyDiagnostics(diagnostics);
     compilation = comp;
     var syntaxNode = (AwaitExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression).AsNode();
     var treeModel = comp.GetSemanticModel(tree);
     return treeModel.GetAwaitExpressionInfo(syntaxNode);
 }
コード例 #13
0
ファイル: TypedConstantTests.cs プロジェクト: EkardNT/Roslyn
 public TypedConstantTests()
 {
     compilation = CreateCompilationWithMscorlib("class C {}");
     namedType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
     systemType = compilation.GetWellKnownType(WellKnownType.System_Type);
     arrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object));
     intType = compilation.GetSpecialType(SpecialType.System_Int32);
     stringType = compilation.GetSpecialType(SpecialType.System_String);
     enumString1 = compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).Construct(compilation.GetSpecialType(SpecialType.System_String));
     enumString2 = compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).Construct(compilation.GetSpecialType(SpecialType.System_String));
 }
コード例 #14
0
        private static void RewriteLocalDeclaration(
            CSharpCompilation compilation,
            EENamedTypeSymbol container,
            HashSet<LocalSymbol> declaredLocals,
            ArrayBuilder<BoundStatement> statements,
            BoundLocalDeclaration node)
        {
            Debug.Assert(node.ArgumentsOpt.IsDefault);

            var local = node.LocalSymbol;
            var syntax = node.Syntax;

            declaredLocals.Add(local);

            var voidType = compilation.GetSpecialType(SpecialType.System_Void);
            var objectType = compilation.GetSpecialType(SpecialType.System_Object);
            var typeType = compilation.GetWellKnownType(WellKnownType.System_Type);
            var stringType = compilation.GetSpecialType(SpecialType.System_String);

            // <>CreateVariable(Type type, string name)
            var method = container.GetOrAddSynthesizedMethod(
                ExpressionCompilerConstants.CreateVariableMethodName,
                (c, n, s) => new PlaceholderMethodSymbol(
                    c,
                    s,
                    n,
                    voidType,
                    m => ImmutableArray.Create<ParameterSymbol>(
                        new SynthesizedParameterSymbol(m, typeType, ordinal: 0, refKind: RefKind.None),
                        new SynthesizedParameterSymbol(m, stringType, ordinal: 1, refKind: RefKind.None))));
            var type = new BoundTypeOfOperator(syntax, new BoundTypeExpression(syntax, aliasOpt: null, type: local.Type), null, typeType);
            var name = new BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType);
            var call = BoundCall.Synthesized(
                syntax,
                receiverOpt: null,
                method: method,
                arguments: ImmutableArray.Create<BoundExpression>(type, name));
            statements.Add(new BoundExpressionStatement(syntax, call));

            var initializer = node.InitializerOpt;
            if (initializer != null)
            {
                // Generate assignment to local. The assignment will
                // be rewritten in PlaceholderLocalRewriter.
                var assignment = new BoundAssignmentOperator(
                    syntax,
                    new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type),
                    initializer,
                    RefKind.None,
                    local.Type);
                statements.Add(new BoundExpressionStatement(syntax, assignment));
            }
        }
コード例 #15
0
 internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax, DiagnosticBag diagnostics)
 {
     var method = GetIntrinsicMethod(compilation, ExpressionCompilerConstants.GetReturnValueMethodName);
     var argument = new BoundLiteral(
         syntax,
         Microsoft.CodeAnalysis.ConstantValue.Create(_index),
         method.Parameters[0].Type);
     var call = BoundCall.Synthesized(
         syntax,
         receiverOpt: null,
         method: method,
         arguments: ImmutableArray.Create<BoundExpression>(argument));
     return ConvertToLocalType(compilation, call, this.Type, diagnostics);
 }
        public EventDocumentationCommentTests()
        {
            compilation = CreateCompilationWithMscorlib(@"namespace Acme
{
    class Widget: IProcess
    {
        public event System.Action E;
        public event System.Action F { add { } remove { } }
    }
}
");

            acmeNamespace = (NamespaceSymbol)compilation.GlobalNamespace.GetMember<NamespaceSymbol>("Acme");
            widgetClass = acmeNamespace.GetMember<NamedTypeSymbol>("Widget");
        }
コード例 #17
0
        public DestructorDocumentationCommentTests()
        {
            _compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"namespace Acme
{
	class Widget: IProcess
	{
        /// <summary>Destructor Documentation</summary>
        ~Widget() {...}
	}
}
");

            _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single();
            _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single();
        }
コード例 #18
0
 internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics)
 {
     var method = GetIntrinsicMethod(compilation, ExpressionCompilerConstants.GetObjectAtAddressMethodName);
     var argument = new BoundLiteral(
         syntax,
         Microsoft.CodeAnalysis.ConstantValue.Create(_address),
         method.Parameters[0].Type);
     var call = BoundCall.Synthesized(
         syntax,
         receiverOpt: null,
         method: method,
         arguments: ImmutableArray.Create<BoundExpression>(argument));
     Debug.Assert(call.Type == this.Type);
     return call;
 }
        public PropertyDocumentationCommentTests()
        {
            compilation = CreateCompilationWithMscorlib(@"namespace Acme
{
    class Widget: IProcess
    {
        public int Width { get { } set { } }
        public int this[int i] { get { } set { } }
        public int this[string s, int i] { get { } set { } }
    }
}
");

            acmeNamespace = (NamespaceSymbol)compilation.GlobalNamespace.GetMembers("Acme").Single();
            widgetClass = acmeNamespace.GetTypeMembers("Widget").Single();
        }
コード例 #20
0
ファイル: LambdaSymbol.cs プロジェクト: afrog33k/csnative
 public LambdaSymbol(
     CSharpCompilation compilation,
     Symbol containingSymbol,
     UnboundLambda unboundLambda,
     ImmutableArray<ParameterSymbol> delegateParameters,
     TypeSymbol returnType)
 {
     this.containingSymbol = containingSymbol;
     this.messageID = unboundLambda.Data.MessageID;
     this.syntax = unboundLambda.Syntax;
     this.returnType = returnType;
     this.isSynthesized = unboundLambda.WasCompilerGenerated;
     this.isAsync = unboundLambda.IsAsync;
     // No point in making this lazy. We are always going to need these soon after creation of the symbol.
     this.parameters = MakeParameters(compilation, unboundLambda, delegateParameters);
 }
コード例 #21
0
        private static void RewriteLocalDeclaration(
            CSharpCompilation compilation,
            EENamedTypeSymbol container,
            HashSet<LocalSymbol> declaredLocals,
            ArrayBuilder<BoundStatement> statements,
            BoundLocalDeclaration node)
        {
            Debug.Assert(node.ArgumentsOpt.IsDefault);

            var local = node.LocalSymbol;
            var syntax = node.Syntax;

            declaredLocals.Add(local);

            var typeType = compilation.GetWellKnownType(WellKnownType.System_Type);
            var stringType = compilation.GetSpecialType(SpecialType.System_String);
            var guidConstructor = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Guid__ctor);

            // CreateVariable(Type type, string name)
            var method = PlaceholderLocalSymbol.GetIntrinsicMethod(compilation, ExpressionCompilerConstants.CreateVariableMethodName);
            var type = new BoundTypeOfOperator(syntax, new BoundTypeExpression(syntax, aliasOpt: null, type: local.Type), null, typeType);
            var name = new BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType);

            bool hasCustomTypeInfoPayload;
            var customTypeInfoPayload = GetCustomTypeInfoPayload(local, syntax, compilation, out hasCustomTypeInfoPayload);
            var customTypeInfoPayloadId = GetCustomTypeInfoPayloadId(syntax, guidConstructor, hasCustomTypeInfoPayload);
            var call = BoundCall.Synthesized(
                syntax,
                receiverOpt: null,
                method: method,
                arguments: ImmutableArray.Create(type, name, customTypeInfoPayloadId, customTypeInfoPayload));
            statements.Add(new BoundExpressionStatement(syntax, call));

            var initializer = node.InitializerOpt;
            if (initializer != null)
            {
                // Generate assignment to local. The assignment will
                // be rewritten in PlaceholderLocalRewriter.
                var assignment = new BoundAssignmentOperator(
                    syntax,
                    new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type),
                    initializer,
                    RefKind.None,
                    local.Type);
                statements.Add(new BoundExpressionStatement(syntax, assignment));
            }
        }
コード例 #22
0
        public MethodDocumentationCommentTests()
        {
            _compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"namespace Acme
{
    struct ValueType
    {
        public void M(int i) { }

        public static explicit operator ValueType (byte value)
        {
            return default(ValueType);
        }
    }
    class Widget: IProcess
    {
        public class NestedClass
        {
            public void M(int i) { }
        }

        /// <summary>M0 Summary.</summary>
        public static void M0() { }
        public void M1(char c, out float f, ref ValueType v) { }
        public void M2(short[] x1, int[,] x2, long[][] x3) { }
        public void M3(long[][] x3, Widget[][,,] x4) { }
        public unsafe void M4(char *pc, Color **pf) { }
        public unsafe void M5(void *pv, double *[][,] pd) { }
        public void M6(int i, params object[] args) { }
    }
    class MyList<T>
    {
        public void Test(T t) { }
        public void Zip(MyList<T> other) { }
        public void ReallyZip(MyList<MyList<T>> other) { }
    }
    class UseList
    {
        public void Process(MyList<int> list) { }
        public MyList<T> GetValues<T>(T inputValue) { return null; }
    }
}
");

            _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single();
            _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single();
        }
コード例 #23
0
        private void CompareConstructedErrorTypes(CSharpCompilation compilation, bool missingTypes, bool fromSource)
        {
            // Get all root types.
            var allTypes = compilation.GlobalNamespace.GetTypeMembers();

            // Get base class for each type named "C?".
            var types = new[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7" }.Select(name => allTypes.First(t => t.Name == name).BaseType).ToArray();
            foreach (var type in types)
            {
                var constructedFrom = type.ConstructedFrom;
                Assert.NotEqual(type, constructedFrom);
                if (missingTypes)
                {
                    Assert.True(type.IsErrorType());
                    Assert.True(constructedFrom.IsErrorType());
                    var extendedError = constructedFrom as ExtendedErrorTypeSymbol;
                    if (fromSource)
                    {
                        Assert.NotNull(extendedError);
                    }
                    else
                    {
                        Assert.Null(extendedError);
                    }
                }
                else
                {
                    Assert.False(type.IsErrorType());
                    Assert.False(constructedFrom.IsErrorType());
                }
            }

            // Compare pairs of types. The only error types that
            // should compare equal are C6 and C7.
            const int n = 7;
            for (int i = 0; i < n - 1; i++)
            {
                var typeA = types[i];
                for (int j = i + 1; j < n; j++)
                {
                    var typeB = types[j];
                    bool expectedEqual = (i == 5) && (j == 6);
                    Assert.Equal(typeA == typeB, expectedEqual);
                }
            }
        }
コード例 #24
0
ファイル: EvaluationContext.cs プロジェクト: tvsonar/roslyn
        private EvaluationContext(
            MethodContextReuseConstraints? methodContextReuseConstraints,
            CSharpCompilation compilation,
            MethodSymbol currentFrame,
            ImmutableArray<LocalSymbol> locals,
            InScopeHoistedLocals inScopeHoistedLocals,
            MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo)
        {
            Debug.Assert(inScopeHoistedLocals != null);
            Debug.Assert(methodDebugInfo != null);

            this.MethodContextReuseConstraints = methodContextReuseConstraints;
            this.Compilation = compilation;
            _currentFrame = currentFrame;
            _locals = locals;
            _inScopeHoistedLocals = inScopeHoistedLocals;
            _methodDebugInfo = methodDebugInfo;
        }
コード例 #25
0
ファイル: EvaluationContext.cs プロジェクト: tvsonar/roslyn
        internal static EvaluationContext CreateTypeContext(
            CSharpCompilation compilation,
            Guid moduleVersionId,
            int typeToken)
        {
            Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition);

            var currentType = compilation.GetType(moduleVersionId, typeToken);
            Debug.Assert((object)currentType != null);
            var currentFrame = new SynthesizedContextMethodSymbol(currentType);
            return new EvaluationContext(
                null,
                compilation,
                currentFrame,
                default(ImmutableArray<LocalSymbol>),
                InScopeHoistedLocals.Empty,
                MethodDebugInfo<TypeSymbol, LocalSymbol>.None);
        }
コード例 #26
0
 internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax)
 {
     Debug.Assert(this.Name == this.Name.ToLowerInvariant());
     var method = container.GetOrAddSynthesizedMethod(
         this.Name,
         (c, n, s) =>
         {
             var returnType = compilation.GetWellKnownType(WellKnownType.System_Exception);
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 returnType,
                 m => ImmutableArray<ParameterSymbol>.Empty);
         });
     var call = BoundCall.Synthesized(syntax, receiverOpt: null, method: method);
     return ConvertToLocalType(compilation, call, this.Type);
 }
コード例 #27
0
        private static void ClassDependsClosure(TypeSymbol type, CSharpCompilation currentCompilation, HashSet<Symbol> partialClosure)
        {
            if ((object)type == null)
            {
                return;
            }

            var namedType = type.OriginalDefinition as NamedTypeSymbol;
            if ((object)namedType != null && partialClosure.Add(namedType))
            {
                ClassDependsClosure(namedType.GetDeclaredBaseType(null), currentCompilation, partialClosure);

                // containment is interesting only for the current compilation
                if (currentCompilation != null && namedType.IsFromCompilation(currentCompilation))
                {
                    ClassDependsClosure(namedType.ContainingType, currentCompilation, partialClosure);
                }
            }
        }
コード例 #28
0
        public FieldDocumentationCommentTests()
        {
            _compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"
namespace Acme
{
	struct ValueType
	{
        /// <summary>Summary for total fields.</summary>
		private int total1, total2;
	}
	class Widget: IProcess
	{
		public class NestedClass
		{
			private int value;
		}
		private string message;
		private static Color defaultColor;
		private const double PI = 3.14159;
		protected readonly double monthlyAverage;
		private long[] array1;
		private Widget[,] array2;
		private unsafe int *pCount;
		private unsafe float **ppValues;
	}

    enum E
    {
        /// <summary>Enum field</summary>
        A = 1
    }
}
");

            _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single();
            _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single();
            _enumSymbol = _acmeNamespace.GetTypeMembers("E").Single();
            _valueType = _acmeNamespace.GetTypeMembers("ValueType").Single();
        }
コード例 #29
0
        public ConstructorDocumentationCommentTests()
        {
            compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"namespace Acme
{
	class Widget: IProcess
	{
        /// <summary>Static Constructor</summary>
        static Widget() {...}
        /** <summary>Instance Constructor</summary> */
        public Widget() {...}
        /// <summary>
        /// Parameterized Constructor
        /// </summary>
        /// <param name=""s"">s, the string argument</param>
        public Widget(string s) {...}
	}
}
");

            acmeNamespace = (NamespaceSymbol)compilation.GlobalNamespace.GetMembers("Acme").Single();
            widgetClass = acmeNamespace.GetTypeMembers("Widget").Single();
        }
コード例 #30
0
        internal static BoundStatement Rewrite(CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, BoundStatement node, ImmutableArray<LocalSymbol> declaredLocalsArray)
        {
            var builder = ArrayBuilder<BoundStatement>.GetInstance();

            foreach (var local in declaredLocalsArray)
            {
                CreateLocal(compilation, declaredLocals, builder, local, node.Syntax);
            }

            // Rewrite top-level declarations only.
            switch (node.Kind)
            {
                case BoundKind.LocalDeclaration:
                    Debug.Assert(declaredLocals.Contains(((BoundLocalDeclaration)node).LocalSymbol));
                    RewriteLocalDeclaration(builder, (BoundLocalDeclaration)node);
                    break;

                case BoundKind.MultipleLocalDeclarations:
                    foreach (var declaration in ((BoundMultipleLocalDeclarations)node).LocalDeclarations)
                    {
                        Debug.Assert(declaredLocals.Contains(declaration.LocalSymbol));
                        RewriteLocalDeclaration(builder, declaration);
                    }

                    break;

                default:
                    if (builder.Count == 0)
                    {
                        builder.Free();
                        return node;
                    }

                    builder.Add(node);
                    break; 
            }

            return BoundBlock.SynthesizedNoLocals(node.Syntax, builder.ToImmutableAndFree());
        }
コード例 #31
0
        /// <summary>
        /// 使用内存流进行脚本编译
        /// </summary>
        /// <param name="content">脚本内容</param>
        /// <param name="className">指定类名</param>
        /// <param name="errorAction">发生错误执行委托</param>
        /// <returns></returns>
        public static Assembly StreamComplier(string content, string className = null, Action <string> errorAction = null)
        {
#if DEBUG
            StringBuilder recoder = new StringBuilder(content);
#endif

            //写入分析树
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(content);


            //创建语言编译
            CSharpCompilation compilation = CSharpCompilation.Create(
                className,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: References);


            //锁住内容
            lock (content)
            {
                //编译并生成程序集
                using (MemoryStream stream = new MemoryStream())
                {
                    var fileResult = compilation.Emit(stream);
                    if (fileResult.Success)
                    {
                        var result = Assembly.Load(stream.GetBuffer());
#if DEBUG
                        recoder.AppendLine("\r\n\r\n------------------------------------------succeed-------------------------------------------");
                        recoder.AppendLine($"\r\n    Target :\t\t{className}");
                        recoder.AppendLine($"\r\n    Size :\t\t{stream.Length}");
                        recoder.AppendLine($"\r\n    Assembly : \t{result.FullName}");
                        recoder.AppendLine("\r\n----------------------------------------------------------------------------------------------");
                        NDebug.Show($"Builder Assembly Succeed : {result.FullName}");
                        NDebug.FileRecoder("Succeed : " + className, recoder.ToString());
#endif

                        return(result);
                    }
                    else
                    {
#if DEBUG
                        recoder.AppendLine("\r\n\r\n------------------------------------------error----------------------------------------------");
                        recoder.AppendLine($"\r\n    Target:\t\t{className}");
                        recoder.AppendLine($"\r\n    Error:");
#endif

                        //错误处理
                        foreach (var item in fileResult.Diagnostics)
                        {
#if DEBUG
                            recoder.AppendLine("\t\t" + item.GetMessage());
#endif
                            errorAction?.Invoke(item.GetMessage());
                        }
#if DEBUG
                        recoder.AppendLine("\r\n---------------------------------------------------------------------------------------------");
#endif
                        NDebug.FileRecoder("Error : " + className, recoder.ToString());
                    }
                }
            }
            return(null);
        }
コード例 #32
0
        public List <IndicatorValue> CalculateIndicatorValues(string Formula, int IndicatorId)
        {
            List <IndicatorValue> indicatorValues = new List <IndicatorValue>();
            string        formula_test            = Formula;
            List <Region> regions = _context.Region.ToList();

            foreach (var region in regions)
            {
                IndicatorValue indicatorValue = _context.IndicatorValue.AsNoTracking().FirstOrDefault(iv => iv.RegionId == region.Id && iv.IndicatorId == IndicatorId);
                if (indicatorValue == null)
                {
                    indicatorValue = new IndicatorValue()
                    {
                        Id          = 0,
                        IndicatorId = IndicatorId
                    };
                }
                indicatorValue.RegionId = region.Id;
                indicatorValue.Region   = region;
                indicatorValue.Year     = region.Year;
                indicatorValues.Add(indicatorValue);
            }
            // => calculate values
            string code = $"decimal?[] r = new decimal?[{indicatorValues.Count().ToString()}];";

            for (int i = 0; i < indicatorValues.Count(); i++)
            {
                code += @"
                        ";
                string formula_code = formula_test;
                while (formula_code.IndexOf("Area") >= 0)
                {
                    formula_code = formula_code.Replace("Area", indicatorValues[i].Region.Area.ToString());
                }
                while (formula_code.IndexOf("Population") >= 0)
                {
                    formula_code = formula_code.Replace("Population", indicatorValues[i].Region.Area.ToString());
                }
                while (formula_code.IndexOf("$") >= 0)
                {
                    DollarRate dollarRate      = _context.DollarRate.AsNoTracking().FirstOrDefault(d => d.Year == indicatorValues[i].Region.Year);
                    decimal?   dollarRateValue = dollarRate == null ? null : dollarRate.Value;
                    formula_code = formula_code.Replace("$", dollarRateValue == null ? "null" : dollarRateValue.ToString());
                }
                while (formula_code.IndexOf("Min") >= 0)
                {
                    int M = formula_code.IndexOf("Min"),
                        I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    ReferencePoint referencePoint = _context.ReferencePoint
                                                    .FirstOrDefault(r => r.IndicatorId == indicatorId);
                    decimal referencePointValue = referencePoint != null ? referencePoint.Min : 0;
                    formula_code = formula_code.Remove(M, d - M + 1 + 1);
                    formula_code = formula_code.Insert(M, referencePointValue.ToString());
                }
                while (formula_code.IndexOf("Max") >= 0)
                {
                    int M = formula_code.IndexOf("Max"),
                        I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    ReferencePoint referencePoint = _context.ReferencePoint
                                                    .FirstOrDefault(r => r.IndicatorId == indicatorId);
                    decimal referencePointValue = referencePoint != null ? referencePoint.Max : 0;
                    formula_code = formula_code.Remove(M, d - M + 1 + 1);
                    formula_code = formula_code.Insert(M, referencePointValue.ToString());
                }
                while (formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]) >= 0)
                {
                    int I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"]);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    IndicatorValue indicatorValue = _context.IndicatorValue
                                                    .AsNoTracking()
                                                    .FirstOrDefault(iv => iv.IndicatorId == indicatorId && iv.RegionId == indicatorValues[i].RegionId && iv.Year == indicatorValues[i].Year);
                    decimal?indicatorValueValue       = indicatorValue != null ? indicatorValue.Value : null;
                    string  indicatorValueValueString = indicatorValueValue != null?indicatorValueValue.ToString() : "null";

                    formula_code = formula_code.Remove(I, d - I + 1);
                    formula_code = formula_code.Insert(I, indicatorValueValueString);
                }
                formula_code = formula_code.Replace(',', '.');
                for (int j = formula_code.Length - 1; j >= 0; j--)
                {
                    bool insert = false;
                    if (Char.IsDigit(formula_code[j]))
                    {
                        insert = true;
                    }
                    if (j != formula_code.Length - 1)
                    {
                        if (formula_code[j + 1] == '.' || Char.IsDigit(formula_code[j + 1]))
                        {
                            insert = false;
                        }
                    }
                    if (insert)
                    {
                        formula_code = formula_code.Insert(j + 1, "M");
                    }
                }
                if (formula_code.Contains("null"))
                {
                    formula_code = "null";
                }
                code += $"r[{i.ToString()}] = null;" + "try{" + $"r[{i.ToString()}] = (decimal?)({formula_code});" + "} catch { }";
            }
            string     codeToCompile = @"using System;
                    namespace RoslynCompile
                    {
                        public class Calculator
                        {
                            public decimal?[] Calculate()
                            {
                                " + code + @"
                                return r;
                            }
                        }
                    }";
            SyntaxTree syntaxTree    = CSharpSyntaxTree.ParseText(codeToCompile);
            string     assemblyName  = Path.GetRandomFileName();

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location)
            };
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                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);
                    indicatorValues = new List <IndicatorValue>();
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly   assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
                    var        type     = assembly.GetType("RoslynCompile.Calculator");
                    var        instance = assembly.CreateInstance("RoslynCompile.Calculator");
                    var        meth     = type.GetMember("Calculate").First() as MethodInfo;
                    decimal?[] r        = meth.Invoke(instance, null) as decimal?[];
                    for (int i = 0; i < indicatorValues.Count(); i++)
                    {
                        indicatorValues[i].Value = r[i];
                    }
                }
            }
            // <=
            return(indicatorValues);
        }
コード例 #33
0
        protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest <TNode>(CSharpCompilation compilation) where TNode : SyntaxNode
        {
            var tree         = compilation.SyntaxTrees[0];
            var model        = compilation.GetSemanticModel(tree);
            var syntaxToBind = GetSyntaxNodeOfTypeForBinding <TNode>(GetSyntaxNodeList(tree));

            return(model.GetSemanticInfoSummary(syntaxToBind));
        }
コード例 #34
0
        private Assembly CompileBuildScript(string buildScriptAssemblyPath, string buildScriptFilePath, IEnumerable <MetadataReference> references, string code)
        {
            SyntaxTree syntaxTree =
                CSharpSyntaxTree.ParseText(SourceText.From(string.Join("\r\n", code), Encoding.UTF8));
            CSharpCompilation compilation = CSharpCompilation.Create(
                Path.GetFileName(buildScriptAssemblyPath),
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOptimizationLevel(OptimizationLevel.Debug)
                .WithAssemblyIdentityComparer(AssemblyIdentityComparer.Default));

            using (var dllStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    var        emitOptions = new EmitOptions(false, DebugInformationFormat.PortablePdb);
                    EmitResult result      = compilation.Emit(dllStream, pdbStream, options: emitOptions);

                    if (!result.Success)
                    {
                        var errorMsg = $"Csharp source code file: {buildScriptFilePath} has some compilation errors!";
                        IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                     diagnostic.IsWarningAsError ||
                                                                                     diagnostic.Severity == DiagnosticSeverity.Error);
                        bool errorMsgDefined = false;
                        foreach (Diagnostic diagnostic in failures)
                        {
                            _log.LogWarning($"ScriptError:{diagnostic.Id}: {diagnostic.GetMessage()}");
                            if (errorMsgDefined)
                            {
                                continue;
                            }

                            switch (diagnostic.Id)
                            {
                            case "CS0012":
                            {
                                errorMsg        = $"{errorMsg} If your script doesn't have compilation errors in VS or VSCode script is probably missing some assembly reference. To resolve this issue you should see build script fundamentals, section 'Referencing other assemblies in build script': https://flubucore.dotnetcore.xyz/referencing-external-assemblies/ more details.";
                                errorMsgDefined = true;
                                break;
                            }

                            case "CS0246":
                            {
                                errorMsg        = $"{errorMsg} If your script doesn't have compilation errors in VS or VSCode script is probably missing some assembly reference or script doesn't include .cs file. To resolve this issue you should see build script fundamentals, section 'Referencing other assemblies in build script' and section 'Adding other .cs files to script' for more details: {Environment.NewLine} https://flubucore.dotnetcore.xyz/referencing-external-assemblies/ {Environment.NewLine} https://flubucore.dotnetcore.xyz/referencing-external-assemblies/#adding-other-cs-files-to-script";
                                errorMsgDefined = true;
                                break;
                            }

                            case "CS0103":
                            {
                                errorMsgDefined = true;
                                errorMsg        = $"{errorMsg} If your script doesn't have compilation errors in VS or VSCode script probably doesn't include .cs file. To resolve this issue you should see build script fundamentals section 'Adding other .cs files to script' for more details: https://flubucore.dotnetcore.xyz/referencing-external-assemblies/#adding-other-cs-files-to-script";
                                break;
                            }
                            }
                        }

                        throw new ScriptLoaderExcetpion(errorMsg);
                    }

                    dllStream.Seek(0, SeekOrigin.Begin);
                    pdbStream.Seek(0, SeekOrigin.Begin);
                    Directory.CreateDirectory(Path.GetDirectoryName(buildScriptAssemblyPath));
                    var dllData = dllStream.ToArray();
                    var pdbData = pdbStream.ToArray();
                    File.WriteAllBytes(buildScriptAssemblyPath, dllData);
                    File.WriteAllBytes(Path.ChangeExtension(buildScriptAssemblyPath, "pdb"), pdbData);

#if NETSTANDARD1_6
                    dllStream.Seek(0, SeekOrigin.Begin);
                    pdbStream.Seek(0, SeekOrigin.Begin);
                    return(AssemblyLoadContext.Default.LoadFromStream(dllStream, pdbStream));
#else
                    return(Assembly.Load(dllData, pdbData));
#endif
                }
            }
        }
コード例 #35
0
 public void Setup()
 {
     m_compilation = CodeAnalysisEditorUtility.ProjectCompilation;
     m_generator   = CodeAnalysisEditorUtility.Generator;
 }
コード例 #36
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));
        }
コード例 #37
0
 public static CSharpCompilation CompileSource(string source) => CSharpCompilation.Create(
     assemblyName: Guid.NewGuid().ToString(),
     syntaxTrees: new[] { CSharpSyntaxTree.ParseText(source, ParseOptions) },
     references: CompilationReferences,
     options: CompilationOptions
     );
コード例 #38
0
ファイル: ResourceTests.cs プロジェクト: lachbaer/roslyn1612
        public void AddResourceToModule()
        {
            for (int metadataOnlyIfNonzero = 0; metadataOnlyIfNonzero < 2; metadataOnlyIfNonzero++)
            {
                var metadataOnly = metadataOnlyIfNonzero != 0;
                Func <Compilation, Stream, ResourceDescription[], CodeAnalysis.Emit.EmitResult> emit;
                emit = (c, s, r) => c.Emit(s, manifestResources: r, options: new EmitOptions(metadataOnly: metadataOnly));

                var sourceTree = SyntaxFactory.ParseSyntaxTree("");

                // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad.
                var c1 = CSharpCompilation.Create(
                    Guid.NewGuid().ToString(),
                    new[] { sourceTree },
                    new[] { MscorlibRef },
                    TestOptions.ReleaseModule);

                var resourceFileName = "RoslynResourceFile.foo";
                var output           = new MemoryStream();

                const string r1Name = "some.dotted.NAME";
                const string r2Name = "another.DoTtEd.NAME";

                var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 };
                var resourceFileData    = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                var result = emit(c1, output,
                                  new ResourceDescription[]
                {
                    new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true),
                    new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false)
                });

                Assert.False(result.Success);
                Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

                result = emit(c1, output,
                              new ResourceDescription[]
                {
                    new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false),
                    new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true)
                });

                Assert.False(result.Success);
                Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

                result = emit(c1, output,
                              new ResourceDescription[]
                {
                    new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false)
                });

                Assert.False(result.Success);
                Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

                var c_mod1 = CSharpCompilation.Create(
                    Guid.NewGuid().ToString(),
                    new[] { sourceTree },
                    new[] { MscorlibRef },
                    TestOptions.ReleaseModule);

                var output_mod1 = new MemoryStream();
                result = emit(c_mod1, output_mod1,
                              new ResourceDescription[]
                {
                    new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true)
                });

                Assert.True(result.Success);
                var mod1     = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable());
                var ref_mod1 = mod1.GetReference();
                Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes);

                {
                    var c2      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1 }, TestOptions.ReleaseDll);
                    var output2 = new MemoryStream();
                    var result2 = c2.Emit(output2);

                    Assert.True(result2.Success);
                    var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray());

                    assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                    {
                        if (e.Name.Equals(c_mod1.SourceModule.Name))
                        {
                            return(assembly.LoadModule(e.Name, output_mod1.ToArray()));
                        }

                        return(null);
                    };

                    string[] resourceNames = assembly.GetManifestResourceNames();
                    Assert.Equal(1, resourceNames.Length);

                    var rInfo = assembly.GetManifestResourceInfo(r1Name);
                    Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName);

                    var rData  = assembly.GetManifestResourceStream(r1Name);
                    var rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(arrayOfEmbeddedData, rBytes);
                }

                var c_mod2 = CSharpCompilation.Create(
                    Guid.NewGuid().ToString(),
                    new[] { sourceTree },
                    new[] { MscorlibRef },
                    TestOptions.ReleaseModule);

                var output_mod2 = new MemoryStream();
                result = emit(c_mod2, output_mod2,
                              new ResourceDescription[]
                {
                    new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true),
                    new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true)
                });

                Assert.True(result.Success);
                var ref_mod2 = ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()).GetReference();

                {
                    var c3      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod2 }, TestOptions.ReleaseDll);
                    var output3 = new MemoryStream();
                    var result3 = c3.Emit(output3);

                    Assert.True(result3.Success);
                    var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray());

                    assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                    {
                        if (e.Name.Equals(c_mod2.SourceModule.Name))
                        {
                            return(assembly.LoadModule(e.Name, output_mod2.ToArray()));
                        }

                        return(null);
                    };

                    string[] resourceNames = assembly.GetManifestResourceNames();
                    Assert.Equal(2, resourceNames.Length);

                    var rInfo = assembly.GetManifestResourceInfo(r1Name);
                    Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName);

                    var rData  = assembly.GetManifestResourceStream(r1Name);
                    var rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(arrayOfEmbeddedData, rBytes);

                    rInfo = assembly.GetManifestResourceInfo(r2Name);
                    Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName);

                    rData  = assembly.GetManifestResourceStream(r2Name);
                    rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(resourceFileData, rBytes);
                }

                var c_mod3 = CSharpCompilation.Create(
                    Guid.NewGuid().ToString(),
                    new[] { sourceTree },
                    new[] { MscorlibRef },
                    TestOptions.ReleaseModule);

                var output_mod3 = new MemoryStream();
                result = emit(c_mod3, output_mod3,
                              new ResourceDescription[]
                {
                    new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
                });

                Assert.True(result.Success);
                var mod3     = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable());
                var ref_mod3 = mod3.GetReference();
                Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes);

                {
                    var c4      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod3 }, TestOptions.ReleaseDll);
                    var output4 = new MemoryStream();
                    var result4 = c4.Emit(output4, manifestResources:
                                          new ResourceDescription[]
                    {
                        new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false)
                    });

                    Assert.True(result4.Success);
                    var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray());

                    assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                    {
                        if (e.Name.Equals(c_mod3.SourceModule.Name))
                        {
                            return(assembly.LoadModule(e.Name, output_mod3.ToArray()));
                        }

                        return(null);
                    };

                    string[] resourceNames = assembly.GetManifestResourceNames();
                    Assert.Equal(2, resourceNames.Length);

                    var rInfo = assembly.GetManifestResourceInfo(r1Name);
                    Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation);

                    var rData  = assembly.GetManifestResourceStream(r1Name);
                    var rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(arrayOfEmbeddedData, rBytes);

                    rInfo = assembly.GetManifestResourceInfo(r2Name);
                    Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName);

                    rData  = assembly.GetManifestResourceStream(r2Name);
                    rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(resourceFileData, rBytes);
                }

                {
                    var c5      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.ReleaseDll);
                    var output5 = new MemoryStream();
                    var result5 = emit(c5, output5, null);

                    Assert.True(result5.Success);
                    var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray());

                    assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                    {
                        if (e.Name.Equals(c_mod1.SourceModule.Name))
                        {
                            return(assembly.LoadModule(e.Name, output_mod1.ToArray()));
                        }
                        else if (e.Name.Equals(c_mod3.SourceModule.Name))
                        {
                            return(assembly.LoadModule(e.Name, output_mod3.ToArray()));
                        }

                        return(null);
                    };

                    string[] resourceNames = assembly.GetManifestResourceNames();
                    Assert.Equal(2, resourceNames.Length);

                    var rInfo = assembly.GetManifestResourceInfo(r1Name);
                    Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName);

                    var rData  = assembly.GetManifestResourceStream(r1Name);
                    var rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(arrayOfEmbeddedData, rBytes);

                    rInfo = assembly.GetManifestResourceInfo(r2Name);
                    Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                    Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName);

                    rData  = assembly.GetManifestResourceStream(r2Name);
                    rBytes = new byte[rData.Length];
                    rData.Read(rBytes, 0, (int)rData.Length);
                    Assert.Equal(resourceFileData, rBytes);
                }

                {
                    var c6      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseDll);
                    var output6 = new MemoryStream();
                    var result6 = emit(c6, output6, null);

                    if (metadataOnly)
                    {
                        Assert.True(result6.Success);
                    }
                    else
                    {
                        Assert.False(result6.Success);
                        result6.Diagnostics.Verify(
                            // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly
                            Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME")
                            );
                    }

                    result6 = emit(c6, output6,
                                   new ResourceDescription[]
                    {
                        new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
                    });

                    if (metadataOnly)
                    {
                        Assert.True(result6.Success);
                    }
                    else
                    {
                        Assert.False(result6.Success);
                        result6.Diagnostics.Verify(
                            // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly
                            Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"),
                            // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly
                            Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME")
                            );
                    }

                    c6 = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseModule);

                    result6 = emit(c6, output6,
                                   new ResourceDescription[]
                    {
                        new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
                    });

                    Assert.True(result6.Success);
                }
            }
        }
コード例 #39
0
        public static Assembly Compile(Xamarin.Android.Binder.CodeGeneratorOptions options,
                                       string assemblyFileName, IEnumerable <string> AdditionalSourceDirectories,
                                       out bool hasErrors, out string output, bool allowWarnings)
        {
            // Gather all the files we need to compile
            var generatedCodePath = options.ManagedCallableWrapperSourceOutputDirectory;
            var sourceFiles       = Directory.EnumerateFiles(generatedCodePath, "*.cs",
                                                             SearchOption.AllDirectories).ToList();

            sourceFiles = sourceFiles.Select(x => Path.GetFullPath(x)).ToList();

            var supportFiles = Directory.EnumerateFiles(Path.Combine(Path.GetDirectoryName(supportFilePath), "SupportFiles"),
                                                        "*.cs", SearchOption.AllDirectories);

            sourceFiles.AddRange(supportFiles);

            foreach (var dir in AdditionalSourceDirectories)
            {
                var additonal = Directory.EnumerateFiles(dir, "*.cs", SearchOption.AllDirectories);
                sourceFiles.AddRange(additonal);
            }

            // Parse the source files
            var syntax_trees = sourceFiles.Distinct().Select(s => CSharpSyntaxTree.ParseText(File.ReadAllText(s))).ToArray();

            // Set up the assemblies we need to reference
            var binDir = Path.GetDirectoryName(typeof(BaseGeneratorTest).Assembly.Location);
            var facDir = GetFacadesPath();

            var references = new [] {
                MetadataReference.CreateFromFile(unitTestFrameworkAssemblyPath),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(binDir, "Java.Interop.dll")),
                MetadataReference.CreateFromFile(Path.Combine(facDir, "netstandard.dll"))
            };

            // Compile!
            var compilation = CSharpCompilation.Create(
                Path.GetFileName(assemblyFileName),
                syntaxTrees: syntax_trees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));

            // Save assembly to a memory stream and load it with reflection
            using (var ms = new MemoryStream()) {
                var result  = compilation.Emit(ms);
                var success = result.Success && (allowWarnings || !result.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Warning));

                if (!success)
                {
                    var failures = result.Diagnostics.Where(diagnostic =>
                                                            diagnostic.Severity == DiagnosticSeverity.Warning ||
                                                            diagnostic.Severity == DiagnosticSeverity.Error);

                    hasErrors = true;
                    output    = OutputDiagnostics(failures);
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);

                    hasErrors = false;
                    output    = null;

                    return(Assembly.Load(ms.ToArray()));
                }
            }

            return(null);
        }
コード例 #40
0
        public static FuncEval <TDelegate> FuncEval <TDelegate>(string expr)
        {
            // TODO: Investigate using the scripting APIs here instead.

            var typeName = "Expressions";

            var deleName = typeof(TDelegate).ToCSharp("System");

            var exprName = "Expression";
            var funcName = "Function";

            var exprProp = $"public static Expression<{deleName}> {exprName} => {expr};";
            var funcProp = $"public static {deleName} {funcName} => {expr};";

            var src = $@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

public static class {typeName}
{{
    public static readonly List<string> s_Log = new List<string>();

    public static T Return<T>(T value)
    {{
        s_Log.Add(value?.ToString());
        return value;
    }}

    public static T Log<T>(T value)
    {{
        return Return<T>(value); // just an alias for now
    }}

    public static T Await<T>(Func<Task<T>> f)
    {{
        return f().Result;
    }}

    public static void AwaitVoid(Func<Task> f)
    {{
        f().Wait();
    }}

    {exprProp}
    {funcProp}
}}
";

            var tree = CSharpSyntaxTree.ParseText(src);

            var csc = CSharpCompilation
                      // A class library `Expressions` which will be emitted in memory
                      .Create("Expressions")
                      .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: 0))

                      // BCL assemblies
                      .AddReferences(MetadataReference.CreateFromFile(typeof(int).Assembly.Location))
                      .AddReferences(MetadataReference.CreateFromFile(typeof(Expression).Assembly.Location))

                      // Our custom assembly
                      .AddReferences(new[] { MetadataReference.CreateFromFile(typeof(CSharpExpression).Assembly.Location) })

                      // Support for dynamic
                      .AddReferences(MetadataReference.CreateFromFile(typeof(CSharpDynamic.Binder).Assembly.Location))

                      // Test utilities
                      .AddReferences(MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location))

                      // Generated test code based on `expr`
                      .AddSyntaxTrees(tree);

            var asm = default(Assembly);

            using (var ms = new MemoryStream())
            {
                var res = default(EmitResult);

                try
                {
                    // NB: This can fail because we're testing custom builds of the compiler.
                    res = csc.Emit(ms);
                }
                catch (Exception ex)
                {
                    throw new Exception("Fatal compiler error!", ex); // TODO: add the program text
                }

                if (!res.Success)
                {
                    var diag = string.Join("\r\n", res.Diagnostics.Select(d => d.ToString()));
                    throw new InvalidProgramException(diag);
                }

                ms.Position = 0;

                asm = Assembly.Load(ms.ToArray());
            }

            var typ = asm.GetType(typeName);

            var exp = typ.GetProperty(exprName);
            var del = typ.GetProperty(funcName);
            var log = typ.GetField("s_Log");

            return(new FuncEval <TDelegate>
            {
                Function = (TDelegate)del.GetValue(null),
                Expression = (Expression <TDelegate>)exp.GetValue(null),
                Log = (List <string>)log.GetValue(null),
            });
        }
コード例 #41
0
        private IView GenerateExecutableCоde(string csharpCode, object viewModel)
        {
            var compileResult = CSharpCompilation.Create("ViewAssembly")
                                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                .AddReferences(MetadataReference.CreateFromFile(typeof(IView).Assembly.Location));

            if (viewModel != null)
            {
                if (viewModel.GetType().IsGenericType)
                {
                    var genericArguments = viewModel.GetType().GenericTypeArguments;

                    foreach (var genericArgument in genericArguments)
                    {
                        compileResult = compileResult
                                        .AddReferences(MetadataReference.CreateFromFile(genericArgument.Assembly.Location));
                    }
                }

                compileResult = compileResult
                                .AddReferences(MetadataReference.CreateFromFile(viewModel.GetType().Assembly.Location));
            }

            var libraries = Assembly.Load(
                new AssemblyName("netstandard")).GetReferencedAssemblies();

            foreach (var library in libraries)
            {
                compileResult = compileResult
                                .AddReferences(MetadataReference.CreateFromFile(
                                                   Assembly.Load(library).Location));
            }

            compileResult = compileResult.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(csharpCode));

            using var memoryStream = new MemoryStream();
            var result = compileResult.Emit(memoryStream);

            if (!result.Success)
            {
                return(new ErrorView(result.Diagnostics
                                     .Where(x => x.Severity == DiagnosticSeverity.Error)
                                     .Select(x => x.GetMessage()), csharpCode));
            }

            try
            {
                memoryStream.Seek(0, SeekOrigin.Begin);
                var byteAssembly = memoryStream.ToArray();

                var assembly = Assembly.Load(byteAssembly);
                var viewType = assembly.GetType("ViewNamespace.ViewClass");

                var instance = Activator.CreateInstance(viewType);

                return((instance as IView) ?? new ErrorView(new List <string> {
                    "Instance is null."
                }, csharpCode));
            }
            catch (Exception ex)
            {
                return(new ErrorView(new List <string> {
                    ex.ToString()
                }, csharpCode));
            }
        }
コード例 #42
0
ファイル: LambdaSymbol.cs プロジェクト: shibutamang/roslyn
        private ImmutableArray <ParameterSymbol> MakeParameters(
            CSharpCompilation compilation,
            UnboundLambda unboundLambda,
            ImmutableArray <TypeSymbolWithAnnotations> parameterTypes,
            ImmutableArray <RefKind> parameterRefKinds,
            DiagnosticBag diagnostics)
        {
            Debug.Assert(parameterTypes.Length == parameterRefKinds.Length);

            if (!unboundLambda.HasSignature || unboundLambda.ParameterCount == 0)
            {
                // The parameters may be omitted in source, but they are still present on the symbol.
                return(parameterTypes.SelectAsArray((type, ordinal, arg) =>
                                                    SynthesizedParameterSymbol.Create(
                                                        arg.owner,
                                                        type,
                                                        ordinal,
                                                        arg.refKinds[ordinal],
                                                        GeneratedNames.LambdaCopyParameterName(ordinal)),     // Make sure nothing binds to this.
                                                    (owner: this, refKinds: parameterRefKinds)));
            }

            var builder = ArrayBuilder <ParameterSymbol> .GetInstance(unboundLambda.ParameterCount);

            var hasExplicitlyTypedParameterList = unboundLambda.HasExplicitlyTypedParameterList;
            var numDelegateParameters           = parameterTypes.Length;

            for (int p = 0; p < unboundLambda.ParameterCount; ++p)
            {
                // If there are no types given in the lambda then used the delegate type.
                // If the lambda is typed then the types probably match the delegate types;
                // if they do not, use the lambda types for binding. Either way, if we
                // can, then we use the lambda types. (Whatever you do, do not use the names
                // in the delegate parameters; they are not in scope!)

                TypeSymbolWithAnnotations type;
                RefKind refKind;
                if (hasExplicitlyTypedParameterList)
                {
                    type    = unboundLambda.ParameterType(p);
                    refKind = unboundLambda.RefKind(p);
                }
                else if (p < numDelegateParameters)
                {
                    type    = parameterTypes[p];
                    refKind = parameterRefKinds[p];
                }
                else
                {
                    type    = TypeSymbolWithAnnotations.Create(new ExtendedErrorTypeSymbol(compilation, name: string.Empty, arity: 0, errorInfo: null));
                    refKind = RefKind.None;
                }

                var name      = unboundLambda.ParameterName(p);
                var location  = unboundLambda.ParameterLocation(p);
                var locations = location == null ? ImmutableArray <Location> .Empty : ImmutableArray.Create <Location>(location);
                var parameter = new SourceSimpleParameterSymbol(this, type, p, refKind, name, locations);

                builder.Add(parameter);
            }

            var result = builder.ToImmutableAndFree();

            return(result);
        }
コード例 #43
0
        private Assembly Compile(IBuilderContext builderContext, IEnumerable <SyntaxTree> syntaxTrees, string libraryFile, HashSet <string> fileReferences)
        {
            // Add references
            var metadataReferences = new List <MetadataReference>();

            foreach (var reference in fileReferences.Where(r => !string.IsNullOrEmpty(r)))
            {
                metadataReferences.Add(MetadataReference.CreateFromFile(reference));
            }

            metadataReferences.AddRange(BasicReferenceAssemblies.All);

            // suppress assembly redirect warnings
            // cf. https://github.com/dotnet/roslyn/issues/19640
            var noWarn = new List <KeyValuePair <string, ReportDiagnostic> >
            {
                new KeyValuePair <string, ReportDiagnostic>("CS1701", ReportDiagnostic.Suppress),
                new KeyValuePair <string, ReportDiagnostic>("CS1702", ReportDiagnostic.Suppress),
            };

            // Compile
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: (builderContext == null || builderContext.DebugScripts) ? OptimizationLevel.Debug : OptimizationLevel.Release,
                warningLevel: 4,
                specificDiagnosticOptions: noWarn,
                deterministic: true
                );

            var assemblyName = libraryFile != null?Path.GetFileNameWithoutExtension(libraryFile) : $"Sharpmake_{new Random().Next():X8}" + GetHashCode();

            var    compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, compilationOptions);
            string pdbFilePath = libraryFile != null?Path.ChangeExtension(libraryFile, ".pdb") : null;

            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    EmitResult result = compilation.Emit(
                        dllStream,
                        pdbStream,
                        options: new EmitOptions(
                            debugInformationFormat: DebugInformationFormat.PortablePdb,
                            pdbFilePath: pdbFilePath
                            )
                        );

                    bool throwErrorException = builderContext == null || builderContext.CompileErrorBehavior == BuilderCompileErrorBehavior.ThrowException;
                    LogCompilationResult(result, throwErrorException);

                    if (result.Success)
                    {
                        if (libraryFile != null)
                        {
                            dllStream.Seek(0, SeekOrigin.Begin);
                            using (var fileStream = new FileStream(libraryFile, FileMode.Create))
                                dllStream.CopyTo(fileStream);

                            pdbStream.Seek(0, SeekOrigin.Begin);
                            using (var pdbFileStream = new FileStream(pdbFilePath, FileMode.Create))
                                pdbStream.CopyTo(pdbFileStream);

                            return(Assembly.LoadFrom(libraryFile));
                        }

                        return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer()));
                    }
                }

            return(null);
        }
コード例 #44
0
 public override Compilation CreateLibraryCompilation(string name, IEnumerable <SyntaxTree> trees)
 {
     return(CSharpCompilation.Create("New", trees, _fxReferences, TestOptions.UnsafeReleaseDll));
 }
コード例 #45
0
 public AnonymousTypeComparer(CSharpCompilation compilation)
 {
     _compilation = compilation;
 }
コード例 #46
0
        public CompilationLookup(CSharpCompilation compilation)
        {
            this.compilation = compilation;

            this.Visit(compilation);
        }
コード例 #47
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()));
                    }
                }
            }
        }
コード例 #48
0
 internal static PENamedTypeSymbol GetType(this CSharpCompilation compilation, Guid moduleVersionId, int typeToken)
 {
     return(GetType(compilation.GetModule(moduleVersionId), (TypeDefinitionHandle)MetadataTokens.Handle(typeToken)));
 }
コード例 #49
0
ファイル: RazorCompiler.cs プロジェクト: zggl/tchapp
        public void Compile(string input)
        {
            input = Path.GetFullPath(input);
            if (!Directory.Exists(input))
            {
                throw new Exception($"path {input} not exists");
            }
            DirectoryInfo dir_info = new DirectoryInfo(input);
            var           files    = dir_info.GetFiles("*.cshtml", SearchOption.AllDirectories);

            SyntaxTree[]  tree = new SyntaxTree[files.Length];
            string        code, class_namespace, page_path;
            List <string> page_list = new List <string>();

            for (var i = 0; i < files.Length; ++i)
            {
                if (!Path.GetFileNameWithoutExtension(files[i].FullName).StartsWith("_"))
                {
                    page_path = files[i].FullName.Replace(input, "").Replace(Path.DirectorySeparatorChar, '/');
                    if (!page_path.StartsWith("/"))
                    {
                        page_path = "/" + page_path;
                    }
                    page_list.Add(page_path);
                }
                class_namespace = Path.GetDirectoryName(files[i].FullName).Replace(input, "").Replace(Path.DirectorySeparatorChar, '.');
                if (class_namespace.Length > 0 && !class_namespace.StartsWith("."))
                {
                    class_namespace = "." + class_namespace;
                }
                code    = getCSharpCode(files[i].FullName, TchRazorActivator.RootNamespace + class_namespace);
                tree[i] = CSharpSyntaxTree.ParseText(code);
            }

            var core_dir = Directory.GetParent(typeof(object).GetTypeInfo().Assembly.Location);
            var dlls     = core_dir.GetFiles("*.dll", SearchOption.AllDirectories);

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

            ref_list.Add(MetadataReference.CreateFromFile(Assembly.GetEntryAssembly().Location));
            ref_list.Add(MetadataReference.CreateFromFile(typeof(IRazorPage).GetTypeInfo().Assembly.Location));
            foreach (var clr_dll in dlls)
            {
                try
                {
                    AssemblyLoadContext.GetAssemblyName(clr_dll.FullName);
                    ref_list.Add(MetadataReference.CreateFromFile(clr_dll.FullName));
                }
                catch (BadImageFormatException) { };
            }

            var option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);
            CSharpCompilation compilation = CSharpCompilation.Create(Path.GetRandomFileName(), tree, ref_list, option);

            Assembly compiled_assembly;

            using (var assembly_stream = new MemoryStream())
            {
                var compileResult = compilation.Emit(assembly_stream);
                if (compileResult.Success)
                {
                    assembly_stream.Seek(0, SeekOrigin.Begin);
                    compiled_assembly = AssemblyLoadContext.Default.LoadFromStream(assembly_stream);
                }
                else
                {
                    foreach (var error_info in compileResult.Diagnostics)
                    {
                        Console.WriteLine(error_info.ToString());
                    }
                    return;
                }
            }
            TchRazorActivator.InnerAssembly = compiled_assembly;
            foreach (var page in page_list)
            {
                ViewContext view_context = new ViewContext();
                view_context.ExecutingFilePath = page;
                TchRazorActivator.GetView(view_context, page).RenderAsync(view_context);
                var html        = (view_context.Writer as StringWriter).GetStringBuilder().ToString();
                var output_path = Path.Combine(input, page.Remove(0, 1).Replace('/', Path.DirectorySeparatorChar));
                output_path = output_path.Remove(output_path.Length - 6, 2);
                File.WriteAllText(output_path, html, Encoding.UTF8);
            }
        }
コード例 #50
0
        private int RunFieldInitalizers(CompilationModule[] compiledModules)
        {
            CompilationModule[] modulesToInitialize = compiledModules.Where(e => e.fieldsWithInitializers.Count > 0).ToArray();

            // We don't need to run the costly compilation if the user hasn't defined any fields with initializers
            if (modulesToInitialize.Length == 0)
            {
                return(0);
            }

            int initializerErrorCount = 0;

            SyntaxTree[]    initializerTrees   = new SyntaxTree[modulesToInitialize.Length];
            StringBuilder[] codeStringBuilders = new StringBuilder[modulesToInitialize.Length];

            for (int moduleIdx = 0; moduleIdx < modulesToInitialize.Length; ++moduleIdx)
            {
                CompilationModule module = modulesToInitialize[moduleIdx];

                CodeCompileUnit compileUnit = new CodeCompileUnit();
                CodeNamespace   ns          = new CodeNamespace("FieldInitialzers");
                compileUnit.Namespaces.Add(ns);
                foreach (var resolverUsingNamespace in module.resolver.usingNamespaces)
                {
                    if (!string.IsNullOrEmpty(resolverUsingNamespace))
                    {
                        ns.Imports.Add(new CodeNamespaceImport(resolverUsingNamespace));
                    }
                }

                CodeTypeDeclaration _class = new CodeTypeDeclaration($"Initializer{moduleIdx}");
                ns.Types.Add(_class);
                CodeMemberMethod method = new CodeMemberMethod();
                _class.Members.Add(method);
                method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                method.ReturnType = new CodeTypeReference(typeof(void));
                method.Name       = "DoInit";
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IUdonProgram), "program"));

                foreach (var fieldDeclarationSyntax in module.fieldsWithInitializers)
                {
                    var  type    = fieldDeclarationSyntax.Declaration.Type;
                    int  count   = 0;
                    bool isConst = fieldDeclarationSyntax.Modifiers.Any(t => t.ToString() == "const");
                    foreach (var variable in fieldDeclarationSyntax.Declaration.Variables)
                    {
                        FieldDefinition fieldDef = module.compiledClassDefinition?.fieldDefinitions?.Find(e => (e.fieldSymbol.declarationType == SymbolDeclTypeFlags.Private || e.fieldSymbol.declarationType == SymbolDeclTypeFlags.Public) &&
                                                                                                          e.fieldSymbol.symbolOriginalName == variable.Identifier.ToString());

                        string typeQualifiedName = type.ToString().Replace('+', '.');
                        if (fieldDef != null)
                        {
                            string namespaceStr = "";

                            System.Type symbolType = fieldDef.fieldSymbol.symbolCsType;

                            if (symbolType.Namespace != null &&
                                symbolType.Namespace.Length > 0)
                            {
                                namespaceStr = symbolType.Namespace + ".";
                            }

                            string nestedTypeStr = "";

                            System.Type declaringType = symbolType.DeclaringType;

                            while (declaringType != null)
                            {
                                nestedTypeStr = $"{declaringType.Name}.{nestedTypeStr}";
                                declaringType = declaringType.DeclaringType;
                            }

                            typeQualifiedName = namespaceStr + nestedTypeStr + fieldDef.fieldSymbol.symbolCsType.Name;
                        }

                        if (variable.Initializer != null)
                        {
                            string name = variable.Identifier.ToString();
                            if (isConst)
                            {
                                _class.Members.Add(new CodeSnippetTypeMember($"const {typeQualifiedName} {name} {variable.Initializer};"));
                            }
                            else
                            {
                                method.Statements.Add(new CodeSnippetStatement($"{typeQualifiedName} {name} {variable.Initializer};"));
                            }

                            method.Statements.Add(new CodeSnippetStatement(
                                                      $"program.Heap.SetHeapVariable(program.SymbolTable.GetAddressFromSymbol(\"{variable.Identifier}\"), {name});"));

                            count++;
                        }
                    }
                }

                StringBuilder sb = new StringBuilder();
                codeStringBuilders[moduleIdx] = sb;

                CSharpCodeProvider provider = new CSharpCodeProvider();
                using (StringWriter streamWriter = new StringWriter(sb))
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, streamWriter, new CodeGeneratorOptions());
                }

                SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sb.ToString());

                initializerTrees[moduleIdx] = syntaxTree;
            }

            var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
            var references = new List <MetadataReference>();

            for (int i = 0; i < assemblies.Length; i++)
            {
                if (!assemblies[i].IsDynamic && assemblies[i].Location.Length > 0)
                {
                    references.Add(MetadataReference.CreateFromFile(assemblies[i].Location));
                }
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                $"init{initAssemblyCounter++}",
                syntaxTrees: initializerTrees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var memoryStream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(memoryStream);
                if (!result.Success)
                {
                    // todo: make these errors point to the correct source files
                    bool error = false;
                    foreach (Diagnostic diagnostic in result.Diagnostics)
                    {
                        if (diagnostic.Severity == DiagnosticSeverity.Error)
                        {
                            Debug.LogError(diagnostic);
                            error = true;
                            initializerErrorCount++;
                        }
                    }

                    if (error)
                    {
                        Debug.LogError($"Generated Source code: {string.Join("\n", codeStringBuilders.Select(e => e.ToString()))}");
                    }
                }
                else
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    Assembly assembly = Assembly.Load(memoryStream.ToArray());

                    for (int moduleIdx = 0; moduleIdx < modulesToInitialize.Length; ++moduleIdx)
                    {
                        CompilationModule module  = modulesToInitialize[moduleIdx];
                        IUdonProgram      program = module.programAsset.GetRealProgram();

                        System.Type cls        = assembly.GetType($"FieldInitialzers.Initializer{moduleIdx}");
                        MethodInfo  methodInfo = cls.GetMethod("DoInit", BindingFlags.Public | BindingFlags.Static);
                        methodInfo.Invoke(null, new[] { program });

                        foreach (var fieldDeclarationSyntax in module.fieldsWithInitializers)
                        {
                            foreach (var variable in fieldDeclarationSyntax.Declaration.Variables)
                            {
                                string varName = variable.Identifier.ToString();

                                object heapValue = program.Heap.GetHeapVariable(program.SymbolTable.GetAddressFromSymbol(varName));

                                if (heapValue != null && UdonSharpUtils.IsUserDefinedType(heapValue.GetType()))
                                {
                                    UdonSharpUtils.LogBuildError($"Field: '{varName}' UdonSharp does not yet support field initializers on user-defined types or jagged arrays", AssetDatabase.GetAssetPath(module.programAsset.sourceCsScript), 0, 0);
                                }
                            }
                        }
                    }
                }
            }

            return(initializerErrorCount);
        }
コード例 #51
0
 public CppImplWalker(CSharpCompilation compilation, SemanticModel model, ConversionSettings settings) : base(compilation, model, settings)
 {
 }
コード例 #52
0
 public void Validate(CSharpCompilation compilation, CSharpSyntaxTree tree, SemanticModel model,
                      Assembly assembly)
 {
     CSharpCommonValidator.ValidateProperties(tree, model, Lesson1CommonValidator.CreateStep4Properties());
 }
コード例 #53
0
ファイル: RoslynExtensions.cs プロジェクト: ashikns/Utf8Json
        public static Compilation GetCompilationFromProject(
            IEnumerable <string> inputFiles,
            IEnumerable <string> inputDirectories,
            IEnumerable <string> additionalCompilationDirectories = null,
            string[] preprocessorSymbols = null)
        {
            var parseOptions = new CSharpParseOptions(LanguageVersion.Default, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessorSymbols ?? new string[0]);
            var references   = new List <MetadataReference>();

            var referenceDlls = Directory.GetFiles(Path.GetDirectoryName(typeof(object).Assembly.Location), "*.dll");

            foreach (var dllFile in referenceDlls)
            {
                references.Add(MetadataReference.CreateFromFile(dllFile));
            }

            foreach (var dir in inputDirectories ?? new string[0])
            {
                var dlls = Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories);
                foreach (var dll in dlls)
                {
                    references.Add(MetadataReference.CreateFromFile(dll));
                }
            }

            foreach (var path in inputFiles ?? new string[0])
            {
                if (path.EndsWith(".dll", StringComparison.Ordinal))
                {
                    references.Add(MetadataReference.CreateFromFile(path));
                }
            }

            if (additionalCompilationDirectories != null)
            {
                var interimSyntaxTrees = new List <SyntaxTree>();

                foreach (var dir in inputDirectories ?? new string[0])
                {
                    var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        var text = File.ReadAllText(file);
                        interimSyntaxTrees.Add(CSharpSyntaxTree.ParseText(text, parseOptions));
                    }
                }

                foreach (var path in inputFiles ?? new string[0])
                {
                    if (path.EndsWith(".cs", StringComparison.Ordinal))
                    {
                        var text = File.ReadAllText(path);
                        interimSyntaxTrees.Add(CSharpSyntaxTree.ParseText(text, parseOptions));
                    }
                }

                foreach (var dir in additionalCompilationDirectories)
                {
                    var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        var text = File.ReadAllText(file);
                        interimSyntaxTrees.Add(CSharpSyntaxTree.ParseText(text, parseOptions));
                    }

                    var dlls = Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories);
                    foreach (var dll in dlls)
                    {
                        references.Add(MetadataReference.CreateFromFile(dll));
                    }
                }

                CSharpCompilation intermediateCompilation = CSharpCompilation.Create(
                    "Assembly-CSharp",
                    syntaxTrees: interimSyntaxTrees,
                    references: references
                    );

                references.Add(intermediateCompilation.ToMetadataReference());
            }

            var syntaxTrees = new List <SyntaxTree>();

            foreach (var dir in inputDirectories ?? new string[0])
            {
                var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    var text = File.ReadAllText(file);
                    syntaxTrees.Add(CSharpSyntaxTree.ParseText(text, parseOptions));
                }
            }

            foreach (var path in inputFiles ?? new string[0])
            {
                if (path.EndsWith(".cs", StringComparison.Ordinal))
                {
                    var text = File.ReadAllText(path);
                    syntaxTrees.Add(CSharpSyntaxTree.ParseText(text, parseOptions));
                }
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                "Assembly-CSharp",
                syntaxTrees: syntaxTrees,
                references: references
                );

            return(compilation);
        }
コード例 #54
0
        public string ConvertToTypescript(string text, SettingStore settingStore)
        {
            try
            {
                var tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text);

                // detect to see if it's actually C# sourcode by checking whether it has any error
                if (tree.GetDiagnostics().Any(f => f.Severity == DiagnosticSeverity.Error))
                {
                    return(null);
                }

                var root = tree.GetRoot();

                // if it only contains comments, just return the original texts
                if (IsEmptyRoot(root))
                {
                    return(null);
                }

                if (settingStore.IsConvertToInterface)
                {
                    root = ClassToInterfaceReplacement.ReplaceClass(root);
                }

                if (settingStore.IsConvertMemberToCamelCase)
                {
                    root = MakeMemberCamelCase.Make(root);
                }

                if (settingStore.IsConvertListToArray)
                {
                    root = ListToArrayReplacement.ReplaceList(root);
                }

                if (settingStore.ReplacedTypeNameArray.Length > 0)
                {
                    root = TypeNameReplacement.Replace(settingStore.ReplacedTypeNameArray, root);
                }

                if (settingStore.AddIPrefixInterfaceDeclaration)
                {
                    root = AddIPrefixInterfaceDeclaration.AddIPrefix(root);
                }

                if (settingStore.IsInterfaceOptionalProperties)
                {
                    root = OptionalInterfaceProperties.AddOptional(root);
                }

                tree = (CSharpSyntaxTree)root.SyntaxTree;

                var translationNode = TF.Get(root, null);

                var compilation = CSharpCompilation.Create("TemporaryCompilation",
                                                           syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
                var model = compilation.GetSemanticModel(tree);

                translationNode.Compilation   = compilation;
                translationNode.SemanticModel = model;

                translationNode.ApplyPatch();
                return(translationNode.Translate());
            }
            catch (Exception ex)
            {
                // TODO
                // swallow exception .!!!!!!!!!!!!!!!!!!!!!!!
            }

            return(null);
        }
コード例 #55
0
 /// <summary>
 /// Constructs a new instance of this object.
 /// </summary>
 /// <param name="cSharpCompilation">A C# compilation resulting from compiling code via a Compiler.</param>
 public Compilation(CSharpCompilation cSharpCompilation)
 {
     this.cSharpCompilation = cSharpCompilation;
 }
コード例 #56
0
ファイル: WinMdTests.cs プロジェクト: layomia/dotnet_roslyn
        private void CompileTimeAndRuntimeAssemblies(
            ImmutableArray <MetadataReference> compileReferences,
            ImmutableArray <MetadataReference> runtimeReferences,
            string storageAssemblyName)
        {
            var source =
                @"class C
{
    static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
    {
    }
}";
            var compilation0 = CreateEmptyCompilation(source, compileReferences, TestOptions.DebugDll);

            WithRuntimeInstance(compilation0, runtimeReferences, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                string error;
                var testData = new CompilationTestData();
                context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData);
                Assert.Null(error);
                testData.GetMethodData("<>x.<>m0").VerifyIL(
                    @"{
  // Code size       17 (0x11)
  .maxstack  2
  IL_0000:  ldarg.0
  IL_0001:  dup
  IL_0002:  brtrue.s   IL_0010
  IL_0004:  pop
  IL_0005:  ldarg.1
  IL_0006:  dup
  IL_0007:  brtrue.s   IL_0010
  IL_0009:  pop
  IL_000a:  ldarg.2
  IL_000b:  dup
  IL_000c:  brtrue.s   IL_0010
  IL_000e:  pop
  IL_000f:  ldarg.3
  IL_0010:  ret
}");
                testData   = new CompilationTestData();
                var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData);
                Assert.Null(error);
                var methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        2 (0x2)
  .maxstack  1
  IL_0000:  ldnull
  IL_0001:  ret
}");
                // Check return type is from runtime assembly.
                var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
                var compilation       = CSharpCompilation.Create(
                    assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                    references: runtimeReferences.Concat(ImmutableArray.Create <MetadataReference>(assemblyReference)));
                var assembly = ImmutableArray.CreateRange(result.Assembly);
                using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
                {
                    var reader          = metadata.MetadataReader;
                    var typeDef         = reader.GetTypeDef("<>x");
                    var methodHandle    = reader.GetMethodDefHandle(typeDef, "<>m0");
                    var module          = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
                    var metadataDecoder = new MetadataDecoder(module);
                    SignatureHeader signatureHeader;
                    BadImageFormatException metadataException;
                    var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
                    Assert.Equal(5, parameters.Length);
                    var actualReturnType = parameters[0].Type;
                    Assert.Equal(TypeKind.Class, actualReturnType.TypeKind); // not error
                    var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
                    Assert.Equal(expectedReturnType, actualReturnType);
                    Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
                }
            });
        }
コード例 #57
0
        public static object Eval(string expr, out SemanticModel sem, bool includingExpressions = true, bool trimCR = false)
        {
            // TODO: Investigate using the scripting APIs here instead.

            expr = Indent(expr);

            var typeName = "Expressions";
            var propName = "Expression";

            var exprProp = $"    public static Expression {propName} => {expr};";

            var src = $@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

public static class {typeName}
{{
{exprProp}
}}
".Trim('\r', '\n');

            if (trimCR)
            {
                src = src.Replace("\r\n", "\n");
            }

            var tree = CSharpSyntaxTree.ParseText(src);

            tree = Format(tree, trimCR);

            var csc = CSharpCompilation
                      // A class library `Expressions` which will be emitted in memory
                      .Create("Expressions")
                      .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: 0))

                      // BCL assemblies
                      .AddReferences(MetadataReference.CreateFromFile(typeof(int).Assembly.Location))
                      .AddReferences(MetadataReference.CreateFromFile(typeof(Expression).Assembly.Location))

                      // BCL extensions for C# 7
                      .AddReferences(new[] { MetadataReference.CreateFromFile(typeof(ValueTuple).Assembly.Location) })

                      // Our custom assembly
                      .AddReferences(includingExpressions ? new[] { MetadataReference.CreateFromFile(typeof(CSharpExpression).Assembly.Location) } : Array.Empty <MetadataReference>())

                      // Support for dynamic
                      .AddReferences(MetadataReference.CreateFromFile(typeof(CSharpDynamic.Binder).Assembly.Location))

                      // Generated test code based on `expr`
                      .AddSyntaxTrees(tree);

            var asm = default(Assembly);

            using (var ms = new MemoryStream())
            {
                var res = default(EmitResult);

                try
                {
                    // NB: This can fail because we're testing custom builds of the compiler.
                    res = csc.Emit(ms);
                    sem = csc.GetSemanticModel(tree, false);
                }
                catch (Exception ex)
                {
                    throw new Exception("Fatal compiler error!", ex); // TODO: add the program text
                }

                if (!res.Success)
                {
                    var diag = string.Join("\r\n", res.Diagnostics.Select(d => d.ToString()));
                    throw new InvalidProgramException(diag);
                }

                ms.Position = 0;

                asm = Assembly.Load(ms.ToArray());
            }

            var typ = asm.GetType(typeName);
            var prp = typ.GetProperty(propName);

            return(prp.GetValue(null));
        }
コード例 #58
0
        /// <summary>
        /// 使用文件流进行脚本编译,根据类名生成dll
        /// </summary>
        /// <param name="content">脚本内容</param>
        /// <param name="className">指定类名</param>
        /// <param name="errorAction">发生错误执行委托</param>
        /// <returns></returns>
        public static Assembly FileComplier(string content, string className = null, Action <string> errorAction = null)
        {
#if DEBUG
            StringBuilder recoder = new StringBuilder(content);
#endif


            //类名获取
            if (className == null)
            {
                className = GetClassName(content);
            }


            //生成路径
            string path = $"{LibPath}{className}.dll";


            NDebug.Show("Writing:" + path);


            if (DynamicDlls.ContainsKey(path))
            {
                return(DynamicDlls[path]);
            }


            //写入分析树
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(content);


            //创建语言编译
            CSharpCompilation compilation = CSharpCompilation.Create(
                className,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: References);


            //锁住内容
            lock (content)
            {
                //再次检查缓存,解决并发问题
                if (DynamicDlls.ContainsKey(path))
                {
                    return(DynamicDlls[path]);
                }


                //编译到文件
                var fileResult = compilation.Emit(path);
                if (fileResult.Success)
                {
                    References.Add(MetadataReference.CreateFromFile(path));
                    //为了实现动态中的动态,使用文件加载模式常驻内存
                    var result = Assembly.LoadFrom(path);


#if DEBUG
                    recoder.AppendLine("\r\n\r\n------------------------------------------succeed-------------------------------------------");
                    recoder.AppendLine($"\r\n    Target :\t\t{className}");
                    recoder.AppendLine($"\r\n    Path :\t\t{path}");
                    recoder.AppendLine($"\r\n    Assembly : \t{result.FullName}");
                    recoder.AppendLine("\r\n----------------------------------------------------------------------------------------------");
                    NDebug.Show($"Builder Assembly Succeed : {result.FullName}");
                    NDebug.FileRecoder("Succeed : " + className, recoder.ToString());
#endif


                    DynamicDlls[path] = result;
                    return(result);
                }
                else
                {
#if DEBUG
                    recoder.AppendLine("\r\n\r\n------------------------------------------error----------------------------------------------");
                    recoder.AppendLine($"\r\n    Target:\t\t{className}");
                    recoder.AppendLine($"\r\n    Error:");
#endif


                    foreach (var item in fileResult.Diagnostics)
                    {
#if DEBUG
                        recoder.AppendLine("\t\t" + item.GetMessage());
#endif
                        errorAction?.Invoke(item.GetMessage());
                    }


#if DEBUG
                    recoder.AppendLine("\r\n---------------------------------------------------------------------------------------------");
#endif
                    NDebug.FileRecoder("Error : " + className, recoder.ToString());
                }
            }
            return(null);
        }
コード例 #59
0
        public Assembly FastLoad(string code, params Assembly[] rs)
        {
            string assemblyName = Path.GetRandomFileName();
            string attribute    = $"[assembly: Monkey.Compilation.MonkeyGenerated]\r\n";

            code = code.Insert(code.IndexOf("namespace"), attribute);
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);

            MetadataReference[] references = AppDomain.CurrentDomain.GetAssemblies()
                                             .Where(x => !x.IsDynamic && !x.GetCustomAttributes <MonkeyGeneratedAttribute>().Any())
                                             .Union(rs)
                                             .Distinct()
                                             .Select(OnLoadAssembly)
                                             .Where(x => x != null)
                                             .ToArray();


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

            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);
                    string[]      lines = Regex.Split(code, "\r\n|\r|\n");
                    StringBuilder sb    = new StringBuilder();
                    foreach (Diagnostic diagnostic in failures)
                    {
                        sb.AppendFormat("{0}: {1}\r\n", diagnostic.Id, diagnostic.GetMessage());
                        var line = diagnostic.Location.GetLineSpan().StartLinePosition.Line;
                        sb.AppendFormat($"Code({line}):\r\n");

                        for (int i = line - 1; i < line + 2; i++)
                        {
                            sb.AppendLine($"{i}:{lines[i]}");
                        }

                        sb.AppendLine();
                    }
                    throw new CompilationException(sb.ToString())
                          {
                              Errors = failures.ToArray()
                          };
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    string tmpFile = Path.GetTempFileName() + ".dll";
                    using (var file = File.OpenWrite(tmpFile))
                        ms.CopyTo(file);

                    Assembly assembly = Assembly.LoadFrom(tmpFile);
                    return(assembly);
                }
            }
        }
コード例 #60
0
ファイル: Compilation.cs プロジェクト: Runt-Editor/Runt
 public static ProjectCompilation Create(string name, int id)
 {
     return(new ProjectCompilation(CSharpCompilation.Create(name), id, ImmutableDictionary.Create <int, int>(), ValidItems.None, 0));
 }