예제 #1
0
 public override SyntaxList <StatementSyntax> VisitWhileBlock(VBSyntax.WhileBlockSyntax node)
 {
     return(SingleStatement(SyntaxFactory.WhileStatement(
                                (ExpressionSyntax)node.WhileStatement.Condition.Accept(nodesVisitor),
                                SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(this))).UnpackBlock()
                                )));
 }
예제 #2
0
            private bool ConvertToSwitch(ExpressionSyntax expr, SyntaxList <VBSyntax.CaseBlockSyntax> caseBlocks, out SwitchStatementSyntax switchStatement)
            {
                switchStatement = null;

                var sections = new List <SwitchSectionSyntax>();

                foreach (var block in caseBlocks)
                {
                    var labels = new List <SwitchLabelSyntax>();
                    foreach (var c in block.CaseStatement.Cases)
                    {
                        if (c is VBSyntax.SimpleCaseClauseSyntax)
                        {
                            var s = (VBSyntax.SimpleCaseClauseSyntax)c;
                            labels.Add(SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)s.Value.Accept(nodesVisitor)));
                        }
                        else if (c is VBSyntax.ElseCaseClauseSyntax)
                        {
                            labels.Add(SyntaxFactory.DefaultSwitchLabel());
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    var list = SingleStatement(SyntaxFactory.Block(block.Statements.SelectMany(s => s.Accept(this)).Concat(SyntaxFactory.BreakStatement())));
                    sections.Add(SyntaxFactory.SwitchSection(SyntaxFactory.List(labels), list));
                }
                switchStatement = SyntaxFactory.SwitchStatement(expr, SyntaxFactory.List(sections));
                return(true);
            }
예제 #3
0
            public override SyntaxList <StatementSyntax> VisitSelectBlock(VBSyntax.SelectBlockSyntax node)
            {
                var expr = (ExpressionSyntax)node.SelectStatement.Expression.Accept(_nodesVisitor);
                var exprWithoutTrivia = expr.WithoutTrivia().WithoutAnnotations();
                var sections          = new List <SwitchSectionSyntax>();

                foreach (var block in node.CaseBlocks)
                {
                    var labels = new List <SwitchLabelSyntax>();
                    foreach (var c in block.CaseStatement.Cases)
                    {
                        if (c is VBSyntax.SimpleCaseClauseSyntax s)
                        {
                            var expressionSyntax = (ExpressionSyntax)s.Value.Accept(_nodesVisitor);
                            SwitchLabelSyntax caseSwitchLabelSyntax = SyntaxFactory.CaseSwitchLabel(expressionSyntax);
                            if (!_semanticModel.GetConstantValue(s.Value).HasValue)
                            {
                                caseSwitchLabelSyntax =
                                    WrapInCasePatternSwitchLabelSyntax(expressionSyntax);
                            }

                            labels.Add(caseSwitchLabelSyntax);
                        }
                        else if (c is VBSyntax.ElseCaseClauseSyntax)
                        {
                            labels.Add(SyntaxFactory.DefaultSwitchLabel());
                        }
                        else if (c is VBSyntax.RelationalCaseClauseSyntax relational)
                        {
                            var operatorKind     = VBasic.VisualBasicExtensions.Kind(relational);
                            var cSharpSyntaxNode = SyntaxFactory.BinaryExpression(operatorKind.ConvertToken(TokenContext.Local), exprWithoutTrivia, (ExpressionSyntax)relational.Value.Accept(_nodesVisitor));
                            labels.Add(WrapInCasePatternSwitchLabelSyntax(cSharpSyntaxNode));
                        }
                        else if (c is VBSyntax.RangeCaseClauseSyntax range)
                        {
                            var lowerBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, (ExpressionSyntax)range.LowerBound.Accept(_nodesVisitor), exprWithoutTrivia);
                            var upperBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, exprWithoutTrivia, (ExpressionSyntax)range.UpperBound.Accept(_nodesVisitor));
                            var withinBounds    = SyntaxFactory.BinaryExpression(SyntaxKind.LogicalAndExpression, lowerBoundCheck, upperBoundCheck);
                            labels.Add(WrapInCasePatternSwitchLabelSyntax(withinBounds));
                        }
                        else
                        {
                            throw new NotSupportedException(c.Kind().ToString());
                        }
                    }

                    var csBlockStatements = block.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)).ToList();
                    if (csBlockStatements.LastOrDefault()
                        ?.IsKind(SyntaxKind.ReturnStatement) != true)
                    {
                        csBlockStatements.Add(SyntaxFactory.BreakStatement());
                    }
                    var list = SingleStatement(SyntaxFactory.Block(csBlockStatements));
                    sections.Add(SyntaxFactory.SwitchSection(SyntaxFactory.List(labels), list));
                }

                var switchStatementSyntax = ValidSyntaxFactory.SwitchStatement(expr, sections);

                return(SingleStatement(switchStatementSyntax));
            }
