Esempio n. 1
0
        /// <summary>
        /// Gets the syntax for the creation of an anonymous type.
        /// </summary>
        /// <param name="tableElement">The description of a table.</param>
        /// <returns>An expression that builds an anonymous type from a table description.</returns>
        public static ExpressionSyntax GetSyntax(TableElement tableElement)
        {
            // Validate the parameter
            if (tableElement == null)
            {
                throw new ArgumentNullException(nameof(tableElement));
            }

            // new { country.CountryId, country.CountryCode, country.Name, country.RowVersion };
            List <SyntaxNodeOrToken> properties = new List <SyntaxNodeOrToken>();

            foreach (ColumnElement columnElement in tableElement.Columns)
            {
                if (properties.Count != 0)
                {
                    properties.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                }

                properties.Add(
                    SyntaxFactory.AnonymousObjectMemberDeclarator(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName(tableElement.Name.ToVariableName()),
                            SyntaxFactory.IdentifierName(columnElement.Name))));
            }

            return(SyntaxFactory.AnonymousObjectCreationExpression(
                       SyntaxFactory.SeparatedList <AnonymousObjectMemberDeclaratorSyntax>(properties)));
        }
Esempio n. 2
0
        public override SyntaxNode MakeSyntaxNode()
        {
            var res = SyntaxFactory.AnonymousObjectMemberDeclarator(NameEquals, Expression);

            IsChanged = false;
            return(res);
        }
Esempio n. 3
0
        public CSharpSyntaxNode Convert(ObjectLiteralExpression node)
        {
            List <Node> properties = node.Properties;
            Node        type       = node.Type;

            if (type.Kind == NodeKind.TypeLiteral && properties.Count >= 2 && (type as TypeLiteral).Members[0].Kind != NodeKind.IndexSignature)
            {
                return(SyntaxFactory.TupleExpression().AddArguments(properties.ToCsNodes <ArgumentSyntax>()));
            }
            else if (type.Kind == NodeKind.AnyKeyword)
            {
                AnonymousObjectCreationExpressionSyntax csAnonyNewExpr = SyntaxFactory.AnonymousObjectCreationExpression();
                foreach (PropertyAssignment prop in node.Properties)
                {
                    string           propName  = prop.Name.Text;
                    Node             initValue = prop.Initializer;
                    ExpressionSyntax valueExpr = initValue.ToCsNode <ExpressionSyntax>();

                    if (type.Kind == NodeKind.TypeLiteral && initValue.Kind == NodeKind.NullKeyword)
                    {
                        Node memType = TypeHelper.GetTypeLiteralMemberType(type as TypeLiteral, propName);
                        if (memType != null)
                        {
                            valueExpr = SyntaxFactory.CastExpression(memType.ToCsNode <TypeSyntax>(), valueExpr);
                        }
                    }

                    csAnonyNewExpr = csAnonyNewExpr.AddInitializers(SyntaxFactory.AnonymousObjectMemberDeclarator(
                                                                        SyntaxFactory.NameEquals(propName),
                                                                        valueExpr));
                }
                return(csAnonyNewExpr);
            }
            else
            {
                ObjectCreationExpressionSyntax csObjLiteral  = SyntaxFactory.ObjectCreationExpression(type.ToCsNode <TypeSyntax>()).AddArgumentListArguments();
                List <ExpressionSyntax>        initItemExprs = new List <ExpressionSyntax>();
                foreach (PropertyAssignment prop in properties)
                {
                    ExpressionSyntax csNameExpression = SyntaxFactory.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        SyntaxFactory.Literal(prop.Name.Text));
                    InitializerExpressionSyntax itemInitExpr = SyntaxFactory
                                                               .InitializerExpression(SyntaxKind.ComplexElementInitializerExpression)
                                                               .AddExpressions(csNameExpression, prop.Initializer.ToCsNode <ExpressionSyntax>());

                    initItemExprs.Add(itemInitExpr);
                }
                if (initItemExprs.Count > 0)
                {
                    return(csObjLiteral.WithInitializer(SyntaxFactory.InitializerExpression(
                                                            SyntaxKind.CollectionInitializerExpression,
                                                            SyntaxFactory.SeparatedList(initItemExprs))));
                }
                return(csObjLiteral);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Creates an argument that creates a lambda expression for extracting the key from a class.
        /// </summary>
        /// <param name="foreignKeyElement">The unique key element.</param>
        /// <returns>An argument that extracts a key from an object.</returns>
        public static ExpressionSyntax GetForeignKey(ForeignKeyElement foreignKeyElement)
        {
            // Validate the parameter
            if (foreignKeyElement == null)
            {
                throw new ArgumentNullException(nameof(foreignKeyElement));
            }

            // Used as a variable when constructing the lambda expression.
            string abbreviation = foreignKeyElement.Table.Name[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant();

            // This will create an expression for extracting the key from record.
            CSharpSyntaxNode syntaxNode = null;

            if (foreignKeyElement.Columns.Count == 1)
            {
                // A simple key can be used like a value type.
                syntaxNode = SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    SyntaxFactory.IdentifierName(abbreviation),
                    SyntaxFactory.IdentifierName(foreignKeyElement.Columns[0].Column.Name));
            }
            else
            {
                // A Compound key must be constructed from an anomymous type.
                List <SyntaxNodeOrToken> keyElements = new List <SyntaxNodeOrToken>();
                foreach (ColumnReferenceElement columnReferenceElement in foreignKeyElement.Columns)
                {
                    if (keyElements.Count != 0)
                    {
                        keyElements.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                    }

                    keyElements.Add(
                        SyntaxFactory.AnonymousObjectMemberDeclarator(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.IdentifierName(abbreviation),
                                SyntaxFactory.IdentifierName(columnReferenceElement.Column.Name))));
                }

                // b => b.BuyerId or b => new { b.BuyerId, b.ExternalId0 }
                syntaxNode = SyntaxFactory.AnonymousObjectCreationExpression(
                    SyntaxFactory.SeparatedList <AnonymousObjectMemberDeclaratorSyntax>(keyElements.ToArray()));
            }

            //            this.BuyerKey = new SimpleForeignKeyIndex<Buyer>("BuyerKey").HasIndex(b => b.BuyerId);
            return(SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(SyntaxFactory.Identifier(abbreviation)), syntaxNode));
        }
