private ObjectCreationExpressionSyntax BuildObjectCreationExpression
 (
     AnonymousObjectCreationExpressionSyntax anonymousObject,
     GeneratedPropertyInfo[] propertySources,
     string className
 )
 => ObjectCreationExpression(ParseTypeName(className))
 .WithInitializer
 (
     InitializerExpression(SyntaxKind.ObjectInitializerExpression)
     .WithExpressions
     (
         new SeparatedSyntaxList <ExpressionSyntax>()
         .AddRange
         (
             anonymousObject
             .Initializers
             .Zip
             (
                 propertySources,
                 (anonymousInitializer, propertySource) => AssignmentExpression
                 (
                     SyntaxKind.SimpleAssignmentExpression,
                     IdentifierName(propertySource.Name),
                     anonymousInitializer.Expression
                 )
             )
         )
     )
 );
        static async Task <Document> AddMissingProperties(Document document,
                                                          AnonymousObjectCreationExpressionSyntax anonymousObject, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (anonymousObject.Parent is ArgumentSyntax argumentSyntax &&
                argumentSyntax.IsActivator(semanticModel, out var typeArgument) &&
                typeArgument.HasMessageContract(out var contractType))
            {
                var dictionary = new Dictionary <AnonymousObjectCreationExpressionSyntax, ITypeSymbol>();

                await FindAnonymousTypesWithMessageContractsInTree(dictionary, anonymousObject, contractType, semanticModel).ConfigureAwait(false);

                var newRoot = AddMissingProperties(root, dictionary);

                var formattedRoot = Formatter.Format(newRoot, Formatter.Annotation, document.Project.Solution.Workspace,
                                                     document.Project.Solution.Workspace.Options);

                return(document.WithSyntaxRoot(formattedRoot));
            }

            return(document);
        }
        public static IReadOnlyCollection <MyType> Parse(string[] parentFieldNames, AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax)
        {
            var allTypes   = new List <MyType>();
            var properties = new List <MyProperty>();

            foreach (var initializer in anonymousObjectCreationExpressionSyntax.Initializers)
            {
                var name = initializer.NameEquals.Name.Identifier.Text;

                if (initializer.Expression is AnonymousObjectCreationExpressionSyntax subDir)
                {
                    var subDirTypes =
                        AnonymousObjectCreationParser.Parse(parentFieldNames.Concat(new[] { name }).ToArray(), subDir);
                    allTypes.AddRange(subDirTypes);

                    var classObj  = subDirTypes.Last() ?? throw new InvalidOperationException();
                    var className = classObj.Name;
                    var props     = string.Join(",", classObj.Properties.Select(_ => _.Expression));

                    var property = new MyProperty(
                        name,
                        className,
                        $"new {className}({props})");
                    properties.Add(property);
                }
                else if (initializer.Expression is InvocationExpressionSyntax invocationExpression)
                {
                    var methodName = invocationExpression.Expression.ToString();
                    if (methodName.EndsWith("Files.FolderFunctions"))
                    {
                        var property = new MyProperty(name, "FolderFunctions", string.Join(".", parentFieldNames) + $".{name}.Clone()");
                        properties.Add(property);
                    }
                    else
                    {
                        var property = new MyProperty(name, "IPhysicalFile",
                                                      string.Join(".", parentFieldNames) + $".{name}.Clone()");
                        properties.Add(property);
                    }
                }
                else
                {
                    var property = new MyProperty(name, "IPhysicalFile",
                                                  string.Join(".", parentFieldNames) + $".{name}.Clone()");
                    properties.Add(property);
                }
            }

            var newClassName = parentFieldNames.Last() + "Type";
            var counter      = 2;

            while (allTypes.Any(_ => _.Name == newClassName))
            {
                newClassName = parentFieldNames.Last() + $"Type{counter}";
                counter++;
            }

            allTypes.Add(new MyType(newClassName, properties));
            return(allTypes);
        }
Ejemplo n.º 4
0
        public static HashSet <CompiledIndexField> ExtractFields(AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax, bool retrieveOriginal = false, bool nestFields = false)
        {
            var fields = new HashSet <CompiledIndexField>();

            for (var i = 0; i < anonymousObjectCreationExpressionSyntax.Initializers.Count; i++)
            {
                var    initializer = anonymousObjectCreationExpressionSyntax.Initializers[i];
                string name;
                if (initializer.NameEquals != null && retrieveOriginal == false)
                {
                    name = initializer.NameEquals.Name.Identifier.Text;
                }
                else
                {
                    if (initializer.Expression is MemberAccessExpressionSyntax memberAccessExpressionSyntax)
                    {
                        fields.Add(ExtractField(memberAccessExpressionSyntax, nestFields));
                        continue;
                    }

                    var identifierNameSyntax = initializer.Expression as IdentifierNameSyntax;

                    if (identifierNameSyntax == null)
                    {
                        throw new NotSupportedException($"Cannot extract field name from: {initializer}");
                    }

                    name = identifierNameSyntax.Identifier.Text;
                }

                fields.Add(new SimpleField(name));
            }

            return(fields);
        }