예제 #4
0
        /// <summary>
        /// Returns syntax for initializing a new instance of the provided type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>Syntax for initializing a new instance of the provided type.</returns>
        private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type)
        {
            ExpressionSyntax result;
            var typeInfo = type.GetTypeInfo();

            if (typeInfo.IsValueType)
            {
                // Use the default value.
                result = SF.DefaultExpression(typeInfo.AsType().GetTypeSyntax());
            }
            else if (typeInfo.GetConstructor(Type.EmptyTypes) != null)
            {
                // Use the default constructor.
                result = SF.ObjectCreationExpression(typeInfo.AsType().GetTypeSyntax()).AddArgumentListArguments();
            }
            else
            {
                // Create an unformatted object.
                Expression <Func <object> > getUninitializedObject =
#if NETSTANDARD
                    () => SerializationManager.GetUninitializedObjectWithFormatterServices(default(Type));
#else
                    () => FormatterServices.GetUninitializedObject(default(Type));
#endif
                result = SF.CastExpression(
                    type.GetTypeSyntax(),
                    getUninitializedObject.Invoke()
                    .AddArgumentListArguments(
                        SF.Argument(SF.TypeOfExpression(typeInfo.AsType().GetTypeSyntax()))));
            }

            return(result);
        }
예제 #5
0
    //*/

    //*
    public static NameSyntax OptionalOf(TypeSyntax type)
    {
        return
            (SF.GenericName(
                 SF.Identifier(nameof(Option)),
                 SF.TypeArgumentList(SF.SingletonSeparatedList(type))));
    }
예제 #6
0
    /*
     * public static MemberAccessExpressionSyntax OptionalValue( ExpressionSyntax optionalOfTExpression )
     * {
     *      return SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, optionalOfTExpression, SF.IdentifierName(nameof( Option<int>.)));
     * }
     */

    /*
     * public static ExpressionSyntax OptionalFor( ExpressionSyntax expression )
     * {
     *      return SF.InvocationExpression(
     *                      SF.MemberAccessExpression(
     *                                      SyntaxKind.SimpleMemberAccessExpression,
     *                                      SF.QualifiedName(
     *                                                      SF.IdentifierName(nameof(ImmutableObjectGraph)),
     *                                                      SF.IdentifierName(nameof(ImmutableObjectGraph.Optional))),
     *                                      SF.IdentifierName(nameof(ImmutableObjectGraph.Optional.For))),
     *                      SF.ArgumentList(SF.SingletonSeparatedList(SF.Argument(expression))));
     * }
     */

    /*
     * public static ExpressionSyntax OptionalForIf( ExpressionSyntax expression, bool isOptional )
     * {
     *      return isOptional ? OptionalFor(expression) : expression;
     * }
     */

    /*
     * public static ImmutableArray<DeclarationInfo> GetDeclarationsInSpan( this SemanticModel model, TextSpan span, bool getSymbol, CancellationToken cancellationToken )
     * {
     *      return CSharpDeclarationComputer.GetDeclarationsInSpan(model, span, getSymbol, cancellationToken);
     * }
     * //*/

    //*
    public static NameSyntax GetTypeSyntax(Type type)
    {
        Requires.NotNull(type, nameof(type));

        SimpleNameSyntax leafType = SF.IdentifierName(type.IsGenericType ? type.Name.Substring(0, type.Name.IndexOf('`')) : type.Name);

        if (type.IsGenericType)
        {
            leafType = SF.GenericName(
                ((IdentifierNameSyntax)leafType).Identifier,
                SF.TypeArgumentList(JoinSyntaxNodes <TypeSyntax>(SyntaxKind.CommaToken, type.GenericTypeArguments.Select(GetTypeSyntax))));
        }

        if (type.Namespace != null)
        {
            NameSyntax namespaceName = null;
            foreach (string segment in type.Namespace.Split('.'))
            {
                var segmentName = SF.IdentifierName(segment);
                namespaceName = namespaceName == null
                                                ? (NameSyntax)segmentName
                                                : SF.QualifiedName(namespaceName, SF.IdentifierName(segment));
            }

            return(SF.QualifiedName(namespaceName, leafType));
        }

        return(leafType);
    }
        private CasePatternSwitchLabelSyntax WrapInCasePatternSwitchLabelSyntax(VBSyntax.SelectBlockSyntax node, ExpressionSyntax cSharpSyntaxNode, bool treatAsBoolean = false)
        {
            var typeInfo = _semanticModel.GetTypeInfo(node.SelectStatement.Expression);

            DeclarationPatternSyntax patternMatch;

            if (typeInfo.ConvertedType.SpecialType == SpecialType.System_Boolean || treatAsBoolean)
            {
                patternMatch = SyntaxFactory.DeclarationPattern(
                    SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)),
                    SyntaxFactory.DiscardDesignation());
            }
            else
            {
                var varName = CommonConversions.ConvertIdentifier(SyntaxFactory.Identifier(GetUniqueVariableNameInScope(node, "case"))).ValueText;
                patternMatch = SyntaxFactory.DeclarationPattern(
                    SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(varName)));
                cSharpSyntaxNode = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), cSharpSyntaxNode);
            }

            var casePatternSwitchLabelSyntax = SyntaxFactory.CasePatternSwitchLabel(patternMatch,
                                                                                    SyntaxFactory.WhenClause(cSharpSyntaxNode), SyntaxFactory.Token(SyntaxKind.ColonToken));

            return(casePatternSwitchLabelSyntax);
        }