Esempio n. 5
0
        private static SyntaxNodeOrToken GetNewSyntaxListItem(SyntaxNodeOrToken item)
        {
            if (!item.IsNode)
            {
                return(item);
            }

            var member = (AnonymousObjectMemberDeclaratorSyntax)item.AsNode();

            if (member.Expression is IdentifierNameSyntax identifier &&
                identifier.Identifier.ValueText == member.NameEquals.Name.Identifier.ValueText)
            {
                return(SyntaxFactory.AnonymousObjectMemberDeclarator(member.Expression).WithTriviaFrom(member));
            }

            return(item);
        }
Esempio n. 6
0
        public string BuildExpression(Dictionary <string, ExpressionSyntax> selectExpressions)
        {
            var memberDeclarators = new SeparatedSyntaxList <AnonymousObjectMemberDeclaratorSyntax>();

            foreach (var curExpr in selectExpressions.OrderBy(x => x.Key))
            {
                var name = SyntaxFactory.NameEquals(curExpr.Key);
                var assignmentExpression = SyntaxFactory.AnonymousObjectMemberDeclarator(name, curExpr.Value);
                memberDeclarators = memberDeclarators.Add(assignmentExpression);
            }

            var anonymousObjectCreationExpression = SyntaxFactory.AnonymousObjectCreationExpression(memberDeclarators);

            if (InvocationExpression != null)
            {
                ExpressionSyntax expression = null;
                if (InvocationExpression.Expression is MemberAccessExpressionSyntax mae)
                {
                    expression = mae;
                }
                else if (InvocationExpression.Expression is IdentifierNameSyntax identifier)
                {
                    expression = identifier;
                }

                var invocExp = SyntaxFactory.InvocationExpression(expression)
                               .WithArgumentList(
                    SyntaxFactory.ArgumentList(
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.Argument(
                                SyntaxFactory.SimpleLambdaExpression(
                                    SyntaxFactory.Parameter(SyntaxFactory.Identifier("doc")),
                                    anonymousObjectCreationExpression)))));
                return(invocExp.ToString().Normalize());
            }

            if (FromExpression != null)
            {
                var queryExpr = SyntaxFactory.QueryExpression(
                    SyntaxFactory.FromClause("doc", FromExpression),
                    SyntaxFactory.QueryBody(SyntaxFactory.SelectClause(anonymousObjectCreationExpression)));
                return(queryExpr.ToString().Normalize());
            }

            return(null);
        }
        private static async Task <Document> AddProjectionAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the type declaration identified by the diagnostic.
            var declarator   = (VariableDeclaratorSyntax)root.FindToken(diagnosticSpan.Start).Parent;
            var invocation   = (InvocationExpressionSyntax)declarator.Initializer.Value;
            var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression;

            var firstArgument = invocation.ArgumentList.Arguments.FirstOrDefault();

            if (firstArgument != null)
            {
                // Move condition from .First() to extra .Where() call so that we can place the .Select() between them
                var whereExpression   = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccess.Expression, SyntaxFactory.IdentifierName("Where"));
                var withWhere         = SyntaxFactory.InvocationExpression(whereExpression, invocation.ArgumentList);
                var whereMemberAccess = memberAccess.WithExpression(withWhere);
                var newInvocation     = SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, whereMemberAccess.Expression, memberAccess.Name));
                root = root.ReplaceNode(invocation, newInvocation);

                declarator   = (VariableDeclaratorSyntax)root.FindToken(diagnosticSpan.Start).Parent;
                invocation   = (InvocationExpressionSyntax)declarator.Initializer.Value;
                memberAccess = (MemberAccessExpressionSyntax)invocation.Expression;
            }

            var selectExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccess.Expression, SyntaxFactory.IdentifierName("Select"));
            var itExpr           = SyntaxFactory.IdentifierName("it");
            var it        = SyntaxFactory.Identifier("it");
            var members   = diagnostic.Properties["Members"].Split('\n').Select(m => SyntaxFactory.AnonymousObjectMemberDeclarator(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, itExpr, SyntaxFactory.IdentifierName(m))));
            var newExpr   = SyntaxFactory.AnonymousObjectCreationExpression(SyntaxFactory.SeparatedList(members));
            var argument  = SyntaxFactory.Argument(SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(it), newExpr));
            var arguments = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(argument));
            var projectedInvocationExpression = SyntaxFactory.InvocationExpression(selectExpression, arguments);
            var newMemberAccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, projectedInvocationExpression, memberAccess.Name);

            var newRoot = root.ReplaceNode(memberAccess, newMemberAccess);

            return(document.WithSyntaxRoot(newRoot));
        }