Ejemplo n.º 5
0
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var jsBlock = new JsBlockStatement();

            var model = Context.Instance.Compilation.GetSemanticModel(node.SyntaxTree);
            var classType = (INamedTypeSymbol)ModelExtensions.GetDeclaredSymbol(model, node);
            if (processedTypes.Contains(classType))
                return;
            processedTypes.Add(classType);

            JsBlockStatement typeInitializer;
            JsBlockStatement staticInitializer;
            jsBlock.Aggregate(idioms.CreateTypeFunction(classType, out typeInitializer, out staticInitializer));
            
            // Create default constructor
            var constructorBlock = new JsBlockStatement();
            constructorBlock.Express(idioms.InvokeMethodAsThis(classType.BaseType.InstanceConstructors.Single(x => x.Parameters.Count() == 0)));
            var constructor = classType.InstanceConstructors.Single();

            typeInitializer.Add(idioms.StoreInPrototype(constructor.GetMemberName(), Js.Reference(SpecialNames.DefineConstructor).Invoke(
                Js.Reference(SpecialNames.TypeInitializerTypeFunction), 
                Js.Function().Body(constructorBlock))));
            
            foreach (var property in classType.GetMembers().OfType<IPropertySymbol>())
            {
                typeInitializer.Aggregate(CreateProperty(property));
            }

            Action action = () =>
            {
                body.Aggregate(jsBlock);
            };
            actions.Add(Tuple.Create(classType, action));
        }
Ejemplo n.º 6
0
        public static HashSet <string> ExtractFields(AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax)
        {
            var fields = new HashSet <string>();

            for (var i = 0; i < anonymousObjectCreationExpressionSyntax.Initializers.Count; i++)
            {
                var    initializer = anonymousObjectCreationExpressionSyntax.Initializers[i];
                string name;
                if (initializer.NameEquals != null)
                {
                    name = initializer.NameEquals.Name.Identifier.Text;
                }
                else
                {
                    var memberAccess = initializer.Expression as MemberAccessExpressionSyntax;
                    if (memberAccess == null)
                    {
                        throw new NotSupportedException($"Cannot extract field name from: {initializer}");
                    }

                    name = memberAccess.Name.Identifier.Text;
                }

                fields.Add(name);
            }

            return(fields);
        }
        static SyntaxNode AddMissingProperties(SyntaxNode root, AnonymousObjectCreationExpressionSyntax anonymousObject, ITypeSymbol contractType)
        {
            var newRoot = root;

            List <IPropertySymbol> contractProperties = contractType.GetContractProperties();

            var propertiesToAdd = new List <AnonymousObjectMemberDeclaratorSyntax>();

            foreach (var messageContractProperty in contractProperties)
            {
                var initializer = anonymousObject.Initializers.FirstOrDefault(i => GetName(i) == messageContractProperty.Name);
                if (initializer == null)
                {
                    var path          = Enumerable.Empty <ITypeSymbol>();
                    var propertyToAdd = CreateProperty(messageContractProperty, path);
                    propertiesToAdd.Add(propertyToAdd);
                }
            }

            if (propertiesToAdd.Any())
            {
                var newAnonymousObject = anonymousObject
                                         .AddInitializers(propertiesToAdd.ToArray())
                                         .WithAdditionalAnnotations(Formatter.Annotation);
                newRoot = newRoot.ReplaceNode(anonymousObject, newAnonymousObject);
            }

            return(newRoot);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// var a = new A
        /// {
        ///     b = 2,
        ///     c = 3,
        /// }
        ///
        /// var a = new A();
        /// a.b = 2;
        /// a.c = 3;
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override Ust VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var typeToken = new TypeToken("Anonymous", node.OpenBraceToken.GetTextSpan());

            Expression[] args = node.Initializers.Select(init =>
            {
                try
                {
                    var left = init.NameEquals == null ? null :
                               new MemberReferenceExpression(typeToken,
                                                             ConvertId(init.NameEquals.Name.Identifier), init.NameEquals.Name.GetTextSpan());
                    var right = (Expression)base.Visit(init.Expression);

                    var assignment = new AssignmentExpression(left, right, init.GetTextSpan());
                    return(assignment);
                }
                catch (Exception ex) when(!(ex is ThreadAbortException))
                {
                    Logger.LogError(new ConversionException(root?.SourceCodeFile, message: ex.Message));
                    return(null);
                }
            }).ToArray();
            var argsNode = new ArgsUst(args, node.GetTextSpan());

            var result = new ObjectCreateExpression(typeToken, argsNode, node.GetTextSpan());

            return(result);
        }
        private async Task <Document> ConvertAsync(Document document, AnonymousObjectCreationExpressionSyntax anonymousObject, CancellationToken ct)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(ct).ConfigureAwait(false);

            GeneratedPropertyInfo[] propertySources =
                anonymousObject
                .Initializers
                .Select((initializer, index) => CreatePropertyInfo(initializer, index, semanticModel))
                .ToArray();

            ClassDeclarationSyntax         nestedClassDeclaration   = BuildClass(propertySources);
            ObjectCreationExpressionSyntax objectCreationExpression = BuildObjectCreationExpression(anonymousObject, propertySources, nestedClassDeclaration.Identifier.Text);

            TypeDeclarationSyntax declaringType = anonymousObject.Ancestors().OfType <TypeDeclarationSyntax>().FirstOrDefault();
            SyntaxNode            newRoot       = root
                                                  .ReplaceNodes
                                                  (
                new SyntaxNode[] { anonymousObject, declaringType },
                (original, rewritten) => rewritten == anonymousObject ? objectCreationExpression : InsertNestedClass(rewritten, nestedClassDeclaration)
                                                  );

            return(document.WithSyntaxRoot(newRoot));
        }
    /// <inheritdoc/>
    public override SyntaxNode?VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
    {
        var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node) !;

        Diagnostics.Add(AnonymousObjectCreationExpression, node);

        return(updatedNode);
    }