예제 #8
0
            public override SyntaxList <StatementSyntax> VisitForEachBlock(VBSyntax.ForEachBlockSyntax node)
            {
                var stmt = node.ForEachStatement;

                TypeSyntax  type = null;
                SyntaxToken id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v           = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    var declaration = CommonConversions.SplitVariableDeclarations(v).Values.Single();
                    type = declaration.Type;
                    id   = declaration.Variables[0].Identifier;
                }
                else
                {
                    var v = (IdentifierNameSyntax)stmt.ControlVariable.Accept(_nodesVisitor);
                    id   = v.Identifier;
                    type = SyntaxFactory.ParseTypeName("var");
                }

                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)));

                return(SingleStatement(SyntaxFactory.ForEachStatement(
                                           type,
                                           id,
                                           (ExpressionSyntax)stmt.Expression.Accept(_nodesVisitor),
                                           block.UnpackNonNestedBlock()
                                           )));
            }
예제 #9
0
        public Dictionary <string, VariableDeclarationSyntax> SplitVariableDeclarations(
            VariableDeclaratorSyntax declarator, bool preferExplicitType = false)
        {
            var rawType     = ConvertDeclaratorType(declarator, preferExplicitType);
            var initializer = ConvertInitializer(declarator);

            var newDecls = new Dictionary <string, VariableDeclarationSyntax>();

            foreach (var name in declarator.Names)
            {
                var(type, adjustedInitializer) = AdjustFromName(rawType, name, initializer);
                var    equalsValueClauseSyntax = adjustedInitializer == null ? null : SyntaxFactory.EqualsValueClause(adjustedInitializer);
                var    v = SyntaxFactory.VariableDeclarator(ConvertIdentifier(name.Identifier), null, equalsValueClauseSyntax);
                string k = type.ToString();
                if (newDecls.TryGetValue(k, out var decl))
                {
                    newDecls[k] = decl.AddVariables(v);
                }
                else
                {
                    newDecls[k] = SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList(v));
                }
            }

            return(newDecls);
        }
예제 #10
0
    public void BeforeCompile(IBeforeCompileContext context)
    {
        // Firstly, I need to resolve the namespace of the ModuleProvider instance in this current compilation.
        string ns = GetModuleProviderNamespace(context.Compilation.SyntaxTrees);
        // Next, get all the available modules in assembly and compilation references.
        var modules = GetAvailableModules(context.Compilation).ToList();
        // Map them to a collection of statements
        var statements = modules.Select(m => F.ParseStatement("AddModule<" + module + ">();")).ToList();
        // Now, I'll create the dynamic implementation as a private class.
        var cu = F.CompilationUnit()
                 .AddMembers(
            F.NamespaceDeclaration(F.IdentifierName(ns))
            .AddMembers(
                F.ClassDeclaration("ModuleProvider")
                .WithModifiers(F.TokenList(F.Token(K.PartialKeyword)))
                .AddMembers(
                    F.MethodDeclaration(F.PredefinedType(F.Token(K.VoidKeyword)), "Setup")
                    .WithModifiers(
                        F.TokenList(
                            F.Token(K.ProtectedKeyword),
                            F.Token(K.OverrideKeyword)))
                    .WithBody(F.Block(statements))
                    )
                )
            )
                 .NormalizeWhitespace(indentation("\t"));
        var tree = T.Create(cu);

        context.Compilation = context.Compilation.AddSyntaxTrees(tree);
    }