Esempio n. 8
0
 public static AnonymousObjectCreationExpressionSyntax Anonymous(params Tuple <string, ExpressionSyntax>[] initializers)
 {
     return(SyntaxFactory.AnonymousObjectCreationExpression(SyntaxFactory.SeparatedList(
                                                                initializers.Select(x =>
                                                                                    SyntaxFactory.AnonymousObjectMemberDeclarator(SyntaxFactory.NameEquals(x.Item1), x.Item2)
                                                                                    ),
                                                                initializers.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken)))));
 }
Esempio n. 9
0
        public virtual LocalDeclarationStatementSyntax GetSyntax()
        {
            if (BodyParams.FirstOrDefault()?.ReplaceBody == true)
            {
                // this is a replace body
                return(SyntaxFactory.LocalDeclarationStatement(
                           SyntaxFactory.VariableDeclaration(
                               SyntaxFactory.IdentifierName("var"))
                           .WithVariables(
                               SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>(
                                   SyntaxFactory.VariableDeclarator(
                                       SyntaxFactory.Identifier(Name))
                                   .WithInitializer(
                                       SyntaxFactory.EqualsValueClause(
                                           SyntaxFactory.IdentifierName(BodyParams.FirstOrDefault()?.Key)))))));
            }

            ExpressionSyntax objectCreation;

            if (BodyType == "Annonymous")
            {
                var anonPropList = new List <SyntaxNodeOrToken>();

                BodyParams.Select(b =>
                {
                    return(b.CallContext != null ?
                           SyntaxFactory.AnonymousObjectMemberDeclarator(
                               SyntaxFactory.MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   SyntaxFactory.IdentifierName(b.CallContext),
                                   SyntaxFactory.IdentifierName(b.Key)))
                           .WithNameEquals(
                               SyntaxFactory.NameEquals(
                                   SyntaxFactory.IdentifierName(b.FieldName)))
                    :
                           SyntaxFactory.AnonymousObjectMemberDeclarator(
                               SyntaxFactory.IdentifierName(b.Key))
                           .WithNameEquals(
                               SyntaxFactory.NameEquals(
                                   SyntaxFactory.IdentifierName(b.Key))));
                })
                .ToList()
                .ForEach(b =>
                {
                    anonPropList.Add(b);
                    anonPropList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                });

                objectCreation = SyntaxFactory.AnonymousObjectCreationExpression(
                    SyntaxFactory.SeparatedList <AnonymousObjectMemberDeclaratorSyntax>(
                        anonPropList.ToArray()
                        ));
            }
            else
            {
                var propList = new List <SyntaxNodeOrToken>();

                BodyParams.Select(b =>
                {
                    return(b.CallContext != null ?
                           SyntaxFactory.AssignmentExpression(
                               SyntaxKind.SimpleAssignmentExpression,
                               SyntaxFactory.IdentifierName(b.Key),
                               SyntaxFactory.MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   SyntaxFactory.IdentifierName(b.CallContext),
                                   SyntaxFactory.IdentifierName(b.Key)
                                   ))
                    :
                           SyntaxFactory.AssignmentExpression(
                               SyntaxKind.SimpleAssignmentExpression,
                               SyntaxFactory.IdentifierName(b.Key),
                               SyntaxFactory.IdentifierName(b.Key)));
                })
                .ToList()
                .ForEach(b =>
                {
                    propList.Add(b);
                    propList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                });

                objectCreation = SyntaxFactory.ObjectCreationExpression(
                    SyntaxFactory.IdentifierName(BodyType))
                                 .WithInitializer(
                    SyntaxFactory.InitializerExpression(
                        SyntaxKind.ObjectInitializerExpression,
                        SyntaxFactory.SeparatedList <ExpressionSyntax>(
                            propList.ToArray()
                            )));
            }

            return(SyntaxFactory.LocalDeclarationStatement(
                       SyntaxFactory.VariableDeclaration(
                           SyntaxFactory.IdentifierName("var"))
                       .WithVariables(
                           SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>(
                               SyntaxFactory.VariableDeclarator(
                                   SyntaxFactory.Identifier(Name))
                               .WithInitializer(
                                   SyntaxFactory.EqualsValueClause(
                                       objectCreation
                                       ))))));
        }