Ejemplo n.º 11
0
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            foreach (AnonymousObjectMemberDeclaratorSyntax initializer in node.Initializers)
            {
                initializer.Accept(this);
            }

            base.VisitAnonymousObjectCreationExpression(node);
        }
        static async Task FindAnonymousTypesWithMessageContractsInTree(IDictionary <AnonymousObjectCreationExpressionSyntax, ITypeSymbol> dictionary,
                                                                       AnonymousObjectCreationExpressionSyntax anonymousObject, ITypeSymbol contractType, SemanticModel semanticModel)
        {
            List <IPropertySymbol> contractProperties = contractType.GetContractProperties();

            foreach (var initializer in anonymousObject.Initializers)
            {
                var name = GetName(initializer);

                var contractProperty = contractProperties.FirstOrDefault(p => p.Name == name);

                if (contractProperty != null)
                {
                    if (initializer.Expression is ImplicitArrayCreationExpressionSyntax implicitArrayCreationExpressionSyntax)
                    {
                        if (contractProperty.Type.IsImmutableArray(out var contractElementType) ||
                            contractProperty.Type.IsList(out contractElementType) ||
                            contractProperty.Type.IsArray(out contractElementType))
                        {
                            SeparatedSyntaxList <ExpressionSyntax> expressions = implicitArrayCreationExpressionSyntax.Initializer.Expressions;
                            foreach (var expression in expressions)
                            {
                                if (expression is AnonymousObjectCreationExpressionSyntax anonymousObjectArrayInitializer)
                                {
                                    await FindAnonymousTypesWithMessageContractsInTree(dictionary, anonymousObjectArrayInitializer,
                                                                                       contractElementType, semanticModel).ConfigureAwait(false);
                                }
                            }
                        }
                    }
                    else if (initializer.Expression is AnonymousObjectCreationExpressionSyntax anonymousObjectProperty)
                    {
                        await FindAnonymousTypesWithMessageContractsInTree(dictionary, anonymousObjectProperty, contractProperty.Type, semanticModel)
                        .ConfigureAwait(false);
                    }
                    else if (initializer.Expression is InvocationExpressionSyntax invocationExpressionSyntax &&
                             semanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol method &&
                             method.ReturnType.IsList(out var methodReturnTypeArgument) &&
                             methodReturnTypeArgument.IsAnonymousType)
                    {
                        if (contractProperty.Type.IsImmutableArray(out var contractElementType) ||
                            contractProperty.Type.IsList(out contractElementType) ||
                            contractProperty.Type.IsArray(out contractElementType))
                        {
                            var syntax = await methodReturnTypeArgument.DeclaringSyntaxReferences[0].GetSyntaxAsync().ConfigureAwait(false);
                            if (syntax is AnonymousObjectCreationExpressionSyntax anonymousObjectTypeArgument)
                            {
                                await FindAnonymousTypesWithMessageContractsInTree(dictionary, anonymousObjectTypeArgument, contractElementType,
                                                                                   semanticModel).ConfigureAwait(false);
                            }
                        }
                    }
                }
            }

            dictionary.Add(anonymousObject, contractType);
        }
Ejemplo n.º 13
0
        public override Evaluation VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            foreach (AnonymousObjectMemberDeclaratorSyntax initializer in node.Initializers)
            {
                initializer.Accept <Evaluation>(this);
            }

            return(base.VisitAnonymousObjectCreationExpression(node));
        }