예제 #11
0
 public override SyntaxList <StatementSyntax> VisitSyncLockBlock(VBSyntax.SyncLockBlockSyntax node)
 {
     return(SingleStatement(SyntaxFactory.LockStatement(
                                (ExpressionSyntax)node.SyncLockStatement.Expression.Accept(_nodesVisitor),
                                SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))).UnpackNonNestedBlock()
                                )));
 }
        public override SyntaxList <StatementSyntax> VisitAssignmentStatement(VBSyntax.AssignmentStatementSyntax node)
        {
            var lhs        = (ExpressionSyntax)node.Left.Accept(_expressionVisitor);
            var lOperation = _semanticModel.GetOperation(node.Left);

            //Already dealt with by call to the same method in VisitInvocationExpression
            if (CommonConversions.GetParameterizedPropertyAccessMethod(lOperation, out var _) != null)
            {
                return(SingleStatement(lhs));
            }
            var rhs = (ExpressionSyntax)node.Right.Accept(_expressionVisitor);

            if (node.Left is VBSyntax.IdentifierNameSyntax id &&
                _methodNode is VBSyntax.MethodBlockSyntax mb &&
                HasReturnVariable &&
                id.Identifier.ValueText.Equals(mb.SubOrFunctionStatement.Identifier.ValueText, StringComparison.OrdinalIgnoreCase))
            {
                lhs = ReturnVariable;
            }

            if (node.IsKind(VBasic.SyntaxKind.ExponentiateAssignmentStatement))
            {
                rhs = SyntaxFactory.InvocationExpression(
                    SyntaxFactory.ParseExpression($"{nameof(Math)}.{nameof(Math.Pow)}"),
                    ExpressionSyntaxExtensions.CreateArgList(lhs, rhs));
            }
            var kind = node.Kind().ConvertToken(TokenContext.Local);

            var assignment = SyntaxFactory.AssignmentExpression(kind, lhs, rhs);

            var postAssignment = GetPostAssignmentStatements(node);

            return(postAssignment.Insert(0, SyntaxFactory.ExpressionStatement(assignment)));
        }
예제 #13
0
            /// <summary>
            /// Array copy for multiple array dimensions represented by <paramref name="convertedBounds"/>
            /// </summary>
            /// <remarks>
            /// Exception cases will sometimes silently succeed in the converted code,
            ///  but existing VB code relying on the exception thrown from a multidimensional redim preserve on
            ///  different rank arrays is hopefully rare enough that it's worth saving a few lines of code
            /// </remarks>
            private StatementSyntax CreateArrayCopy(VBasic.VisualBasicSyntaxNode originalVbNode,
                                                    IdentifierNameSyntax sourceArrayExpression,
                                                    MemberAccessExpressionSyntax sourceLength,
                                                    ExpressionSyntax targetArrayExpression, ICollection convertedBounds)
            {
                var lastSourceLengthArgs = ExpressionSyntaxExtensions.CreateArgList(CommonConversions.Literal(convertedBounds.Count - 1));
                var sourceLastRankLength = SyntaxFactory.InvocationExpression(
                    SyntaxFactory.ParseExpression($"{sourceArrayExpression.Identifier}.GetLength"), lastSourceLengthArgs);
                var targetLastRankLength =
                    SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression($"{targetArrayExpression}.GetLength"),
                                                       lastSourceLengthArgs);
                var length = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("Math.Min"), ExpressionSyntaxExtensions.CreateArgList(sourceLastRankLength, targetLastRankLength));

                var loopVariableName            = GetUniqueVariableNameInScope(originalVbNode, "i");
                var loopVariableIdentifier      = SyntaxFactory.IdentifierName(loopVariableName);
                var sourceStartForThisIteration =
                    SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression, loopVariableIdentifier, sourceLastRankLength);
                var targetStartForThisIteration =
                    SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression, loopVariableIdentifier, targetLastRankLength);

                var arrayCopy = CreateArrayCopyWithStartingPoints(sourceArrayExpression, sourceStartForThisIteration, targetArrayExpression,
                                                                  targetStartForThisIteration, length);

                var sourceArrayCount = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression,
                                                                      SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, sourceLength, sourceLastRankLength), CommonConversions.Literal(1));

                return(CreateForZeroToValueLoop(loopVariableIdentifier, arrayCopy, sourceArrayCount));
            }