Esempio n. 10
0
        /// <summary>
        /// Creates an argument that creates a lambda expression for extracting the key from a class.
        /// </summary>
        /// <param name="uniqueKeyElement">The unique key element.</param>
        /// <param name="isAnonymous">Indicates we should create an anonymous key for Entity Framework.</param>
        /// <returns>An argument that extracts a key from an object.</returns>
        public static ExpressionSyntax GetUniqueKey(UniqueElement uniqueKeyElement, bool isAnonymous = false)
        {
            // Used as a variable when constructing the lambda expression.
            string abbreviation = uniqueKeyElement.Table.Name[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant();

            // This will create an expression for extracting the key from record.
            CSharpSyntaxNode syntaxNode = null;

            if (uniqueKeyElement.Columns.Count == 1)
            {
                // A simple key can be used like a value type.
                syntaxNode = SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    SyntaxFactory.IdentifierName(abbreviation),
                    SyntaxFactory.IdentifierName(uniqueKeyElement.Columns[0].Column.Name));
            }
            else
            {
                // A Compound key must be constructed from an anomymous type.
                List <SyntaxNodeOrToken> keyElements = new List <SyntaxNodeOrToken>();
                foreach (ColumnReferenceElement columnReferenceElement in uniqueKeyElement.Columns)
                {
                    if (keyElements.Count != 0)
                    {
                        keyElements.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                    }

                    if (isAnonymous)
                    {
                        keyElements.Add(
                            SyntaxFactory.AnonymousObjectMemberDeclarator(
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(abbreviation),
                                    SyntaxFactory.IdentifierName(columnReferenceElement.Column.Name))));
                    }
                    else
                    {
                        keyElements.Add(
                            SyntaxFactory.Argument(
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(abbreviation),
                                    SyntaxFactory.IdentifierName(columnReferenceElement.Column.Name))));
                    }
                }

                if (isAnonymous)
                {
                    // b => b.BuyerId or b => new { b.BuyerId, b.ExternalId0 }
                    syntaxNode = SyntaxFactory.AnonymousObjectCreationExpression(
                        SyntaxFactory.SeparatedList <AnonymousObjectMemberDeclaratorSyntax>(keyElements.ToArray()));
                }
                else
                {
                    // b => b.BuyerId or p => ValueTuple.Create(p.Name, p.CountryCode)
                    syntaxNode = SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName("ValueTuple"),
                            SyntaxFactory.IdentifierName("Create")))
                                 .WithArgumentList(
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SeparatedList <ArgumentSyntax>(keyElements.ToArray())));
                }
            }

            //            this.BuyerKey = new UniqueIndex("BuyerKey").HasIndex(b => b.BuyerId);
            return(SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(SyntaxFactory.Identifier(abbreviation)), syntaxNode));
        }