Ejemplo n.º 14
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     Writer.WriteStartJsObject();
     foreach (var initializer in node.Initializers)
     {
         Visit(initializer);
     }
     Writer.WriteEndJsObject();
 }
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var generated = node.Ancestors().OfType<ClassDeclarationSyntax>().Any(a => a.Identifier.ValueText.StartsWith("__FTI"));

            if (generated) return base.VisitAnonymousObjectCreationExpression(node);

            var expType = Model.GetTypeInfo(node).Type;

            if (AnonTypeUsage.AreEquivalent(expType, Type, Comp))
            {
                var propAssignment =
                    node.Initializers.OfType<AnonymousObjectMemberDeclaratorSyntax>()
                    .Select(
                    w =>
                    {
                        // Handle the new { Blah = Foo + Bar } case
                        if (w.NameEquals != null)
                        {
                            return
                                Syntax.BinaryExpression(
                                    SyntaxKind.AssignExpression,
                                    w.NameEquals.Identifier,
                                    w.Expression
                                ).WithLeadingTrivia(w.GetLeadingTrivia()).WithTrailingTrivia(w.GetTrailingTrivia());
                        }

                        // Handle the new { Fizz } case
                        return
                            Syntax.BinaryExpression(
                                SyntaxKind.AssignExpression,
                                w.Expression,
                                w.Expression
                            ).WithLeadingTrivia(w.GetLeadingTrivia()).WithTrailingTrivia(w.GetTrailingTrivia());
                    })
                    .Cast<ExpressionSyntax>().ToList();

                var separators = new List<SyntaxToken>();
                for (var i = 0; i < node.Initializers.SeparatorCount; i++) separators.Add(Syntax.Token(node.Initializers.GetSeparator(i).Kind));

                var equiv =
                    Syntax.ObjectCreationExpression(
                        NewType.WithLeadingTrivia(Syntax.ParseLeadingTrivia(" ")),
                        Syntax.ArgumentList(),
                        Syntax.InitializerExpression(
                            SyntaxKind.ObjectInitializerExpression,
                            Syntax.SeparatedList(
                                propAssignment,
                                separators
                            )
                        )
                    );

                return equiv.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
            }

            return base.VisitAnonymousObjectCreationExpression(node);
        }
Ejemplo n.º 16
0
        // The visitor methods below are only for expressions within the
        // body of the current query. Their job is to count operators and
        // operands for Halstead metrics, and weighted or non-weighted
        // nodes for our own tree-based metrics. All other constructs
        // (such as type declarations, visibility modifiers, global
        // variables) are ignored.
        //
        // We also ignore AST nodes that represent duplicates and as such
        // would inflate the metrics. An example of this kind of node is
        // the call-time argument of a function. There is a separate
        // `ArgumentSyntax` class that represents expressions passed to
        // a function; however, this is redundant because the expressions
        // being passed will be visited anyway. Another example is the
        // `case` labels of a `switch` expression. They are not counted
        // separately because the contained pattern or literal will be
        // counted in any case.
        //
        // Nodes related to imperative looping and control flow (e.g.
        // `break`, `continue`, and `try...catch`) are also ignored.
        // They are not present in any of our queries anyway.

        public override void VisitAnonymousObjectCreationExpression(
            AnonymousObjectCreationExpressionSyntax node
            )
        {
            IncrementNodeCount(1); // no direct equivalent in SQL
            AddOperator("new");

            base.VisitAnonymousObjectCreationExpression(node);
        }
Ejemplo n.º 17
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);
            }
        }
Ejemplo n.º 18
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     if (compilation != null)
     {
         var type = compilation.GetSemanticModel(node.SyntaxTree).GetDeclaredSymbol(node);
         types.Add(type);
     }
     anonymousTypeDeclarations.Add(node);
     base.VisitAnonymousObjectCreationExpression(node);
 }
Ejemplo n.º 19
0
        /// <summary>
        ///     In this section it'll be create:
        ///     - HasMember edge
        ///     - logical::Class node
        ///     - logical::Method node(s) and HasMember edge to the logical::Class node
        ///     These edges add to the acutal method from
        /// </summary>
        /// <param name="node"></param>
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            MainDeclaration.Instance.RoslynWatch.Start( );
            var symbol = MainDeclaration.Instance.Model.GetSymbolInfo(node).Symbol;

            MainDeclaration.Instance.RoslynWatch.Stop( );
            var acb = new AnonimClassBuilder(symbol.ContainingType, ref _map, node);

            acb.Build( );
        }
Ejemplo n.º 20
0
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type     = Program.GetModel(syntax).GetTypeInfo(syntax).Type.As <INamedTypeSymbol>();
            var anonName = TypeName(type);

            using (var writer = new ScalaWriter("anonymoustypes", StripGeneric(anonName)))
            {
                var fields = type.GetMembers().OfType <IPropertySymbol>().OrderBy(o => o.Name).ToList();

                writer.WriteLine("package anonymoustypes;");
                WriteImports.Go(writer);

                writer.WriteIndent();
                writer.Write("class ");
                writer.Write(anonName);
                writer.Write("(");
                bool first = true;
                foreach (var field in fields)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(", ");
                    }

                    writer.Write("_");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(TypeProcessor.ConvertTypeWithColon(field.Type));
                }
                writer.Write(")\r\n");


                writer.WriteOpenBrace();



                foreach (var field in fields)
                {
                    writer.WriteIndent();
                    writer.Write("final var ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(TypeProcessor.ConvertTypeWithColon(field.Type));
                    writer.Write(" = _");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(";\r\n");
                }



                writer.WriteCloseBrace();
            }
        }
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            if (Fields != null)
            {
                return(node);
            }

            Fields = RewritersHelper.ExtractFields(node);

            return(node);
        }