예제 #14
0
 public static ExpressionSyntax BaseDot(SimpleNameSyntax memberAccess)
 {
     return(SF.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SF.BaseExpression(),
                memberAccess));
 }
예제 #15
0
    public static SyntaxNodeOrTokenList JoinSyntaxNodes <T>(SyntaxToken separatingToken, IReadOnlyList <T> nodes)
        where T : SyntaxNode
    {
        Requires.NotNull(nodes, nameof(nodes));

        switch (nodes.Count)
        {
        case 0:
            return(SF.NodeOrTokenList());

        case 1:
            return(SF.NodeOrTokenList(nodes[0]));

        default:
            var nodesOrTokens = new SyntaxNodeOrToken[(nodes.Count * 2) - 1];
            nodesOrTokens[0] = nodes[0];
            for (int i = 1; i < nodes.Count; i++)
            {
                int targetIndex = i * 2;
                nodesOrTokens[targetIndex - 1] = separatingToken;
                nodesOrTokens[targetIndex]     = nodes[i];
            }

            return(SF.NodeOrTokenList(nodesOrTokens));
        }
    }
예제 #16
0
    /*
     * public static T Or<T>(this Option<T> thisOption, T or)
     * {
     *      T v;
     *
     *      thisOption.
     *
     *      return v;
     * }
     */


    public static FieldDeclarationSyntax Field(string fieldName, string type, Optional <ExpressionSyntax> assignment, params SyntaxKind[] modifiers)
    {
        //var st = SF.ParseStatement( $"static public readonly {m_class.Identifier} def = new {m_class.Identifier};" );
        //var newClass = SF.ParseExpression( $"new {m_class.Identifier}()" );

        var declarator = SF.VariableDeclarator(fieldName);

        if (assignment.HasValue)
        {
            declarator = declarator.WithInitializer(SF.EqualsValueClause(assignment.Value));
        }


        var decl = SF.VariableDeclaration(SF.IdentifierName(type), SF.SingletonSeparatedList(declarator));

        var field = SF.FieldDeclaration(decl);

        if (modifiers.Length > 0)
        {
            var stl = new SyntaxTokenList(modifiers.Select(mod => SF.Token(mod)));

            field = field.WithModifiers(stl);
        }

        return(field);
    }
예제 #17
0
        public async Task <(IReadOnlyCollection <(CSSyntax.VariableDeclarationSyntax Decl, ITypeSymbol Type)> Variables, IReadOnlyCollection <CSharpSyntaxNode> Methods)> SplitVariableDeclarationsAsync(
            VariableDeclaratorSyntax declarator, HashSet <ILocalSymbol> symbolsToSkip = null, bool preferExplicitType = false)
        {
            var vbInitValue             = GetInitializerToConvert(declarator);
            var initializerOrMethodDecl = await vbInitValue.AcceptAsync <CSharpSyntaxNode>(TriviaConvertingExpressionVisitor);

            var vbInitializerTypeInfo = vbInitValue != null?_semanticModel.GetTypeInfo(vbInitValue) : default(TypeInfo?);

            var vbInitializerType = vbInitValue != null ? vbInitializerTypeInfo.Value.Type : default(ITypeSymbol);

            bool          requireExplicitTypeForAll = declarator.Names.Count > 1;
            IMethodSymbol initSymbol = null;

            if (vbInitValue != null)
            {
                TypeInfo expType = vbInitializerTypeInfo.Value;
                preferExplicitType |= ShouldPreferExplicitType(vbInitValue, expType.ConvertedType, out bool vbInitIsNothingLiteral);
                initSymbol          = _semanticModel.GetSymbolInfo(vbInitValue).Symbol as IMethodSymbol;
                bool isAnonymousFunction = initSymbol?.IsAnonymousFunction() == true;
                requireExplicitTypeForAll |= vbInitIsNothingLiteral || isAnonymousFunction;
            }

            var csVars    = new Dictionary <string, (CSSyntax.VariableDeclarationSyntax Decl, ITypeSymbol Type)>();
            var csMethods = new List <CSharpSyntaxNode>();

            foreach (var name in declarator.Names)
            {
                var declaredSymbol = _semanticModel.GetDeclaredSymbol(name);
                if (symbolsToSkip?.Contains(declaredSymbol) == true)
                {
                    continue;
                }
                var declaredSymbolType      = declaredSymbol.GetSymbolType();
                var equalsValueClauseSyntax = await ConvertEqualsValueClauseSyntaxAsync(declarator, name, vbInitValue, declaredSymbolType, declaredSymbol, initializerOrMethodDecl);

                var    v = SyntaxFactory.VariableDeclarator(ConvertIdentifier(name.Identifier), null, equalsValueClauseSyntax);
                string k = declaredSymbolType?.GetFullMetadataName() ?? name.ToString();//Use likely unique key if the type symbol isn't available

                if (csVars.TryGetValue(k, out var decl))
                {
                    csVars[k] = (decl.Decl.AddVariables(v), decl.Type);
                    continue;
                }

                if (initializerOrMethodDecl == null || initializerOrMethodDecl is ExpressionSyntax)
                {
                    var variableDeclaration = CreateVariableDeclaration(declarator, preferExplicitType,
                                                                        requireExplicitTypeForAll, vbInitializerType, declaredSymbolType, equalsValueClauseSyntax,
                                                                        initSymbol, v);
                    csVars[k] = (variableDeclaration, declaredSymbolType);
                }
                else
                {
                    csMethods.Add(initializerOrMethodDecl);
                }
            }

            return(csVars.Values, csMethods);
        }
예제 #18
0
        /// <summary>
        /// Generates the class for the provided grain types.
        /// </summary>
        /// <param name="grainType">
        /// The grain interface type.
        /// </param>
        /// <returns>
        /// The generated class.
        /// </returns>
        internal static TypeDeclarationSyntax GenerateClass(Type grainType)
        {
            var baseTypes = new List <BaseTypeSyntax> {
                SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax())
            };

            var grainTypeInfo = grainType.GetTypeInfo();
            var genericTypes  = grainTypeInfo.IsGenericTypeDefinition
                                   ? grainTypeInfo.GetGenericArguments()
                                .Select(_ => SF.TypeParameter(_.ToString()))
                                .ToArray()
                                   : new TypeParameterSyntax[0];

            // Create the special method invoker marker attribute.
            var interfaceId         = GrainInterfaceUtils.GetGrainInterfaceId(grainType);
            var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId));
            var grainTypeArgument   = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false));
            var attributes          = new List <AttributeSyntax>
            {
                CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
                SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax())
                .AddArgumentListArguments(
                    SF.AttributeArgument(grainType.GetParseableName().GetLiteralExpression()),
                    SF.AttributeArgument(interfaceIdArgument),
                    SF.AttributeArgument(grainTypeArgument)),
#if !NETSTANDARD
                SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax())
#endif
            };

            var members = new List <MemberDeclarationSyntax>
            {
                GenerateInvokeMethod(grainType),
                GenerateInterfaceIdProperty(grainType)
            };

            // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker.
            if (typeof(IGrainExtension).IsAssignableFrom(grainType))
            {
                baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax()));
                members.Add(GenerateExtensionInvokeMethod(grainType));
            }

            var classDeclaration =
                SF.ClassDeclaration(
                    CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix)
                .AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
                .AddBaseListTypes(baseTypes.ToArray())
                .AddConstraintClauses(grainType.GetTypeConstraintSyntax())
                .AddMembers(members.ToArray())
                .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()));

            if (genericTypes.Length > 0)
            {
                classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
            }

            return(classDeclaration);
        }
 public override ExplicitInterfaceSpecifierSyntax ExplicitInterfaceSpecifier()
 {
     return(SF.ExplicitInterfaceSpecifier(
                SF.GenericName(
                    Basics.SerializerInterfaceIdentifier,
                    SF.TypeArgumentList(new SeparatedSyntaxList <TypeSyntax>().Add(SF.ParseTypeName(ClassSymbol.ToString())))),
                SF.Token(SyntaxKind.DotToken)));
 }