Ejemplo n.º 22
0
 public static IReadOnlyList <string> GetMembers(
     AnonymousObjectCreationExpressionSyntax anonymousObject)
 {
     return(anonymousObject.Initializers.Select(
                declarator =>
                declarator.NameEquals?.Name.Identifier.Text
                ?? (declarator.Expression as IdentifierNameSyntax)?.Identifier.Text
                ?? (declarator.Expression as MemberAccessExpressionSyntax)?.Name.Identifier.Text)
            .Where(name => name != null)
            .ToList());
 }
Ejemplo n.º 23
0
        public override LuaSyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            LuaTableInitializerExpression table = new LuaTableInitializerExpression();

            foreach (var initializer in node.Initializers)
            {
                var item = (LuaKeyValueTableItemSyntax)initializer.Accept(this);
                table.Items.Add(item);
            }
            return(new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.AnonymousType, table));
        }
Ejemplo n.º 24
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     _properties.Last = _properties.Last;
     foreach (var m in node.Initializers)
     {
         var initializerVisitor = new GetMembersVisitor(this);
         initializerVisitor.Visit(m);
         AddProperties(initializerVisitor._properties);
     }
     _properties.Last = new PropertyDependence {
         PropertiesDependences = _properties.PropertiesDependences
     };
     _proceed = true;
 }
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            if (model.GetTypeInfo(node).Type.Equals(targetAnonymousType))
            {
                var newDeclarationText = node.ToString().Insert(3, " " + newTypeName);
                var newDeclaration = SyntaxFactory.ParseExpression(newDeclarationText);

                //Cannot use type inference here otherwise a cast from ObjectCreationExpressionSyntax to
                // AnonymousObjectCreationExpressionSyntax inside ReplaceNode will fail
                return node.ReplaceNode<SyntaxNode>(node, newDeclaration);
            }
            else
            {
                return base.VisitAnonymousObjectCreationExpression(node);
            }
        }
        public override IEnumerable <IModel> VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var model = Create <AnonymousObjectExpression>(node);

            foreach (var item in node.Initializers)
            {
                var assignment = Create <AssignmentExpression>(item);
                assignment.RightExpression = TransformToSingle <ExpressionModel>(item.Expression);
                assignment.LeftExpression  = assignment.Assignee =
                    TransformToSingle <IdentifierName>(item.NameEquals.Identifier);

                model.Assignments.Add(assignment);
            }

            yield return(model);
        }
Ejemplo n.º 27
0
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            if (sem.GetTypeInfo(node).Type is INamedTypeSymbol type && type.IsAnonymousType)
            {
                var typeName = ANONYMOUS_TYPE_NAME;

                return(ObjectCreationExpression(ParseTypeName(typeName).WithLeadingTrivia(Space))
                       .WithInitializer(InitializerExpression(
                                            kind: SyntaxKind.ObjectInitializerExpression,
                                            openBraceToken: node.OpenBraceToken,
                                            expressions: SeparatedList(node.Initializers.Select(MapInitialiser)),
                                            closeBraceToken: node.CloseBraceToken))
                       .WithTriviaFrom(node));
            }

            return(base.VisitAnonymousObjectCreationExpression(node));
        }
 public static Doc Print(AnonymousObjectCreationExpressionSyntax node)
 {
     return(Doc.Group(
                Token.PrintWithSuffix(node.NewKeyword, Doc.Line),
                Token.Print(node.OpenBraceToken),
                Doc.Indent(
                    Doc.Line,
                    SeparatedSyntaxList.Print(
                        node.Initializers,
                        AnonymousObjectMemberDeclarator.Print,
                        Doc.Line
                        )
                    ),
                Doc.Line,
                Token.Print(node.CloseBraceToken)
                ));
 }
Ejemplo n.º 29
0
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            CodeBuilder.Append("wrapdictionary{");
            int ct = node.Initializers.Count;

            for (int i = 0; i < ct; ++i)
            {
                var init = node.Initializers[i];
                CodeBuilder.Append(init.NameEquals.Name);
                CodeBuilder.AppendFormat(" {0} ", init.NameEquals.EqualsToken.Text);
                VisitToplevelExpression(init.Expression, string.Empty);
                if (i < ct - 1)
                {
                    CodeBuilder.Append(", ");
                }
            }
            CodeBuilder.Append("}");
        }
 private Doc PrintAnonymousObjectCreationExpressionSyntax(
     AnonymousObjectCreationExpressionSyntax node)
 {
     return(Group(
                this.PrintSyntaxToken(node.NewKeyword, Line),
                this.PrintSyntaxToken(node.OpenBraceToken),
                Indent(
                    Line,
                    this.PrintSeparatedSyntaxList(
                        node.Initializers,
                        this.PrintAnonymousObjectMemberDeclaratorSyntax,
                        Line
                        )
                    ),
                Line,
                this.PrintSyntaxToken(node.CloseBraceToken)
                ));
 }
        static async Task FindAnonymousTypesWithMessageContractsInTree(IDictionary <AnonymousObjectCreationExpressionSyntax, ITypeSymbol> dictionary,
                                                                       AnonymousObjectCreationExpressionSyntax anonymousObject, ITypeSymbol contractType, SemanticModel semanticModel)
        {
            List <IPropertySymbol> contractProperties = contractType.GetContractProperties();

            foreach (var initializer in anonymousObject.Initializers)
            {
                var name = GetName(initializer);

                var contractProperty = contractProperties.FirstOrDefault(p => p.Name == name);

                if (contractProperty != null)
                {
                    await FindAnonymousTypesWithMessageContractsInTree(dictionary, initializer, contractProperty, semanticModel).ConfigureAwait(false);
                }
            }

            dictionary.Add(anonymousObject, contractType);
        }
        public static void Go(OutputWriter writer, AnonymousObjectCreationExpressionSyntax expression)
        {
            writer.Write("new ");
            writer.Write(TypeName(expression));
            writer.Write("(");

            bool first = true;
            foreach (var field in expression.Initializers.OrderBy(o => o.Name()))
            {
                if (first)
                    first = false;
                else
                    writer.Write(", ");

                Core.Write(writer, field.Expression);
            }

            writer.Write(")");
        }