예제 #20
0
 private TypeSyntax ConvertDeclaratorType(VariableDeclaratorSyntax declarator)
 {
     return((TypeSyntax)declarator.AsClause?.TypeSwitch(
                (SimpleAsClauseSyntax c) => c.Type,
                (AsNewClauseSyntax c) => c.NewExpression.Type(),
                _ => { throw new NotImplementedException($"{_.GetType().FullName} not implemented!"); }
                )?.Accept(_nodesVisitor) ?? SyntaxFactory.ParseTypeName("var"));
 }
예제 #21
0
        public static Dictionary <string, CSharpSyntaxNode> ConvertMultiple(VBasic.VisualBasicCompilation compilation, IEnumerable <VBasic.VisualBasicSyntaxTree> syntaxTrees)
        {
            var cSharpFirstPass = syntaxTrees.ToDictionary(tree => tree.FilePath ?? "unknown",
                                                           tree => (CSharpSyntaxTree)SyntaxFactory.SyntaxTree(tree.GetRoot().Accept(new NodesVisitor(compilation.GetSemanticModel(tree, true)))));
            var cSharpCompilation = CSharpCompilation.Create("Conversion", cSharpFirstPass.Values, compilation.References);

            return(cSharpFirstPass.ToDictionary(cs => cs.Key, cs => new CompilationErrorFixer(cSharpCompilation, cs.Value).Fix()));
        }