Ejemplo n.º 33
0
        private async Task <Document> ConvertAsync(Document document, AnonymousObjectCreationExpressionSyntax anonymousObjectCreation, CancellationToken cancellationToken)
        {
            // Create Tuple
            var te = SyntaxFactory.TupleExpression();

            // Add arguments to Tuple
            var arguments = anonymousObjectCreation.Initializers.Select(it => it.NameEquals == null
                    ? SyntaxFactory.Argument(it.Expression)
                    : SyntaxFactory.Argument(SyntaxFactory.NameColon(it.NameEquals.Name.ToString()), SyntaxFactory.Token(SyntaxKind.None), it.Expression));

            te = te.AddArguments(arguments.ToArray());

            // Replace old (AnonymousObject) with the new (Tuple)
            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken)
                          .ConfigureAwait(false);

            var newRoot = oldRoot.ReplaceNode(anonymousObjectCreation, te);

            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 34
0
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            // we only want the outer most value
            if (_queryProcessed && _outerMostRequired)
            {
                return(node);
            }

            _fieldNames.Clear();
            _selectExpressions.Clear();

            _queryProcessed = true;

            foreach (var initializer in node.Initializers)
            {
                CollectFieldNamesAndSelectsFromMemberDeclarator(initializer);
            }

            return(node);
        }
Ejemplo n.º 35
0
        public override SyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            _output.TrivialWrite('{');
            int count = 0;
            foreach (var member in node.Initializers)
            {
                string left = member.NameEquals.Name.Identifier.ValueText;

                _output.Write(node, "\"" + NamingConvention.LowerCase1stChar(left) + "\"");

                _output.TrivialWrite(": ");

                this.VisitExpression(member.Expression);
                count++;
                if (count != node.Initializers.Count)
                    _output.TrivialWrite(", ");
            }
            _output.TrivialWrite('}');
            return node;
        }
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var expType = Model.GetTypeInfo(node).Type;

            if (AreEquivalent(expType, Type, Comp))
            {
                ((List<AnonymousObjectCreationExpressionSyntax>)Results).Add(node);
            }

            base.VisitAnonymousObjectCreationExpression(node);
        }
Ejemplo n.º 37
0
 public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     CheckSyntaxNode(declaratorSyntax);
     var model = this.GetMemberModel(declaratorSyntax);
     return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken);
 }
Ejemplo n.º 38
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     base.VisitAnonymousObjectCreationExpression(node);
 }
Ejemplo n.º 39
0
 public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     CheckSyntaxNode(declaratorSyntax);
     var bound = this.GetLowerBoundNode(declaratorSyntax) as BoundAnonymousObjectCreationExpression;
     return (bound == null) ? null : bound.Type as NamedTypeSymbol;
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Given a syntax node of anonymous object creation expression, get the anonymous object type symbol.
 /// </summary>
 /// <param name="declaratorSyntax">The syntax node that declares an anonymous object.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The symbol that was declared.</returns>
 public abstract INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken));
        private static SyntaxNode RewriteAnonymousObjectInitializer(AnonymousObjectCreationExpressionSyntax initializer)
        {
            var existingItems = new List<AnonymousObjectMemberDeclaratorSyntax>(initializer.Initializers);
            var last = existingItems.Last();
            existingItems.Remove(last);
            existingItems.Add(last.WithoutTrailingTrivia());

            var existingSeparators = initializer.Initializers.GetSeparators();
            var newSeparators = new List<SyntaxToken>(existingSeparators);
            newSeparators.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(last.GetTrailingTrivia()));

            var newInitializerExpressions = SyntaxFactory.SeparatedList(
                existingItems,
                newSeparators);

            var fixedInitializer = initializer.WithInitializers(newInitializerExpressions);
            return fixedInitializer;
        }
Ejemplo n.º 42
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     this.OnNodeVisited(node);
     if (!this.traverseRootOnly) base.VisitAnonymousObjectCreationExpression(node);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     this.OnNodeVisited(node, this.type.IsInstanceOfType(node));
     base.VisitAnonymousObjectCreationExpression(node);
 }
        public static void WriteAnonymousType(AnonymousObjectCreationExpressionSyntax syntax)
        {
            var type = TypeProcessor.GetTypeInfo(syntax).Type.As<INamedTypeSymbol>();

            Context.Instance.Type = type;

            TypeProcessor.ClearUsedTypes();

            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");
            // + "." + TypeState.Instance.TypeName;
            Context.Instance.Namespace = mynamespace;
            var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));
            // Required as certain functions like boxing are in this namespace

            Context.Instance.UsingDeclarations =
                syntax.Parent.DescendantNodes().OfType<UsingDirectiveSyntax>().ToArray()
                    .Union(new[]
                {
                    myUsingDirective, SystemUsingDirective
                }).ToArray();

            //using (var writer = new CppWriter (TypeState.Instance.Namespace, )) {

            //Ty

            var anonName = TypeName(type);
            using (var writer = new OutputWriter(Context.Instance.Namespace, StripGeneric(anonName)))
            {
                var fields = type.GetMembers().OfType<IPropertySymbol>().OrderBy(o => o.Name).ToList();

//                writer.WriteLine("namespace anonymoustypes {");
                WriteStandardIncludes.Go(writer);

                writer.WriteIndent();
                writer.Write("class ");
                writer.Write(anonName);

                writer.OpenBrace();

                foreach (var field in fields)
                {
                    writer.WriteIndent();
                    writer.Write("public ");
                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(field.Name));
                    writer.Write(" = " + TypeProcessor.DefaultValue(field.Type));
                    writer.Write(";\r\n");
                }

                //Must Write a constructor here ...
                writer.Write("\r\nthis (");
                bool first = true;
                foreach (var field in fields)
                {
                    if (first)
                        first = false;
                    else
                        writer.Write(", ");

                    writer.Write(TypeProcessor.ConvertType(field.Type) + " ");
                    writer.Write("_" + WriteIdentifierName.TransformIdentifier(field.Name));
                }
                writer.Write(")\r\n");
                writer.OpenBrace();
                writer.Indent++;

                foreach (var field in fields)
                {
                    var fieldNAme = WriteIdentifierName.TransformIdentifier(field.Name);

                    writer.WriteLine(fieldNAme + " = _" + fieldNAme + ";");
                }
                writer.Indent--;

                writer.CloseBrace();

                writer.CloseBrace();
//                writer.Write("};");
//                writer.Write("}");
            }
        }
Ejemplo n.º 45
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     _properties.Last = _properties.Last;
     foreach (var m in node.Initializers)
     {
         var initializerVisitor = new GetMembersVisitor(this);
         initializerVisitor.Visit(m);
         AddProperties(initializerVisitor._properties);
     }
     _properties.Last = new PropertyDependence { PropertiesDependences = _properties.PropertiesDependences };
     _proceed = true;
 }
Ejemplo n.º 46
0
 public InvocationExpressionSyntax Object(AnonymousObjectCreationExpressionSyntax obj, bool compact = false)
 {
     var method = context.JsniType.GetMembers("object").OfType<IMethodSymbol>().Single();
     return method.Invoke(obj, compact ? Cs.True() : Cs.False());
 }
Ejemplo n.º 47
0
        public void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            ExpressionStart(node);

            if (_writer.Configuration.Other.AlignMultiLineConstructs.ArrayObjectCollectionInitializer)
                _writer.SetAlignmentBreak(true);

            _writer.WriteKeyword(PrinterKeyword.New);

            _writer.PushBraceFormatting(_writer.Configuration.BracesLayout.ArrayAndObjectInitializer, false);

            _writer.BeginBlock();

            var wrapStyle = _writer.Configuration.LineBreaksAndWrapping.LineWrapping.WrapObjectAndCollectionInitializers;

            for (int i = 0; i < node.Initializers.Count; i++)
            {
                _writer.WriteIndent();

                node.Initializers[i].Accept(this);

                if (i != node.Initializers.Count - 1)
                {
                    _writer.WriteSyntax(Syntax.Comma);

                    if (wrapStyle != Configuration.WrapStyle.SimpleWrap)
                        _writer.Break(wrapStyle == Configuration.WrapStyle.ChopAlways);

                    _writer.WriteSpace();
                }
                else
                {
                    _writer.WriteLine(true);
                }
            }

            _writer.EndBlock();

            _writer.PopBraceFormatting();

            if (_writer.Configuration.Other.AlignMultiLineConstructs.ArrayObjectCollectionInitializer)
                _writer.SetAlignmentBreak(false);

            ExpressionEnd(node);
        }
Ejemplo n.º 48
0
 public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (Logger.LogBlock(FunctionId.CSharp_SemanticModel_GetDeclaredSymbol, message: this.SyntaxTree.FilePath, cancellationToken: cancellationToken))
     {
         CheckSyntaxNode(declaratorSyntax);
         var model = this.GetMemberModel(declaratorSyntax);
         return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken);
     }
 }
Ejemplo n.º 49
0
 public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
 {
     if (compilation != null)
     {
         var type = compilation.GetSemanticModel(node.SyntaxTree).GetDeclaredSymbol(node);
         types.Add(type);                
     }
     anonymousTypeDeclarations.Add(node);
     base.VisitAnonymousObjectCreationExpression(node);
 }