예제 #22
0
            public override SyntaxList <StatementSyntax> VisitAddRemoveHandlerStatement(VBSyntax.AddRemoveHandlerStatementSyntax node)
            {
                var syntaxKind = ConvertAddRemoveHandlerToCSharpSyntaxKind(node);

                return(SingleStatement(SyntaxFactory.AssignmentExpression(syntaxKind,
                                                                          (ExpressionSyntax)node.EventExpression.Accept(_nodesVisitor),
                                                                          (ExpressionSyntax)node.DelegateExpression.Accept(_nodesVisitor))));
            }
 StatementSyntax GenerateCheckpoint()
 {
     return(SF.LocalDeclarationStatement(
                SF.VariableDeclaration(
                    SF.ParseTypeName("var"),
                    SF.SingletonSeparatedList(
                        SF.VariableDeclarator(
                            checkpointToken,
예제 #24
0
 public static NameSyntax IEquatableOf(TypeSyntax typeSyntax)
 {
     return(SF.QualifiedName(
                SF.IdentifierName(nameof(System)),
                SF.GenericName(
                    SF.Identifier(nameof(IEquatable <int>)),
                    SF.TypeArgumentList(SF.SingletonSeparatedList(typeSyntax)))));
 }
예제 #25
0
 public override SyntaxList <StatementSyntax> VisitReturnStatement(VBSyntax.ReturnStatementSyntax node)
 {
     if (IsIterator)
     {
         return(SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement)));
     }
     return(SingleStatement(SyntaxFactory.ReturnStatement((ExpressionSyntax)node.Expression?.Accept(_nodesVisitor))));
 }
 public static ExpressionSyntax VbCoerceToString(ExpressionSyntax csNode, TypeInfo typeInfo)
 {
     return(typeInfo.Type?.SpecialType switch
     {
         SpecialType.System_String => csNode,
         SpecialType.System_Char => SyntaxFactory.InvocationExpression(ValidSyntaxFactory.MemberAccess(csNode, nameof(ToString))),
         _ => NewStringFromArg(csNode)
     });
예제 #27
0
            public override SyntaxList <StatementSyntax> VisitAddRemoveHandlerStatement(VBSyntax.AddRemoveHandlerStatementSyntax node)
            {
                var syntaxKind = node.Kind() == VBasic.SyntaxKind.AddHandlerStatement ? SyntaxKind.AddAssignmentExpression : SyntaxKind.SubtractAssignmentExpression;

                return(SingleStatement(SyntaxFactory.AssignmentExpression(syntaxKind,
                                                                          (ExpressionSyntax)node.EventExpression.Accept(nodesVisitor),
                                                                          (ExpressionSyntax)node.DelegateExpression.Accept(nodesVisitor))));
            }
예제 #28
0
 internal static AttributeSyntax GetGeneratedCodeAttributeSyntax()
 {
     return
         (SF.Attribute(typeof(GeneratedCodeAttribute).GetNameSyntax())
          .AddArgumentListArguments(
              SF.AttributeArgument(CodeGeneratorName.GetLiteralExpression()),
              SF.AttributeArgument(CodeGeneratorVersion.GetLiteralExpression())));
 }
예제 #29
0
            /// <summary>
            /// Returns syntax for retrieving the value of this field, deep copying it if necessary.
            /// </summary>
            /// <param name="instance">The instance of the containing type.</param>
            /// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param>
            /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
            /// <returns>Syntax for retrieving the value of this field.</returns>
            public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false)
            {
                // Retrieve the value of the field.
                var getValueExpression = this.GetValueExpression(instance);

                // Avoid deep-copying the field if possible.
                if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
                {
                    // Return the value without deep-copying it.
                    return(getValueExpression);
                }

                // Addressable arguments must be converted to references before passing.
                // IGrainObserver instances cannot be directly converted to references, therefore they are not included.
                ExpressionSyntax deepCopyValueExpression;

                if (typeof(IAddressable).IsAssignableFrom(this.FieldInfo.FieldType) &&
                    this.FieldInfo.FieldType.GetTypeInfo().IsInterface &&
                    !typeof(IGrainObserver).IsAssignableFrom(this.FieldInfo.FieldType))
                {
                    var getAsReference = getValueExpression.Member(
                        (IAddressable grain) => grain.AsReference <IGrain>(),
                        this.FieldInfo.FieldType);

                    // If the value is not a GrainReference, convert it to a strongly-typed GrainReference.
                    // C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>()
                    deepCopyValueExpression =
                        SF.ConditionalExpression(
                            SF.ParenthesizedExpression(
                                SF.BinaryExpression(
                                    SyntaxKind.LogicalOrExpression,
                                    SF.BinaryExpression(
                                        SyntaxKind.EqualsExpression,
                                        getValueExpression,
                                        SF.LiteralExpression(SyntaxKind.NullLiteralExpression)),
                                    SF.BinaryExpression(
                                        SyntaxKind.IsExpression,
                                        getValueExpression,
                                        typeof(GrainReference).GetTypeSyntax()))),
                            getValueExpression,
                            SF.InvocationExpression(getAsReference));
                }
                else
                {
                    deepCopyValueExpression = getValueExpression;
                }

                // Deep-copy the value.
                Expression <Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object), default(ICopyContext));
                var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax();

                return(SF.CastExpression(
                           typeSyntax,
                           deepCopyInner.Invoke()
                           .AddArgumentListArguments(
                               SF.Argument(deepCopyValueExpression),
                               SF.Argument(serializationContextExpression))));
            }
예제 #30
0
        /// <summary>
        /// Returns syntax for the static fields of the serializer class.
        /// </summary>
        /// <param name="fields">The fields.</param>
        /// <returns>Syntax for the static fields of the serializer class.</returns>
        private static MemberDeclarationSyntax[] GenerateFields(List <FieldInfoMember> fields)
        {
            var result = new List <MemberDeclarationSyntax>();

            // Add each field and initialize it.
            foreach (var field in fields)
            {
                // Declare the getter for this field.
                if (!field.IsGettableProperty)
                {
                    var getterType =
                        typeof(Func <,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
                        .GetTypeSyntax();
                    var fieldGetterVariable = SF.VariableDeclarator(field.GetterFieldName);

                    result.Add(
                        SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable))
                        .AddModifiers(
                            SF.Token(SyntaxKind.PrivateKeyword),
                            SF.Token(SyntaxKind.ReadOnlyKeyword)));
                }

                if (!field.IsSettableProperty)
                {
                    if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.IsValueType)
                    {
                        var setterType =
                            typeof(ValueTypeSetter <,>).MakeGenericType(
                                field.FieldInfo.DeclaringType,
                                field.FieldInfo.FieldType).GetTypeSyntax();

                        var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName);

                        result.Add(
                            SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
                            .AddModifiers(
                                SF.Token(SyntaxKind.PrivateKeyword),
                                SF.Token(SyntaxKind.ReadOnlyKeyword)));
                    }
                    else
                    {
                        var setterType =
                            typeof(Action <,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType)
                            .GetTypeSyntax();

                        var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName);

                        result.Add(
                            SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
                            .AddModifiers(
                                SF.Token(SyntaxKind.PrivateKeyword),
                                SF.Token(SyntaxKind.ReadOnlyKeyword)));
                    }
                }
            }

            return(result.ToArray());
        }