Ejemplo n.º 50
0
        private BoundExpression BindAnonymousObjectCreation(AnonymousObjectCreationExpressionSyntax node, DiagnosticBag diagnostics)
        {
            //  prepare
            var initializers = node.Initializers;
            int fieldCount = initializers.Count;
            bool hasError = false;

            //  bind field initializers
            BoundExpression[] boundExpressions = new BoundExpression[fieldCount];
            AnonymousTypeField[] fields = new AnonymousTypeField[fieldCount];
            CSharpSyntaxNode[] fieldSyntaxNodes = new CSharpSyntaxNode[fieldCount];

            // WARNING: Note that SemanticModel.GetDeclaredSymbol for field initializer node relies on 
            //          the fact that the order of properties in anonymous type template corresponds 
            //          1-to-1 to the appropriate filed initializer syntax nodes; This means such 
            //          correspondence must be preserved all the time including erroneos scenarios

            // set of names already used
            HashSet<string> uniqueFieldNames = new HashSet<string>();

            for (int i = 0; i < fieldCount; i++)
            {
                AnonymousObjectMemberDeclaratorSyntax fieldInitializer = initializers[i];
                NameEqualsSyntax nameEquals = fieldInitializer.NameEquals;
                ExpressionSyntax expression = fieldInitializer.Expression;

                SyntaxToken nameToken = default(SyntaxToken);
                if (nameEquals != null)
                {
                    nameToken = nameEquals.Name.Identifier;
                }
                else
                {
                    nameToken = expression.ExtractAnonymousTypeMemberName();
                }

                hasError = hasError || expression.HasErrors;
                boundExpressions[i] = this.BindValue(expression, diagnostics, BindValueKind.RValue);

                //  check the name to be unique
                string fieldName = null;
                if (nameToken.Kind() == SyntaxKind.IdentifierToken)
                {
                    fieldName = nameToken.ValueText;
                    if (uniqueFieldNames.Contains(fieldName))
                    {
                        //  name duplication
                        Error(diagnostics, ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, fieldInitializer);
                        hasError = true;
                        fieldName = null;
                    }
                    else
                    {
                        uniqueFieldNames.Add(fieldName);
                    }
                }
                else
                {
                    // there is something wrong with field's name
                    hasError = true;
                }

                //  calculate the expression's type and report errors if needed
                TypeSymbol fieldType = GetAnonymousTypeFieldType(boundExpressions[i], fieldInitializer, diagnostics, ref hasError);

                // build anonymous type field descriptor
                fieldSyntaxNodes[i] = (nameToken.Kind() == SyntaxKind.IdentifierToken) ? (CSharpSyntaxNode)nameToken.Parent : fieldInitializer;
                fields[i] = new AnonymousTypeField(fieldName == null ? "$" + i.ToString() : fieldName, fieldSyntaxNodes[i].Location, fieldType);

                //  NOTE: ERR_InvalidAnonymousTypeMemberDeclarator (CS0746) would be generated by parser if needed
            }

            //  Create anonymous type 
            AnonymousTypeManager manager = this.Compilation.AnonymousTypeManager;
            AnonymousTypeDescriptor descriptor = new AnonymousTypeDescriptor(fields.AsImmutableOrNull(), node.NewKeyword.GetLocation());
            NamedTypeSymbol anonymousType = manager.ConstructAnonymousTypeSymbol(descriptor);

            // declarators - bound nodes created for providing semantic info 
            // on anonymous type fields having explicitly specified name
            ArrayBuilder<BoundAnonymousPropertyDeclaration> declarators =
                ArrayBuilder<BoundAnonymousPropertyDeclaration>.GetInstance();
            for (int i = 0; i < fieldCount; i++)
            {
                NameEqualsSyntax explicitName = initializers[i].NameEquals;
                if (explicitName != null)
                {
                    AnonymousTypeField field = fields[i];
                    if (field.Name != null)
                    {
                        //  get property symbol and create a bound property declaration node
                        foreach (var symbol in anonymousType.GetMembers(field.Name))
                        {
                            if (symbol.Kind == SymbolKind.Property)
                            {
                                declarators.Add(new BoundAnonymousPropertyDeclaration(fieldSyntaxNodes[i], (PropertySymbol)symbol, field.Type));
                                break;
                            }
                        }
                    }
                }
            }

            // check if anonymous object creation is allowed in this context
            if (!this.IsAnonymousTypesAllowed())
            {
                Error(diagnostics, ErrorCode.ERR_AnonymousTypeNotAvailable, node.NewKeyword);
                hasError = true;
            }

            //  Finally create a bound node
            return new BoundAnonymousObjectCreationExpression(
                node,
                anonymousType.InstanceConstructors[0],
                boundExpressions.AsImmutableOrNull(),
                declarators.ToImmutableAndFree(),
                anonymousType,
                hasError);
        }
 public static string TypeName(AnonymousObjectCreationExpressionSyntax expression)
 {
     return TypeName(TypeProcessor.GetTypeInfo(expression).Type.As<INamedTypeSymbol>());
 }