public static ExpressionSyntax ImplicitlyTyped(ITypeSymbol typeSymbol, SemanticModel model, HashSet <string> visitedTypes, IFrameworkSet frameworkSet) { if (typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.TypeArguments.Length > 0) { var targetType = namedTypeSymbol.TypeArguments[0]; if (visitedTypes.Contains(targetType.ToFullName())) { return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(targetType.ToTypeSyntax(frameworkSet.Context)))); } return(SyntaxFactory.ImplicitArrayCreationExpression( SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( new SyntaxNodeOrToken[] { AssignmentValueHelper.GetDefaultAssignmentValue(targetType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), SyntaxFactory.Token(SyntaxKind.CommaToken), AssignmentValueHelper.GetDefaultAssignmentValue(targetType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), SyntaxFactory.Token(SyntaxKind.CommaToken), AssignmentValueHelper.GetDefaultAssignmentValue(targetType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), })))); } return(AssignmentValueHelper.GetDefaultAssignmentValue(typeSymbol, model, frameworkSet)); }
protected override IEnumerable <StatementSyntax> GetInitialStatementsForMethodDefinitions() { Contract.ThrowIfFalse(IsExtractMethodOnExpression(CSharpSelectionResult)); ExpressionSyntax expression = null; // special case for array initializer var returnType = AnalyzerResult.ReturnType; var containingScope = CSharpSelectionResult.GetContainingScope(); if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax) { var typeSyntax = returnType.GenerateTypeSyntax(); expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax); } else { expression = containingScope as ExpressionSyntax; } if (AnalyzerResult.HasReturnType) { return(SpecializedCollections.SingletonEnumerable <StatementSyntax>( SyntaxFactory.ReturnStatement( WrapInCheckedExpressionIfNeeded(expression)))); } else { return(SpecializedCollections.SingletonEnumerable <StatementSyntax>( SyntaxFactory.ExpressionStatement( WrapInCheckedExpressionIfNeeded(expression)))); } }
public static IEnumerable <MemberDeclarationSyntax> GenerateGetColumns(SqModelMeta meta) { return(meta.Properties.First() .Column.Select(tableColumn => { var arrayItems = meta.Properties.Select(p => p.Column.First()) .Select(p => SyntaxFactory.IdentifierName("table").MemberAccess(p.ColumnName)); var arrayType = SyntaxFactory.ArrayType( SyntaxFactory.IdentifierName(nameof(TableColumn)), new SyntaxList <ArrayRankSpecifierSyntax>(new[] { SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenBracketToken), new SeparatedSyntaxList <ExpressionSyntax>(), SyntaxFactory.Token(SyntaxKind.CloseBracketToken)) })); var array = SyntaxFactory.ArrayCreationExpression( arrayType, SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, new SeparatedSyntaxList <ExpressionSyntax>().AddRange(arrayItems)) ); return SyntaxFactory .MethodDeclaration(arrayType, MethodNameGetColumns) .WithModifiers(Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword)) .AddParameterListParameters(FuncParameter("table", tableColumn.TableRef.TableTypeName)) .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement( array ))); })); }
public static ExpressionSyntax ImplicitlyTypedArray(ITypeSymbol typeSymbol, SemanticModel model, HashSet <string> visitedTypes, IFrameworkSet frameworkSet) { if (typeSymbol is IArrayTypeSymbol arrayTypeSymbol) { if (visitedTypes.Contains(arrayTypeSymbol.ElementType.ToFullName())) { return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(arrayTypeSymbol.ElementType.ToTypeSyntax(frameworkSet.Context)))); } return(SyntaxFactory.ImplicitArrayCreationExpression( SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( new SyntaxNodeOrToken[] { AssignmentValueHelper.GetDefaultAssignmentValue(arrayTypeSymbol.ElementType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), SyntaxFactory.Token(SyntaxKind.CommaToken), AssignmentValueHelper.GetDefaultAssignmentValue(arrayTypeSymbol.ElementType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), SyntaxFactory.Token(SyntaxKind.CommaToken), AssignmentValueHelper.GetDefaultAssignmentValue(arrayTypeSymbol.ElementType, model, new HashSet <string>(visitedTypes, StringComparer.OrdinalIgnoreCase), frameworkSet), })))); } var random = ValueGenerationStrategyFactory.Random; return(SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Array"), SyntaxFactory.IdentifierName("CreateInstance"))) .WithArgumentList( Generate.Arguments(SyntaxFactory.TypeOfExpression(SyntaxFactory.IdentifierName("int")), Generate.Literal(random.Next(int.MaxValue)), Generate.Literal(random.Next(int.MaxValue)), Generate.Literal(random.Next(int.MaxValue))))); }
public static async Task <Document> RefactorAsync( Document document, ImplicitArrayCreationExpressionSyntax implicitArrayCreation, CancellationToken cancellationToken = default) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(implicitArrayCreation, cancellationToken); var arrayType = (ArrayTypeSyntax)typeSymbol.ToTypeSyntax().WithSimplifierAnnotation(); SyntaxToken newKeyword = implicitArrayCreation.NewKeyword; if (!newKeyword.HasTrailingTrivia) { newKeyword = newKeyword.WithTrailingTrivia(SyntaxFactory.Space); } ArrayCreationExpressionSyntax newNode = SyntaxFactory.ArrayCreationExpression( newKeyword, arrayType .WithLeadingTrivia(implicitArrayCreation.OpenBracketToken.LeadingTrivia) .WithTrailingTrivia(implicitArrayCreation.CloseBracketToken.TrailingTrivia), implicitArrayCreation.Initializer); return(await document.ReplaceNodeAsync(implicitArrayCreation, newNode, cancellationToken).ConfigureAwait(false)); }
public static ArrayCreationExpressionSyntax CreateArrayOf(string typeName, ExpressionSyntax[] expressions, int ranksAmount = 1) { var newKeyword = SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.NewKeyword, SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))); var syntaxList = new SeparatedSyntaxList <ExpressionSyntax>(); for (var i = 0; i < expressions.Length; i++) { syntaxList = syntaxList.Add(expressions[i]); } var rankSpecifiers = new SyntaxList <ArrayRankSpecifierSyntax>(); for (var i = 0; i < ranksAmount; i++) { rankSpecifiers = rankSpecifiers.Add( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), new SeparatedSyntaxList <ExpressionSyntax> { SyntaxFactory.OmittedArraySizeExpression( SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken) ) }, SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ) ); } return(SyntaxFactory.ArrayCreationExpression( newKeyword, SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(typeName), rankSpecifiers), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, syntaxList))); }
private static ExpressionSyntax GetExpressionToInline(LocalDeclarationStatementSyntax localDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken) { VariableDeclarationSyntax variableDeclaration = localDeclaration.Declaration; ExpressionSyntax expression = variableDeclaration .Variables .First() .Initializer .Value; if (expression.IsKind(SyntaxKind.ArrayInitializerExpression)) { expression = SyntaxFactory.ArrayCreationExpression( (ArrayTypeSyntax)variableDeclaration.Type.WithoutTrivia(), (InitializerExpressionSyntax)expression); return(expression.WithFormatterAnnotation()); } else { expression = expression.Parenthesize(); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(variableDeclaration.Type, cancellationToken); if (typeSymbol.SupportsExplicitDeclaration()) { TypeSyntax type = typeSymbol.ToMinimalTypeSyntax(semanticModel, localDeclaration.SpanStart); expression = SyntaxFactory.CastExpression(type, expression).WithSimplifierAnnotation(); } return(expression); } }
private async Task <CSharpSyntaxNode> GetInitializerFromNameAndTypeAsync(ITypeSymbol typeSymbol, VBSyntax.ModifiedIdentifierSyntax name, CSharpSyntaxNode initializer) { if (!SyntaxTokenExtensions.IsKind(name.Nullable, SyntaxKind.None)) { if (typeSymbol.IsArrayType()) { initializer = null; } } var rankSpecifiers = await ConvertArrayRankSpecifierSyntaxesAsync(name.ArrayRankSpecifiers, name.ArrayBounds, false); if (rankSpecifiers.Count > 0) { var rankSpecifiersWithSizes = await ConvertArrayRankSpecifierSyntaxesAsync(name.ArrayRankSpecifiers, name.ArrayBounds); var arrayTypeSyntax = ((ArrayTypeSyntax)GetTypeSyntax(typeSymbol)).WithRankSpecifiers(rankSpecifiersWithSizes); if (rankSpecifiersWithSizes.SelectMany(ars => ars.Sizes).Any(e => !e.IsKind(CSSyntaxKind.OmittedArraySizeExpression))) { initializer = SyntaxFactory.ArrayCreationExpression(arrayTypeSyntax); } else if (initializer is CSSyntax.ImplicitArrayCreationExpressionSyntax iaces && iaces.Initializer != null) { initializer = SyntaxFactory.ArrayCreationExpression(arrayTypeSyntax, iaces.Initializer); } } return(initializer); }
public override SyntaxNode MakeSyntaxNode() { var res = SyntaxFactory.ArrayCreationExpression(NewKeyword, Type, Initializer); IsChanged = false; return(res); }
public override ExpressionSyntax Visit(ConversionContext context, ArrayCreationExpr expr) { var type = TypeHelper.ConvertTypeOf(expr); var rankDimensions = expr.getDimensions().ToList <Expression>(); var initializer = expr.getInitializer(); var rankSyntaxes = new List <ExpressionSyntax>(); if (rankDimensions != null) { rankSyntaxes.AddRange(rankDimensions.Select(dimension => VisitExpression(context, dimension))); } if (initializer == null) { return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.ParseTypeName(type))) .AddTypeRankSpecifiers(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SeparatedList(rankSyntaxes, Enumerable.Repeat(SyntaxFactory.Token(SyntaxKind.CommaToken), rankSyntaxes.Count - 1))))); } // todo: support multi-dimensional and jagged arrays var values = initializer.getValues().ToList <Expression>(); var syntaxes = values.Select(value => VisitExpression(context, value)).ToList(); var initSyntax = syntaxes.Any() ? SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(syntaxes, Enumerable.Repeat(SyntaxFactory.Token(SyntaxKind.CommaToken), syntaxes.Count - 1))) : SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression); return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.ParseTypeName(type)), initSyntax)); }
private static async Task <Document> ChangeToImmutableArrayCreateRange( ObjectCreationExpressionSyntax objectCreation, InitializerExpressionSyntax initializer, INamedTypeSymbol immutableArrayType, ITypeSymbol elementType, Document document, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var arrayElementType = (TypeSyntax)generator.TypeExpression(elementType); var arrayType = SyntaxFactory.ArrayType(arrayElementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList( (ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var arrayCreationExpression = SyntaxFactory.ArrayCreationExpression( type: arrayType, initializer: SyntaxFactory.InitializerExpression( kind: SyntaxKind.ArrayInitializerExpression, expressions: initializer.Expressions)) .WithAdditionalAnnotations(Formatter.Annotation); var type = generator.TypeExpression(immutableArrayType); var memberAccess = generator.MemberAccessExpression(type, "CreateRange"); var invocation = generator.InvocationExpression(memberAccess, arrayCreationExpression); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = oldRoot.ReplaceNode(objectCreation, invocation); return(document.WithSyntaxRoot(newRoot)); }
public static ExpressionSyntax Byte() { return(SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ByteKeyword))) .WithRankSpecifiers( SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression()))))) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( new SyntaxNodeOrToken[] { Generate.Literal((byte)ValueGenerationStrategyFactory.Random.Next(255)), SyntaxFactory.Token(SyntaxKind.CommaToken), Generate.Literal((byte)ValueGenerationStrategyFactory.Random.Next(255)), SyntaxFactory.Token(SyntaxKind.CommaToken), Generate.Literal((byte)ValueGenerationStrategyFactory.Random.Next(255)), SyntaxFactory.Token(SyntaxKind.CommaToken), Generate.Literal((byte)ValueGenerationStrategyFactory.Random.Next(255)), })))); }
public static ArrayCreationExpressionSyntax CreateArray(ArrayTypeSyntax arrayType, ValueBridge size) { var rankSpecifiers = arrayType.RankSpecifiers; var newRankSpecifiers = rankSpecifiers.Select((x, i) => i == 0 ? SyntaxFactory.ArrayRankSpecifier(SyntaxFactoryHelper.CreateSeparatedList((ExpressionSyntax)size)) : x); return(SyntaxFactory.ArrayCreationExpression( arrayType.WithRankSpecifiers(new SyntaxList <ArrayRankSpecifierSyntax>(newRankSpecifiers)))); }
internal override void CollectInputExpressions(List <StatementSyntax> expressions) { base.CollectInputExpressions(expressions); var entryType = MyVisualScriptingProxy.GetType(ObjectBuilder.Type); var listType = typeof(List <>).MakeGenericType(entryType); var separatedList = new List <SyntaxNodeOrToken>(); // Create source of arguments for array creation syntax for (var index = 0; index < ObjectBuilder.DefaultEntries.Count; index++) { var entry = ObjectBuilder.DefaultEntries[index]; var literal = MySyntaxFactory.Literal(ObjectBuilder.Type, entry); separatedList.Add(literal); if (index < ObjectBuilder.DefaultEntries.Count - 1) { separatedList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } } // Syntax of "new Type[]{arg0, arg1, ...}" ArrayCreationExpressionSyntax arrayCreationSyntax = null; if (separatedList.Count > 0) { arrayCreationSyntax = SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType( SyntaxFactory.IdentifierName(ObjectBuilder.Type), SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression() ) ) ) ), SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( separatedList ) ) ); } // Syntax of new List<Type>(arrayCreationSyntax); var listCreationSyntax = MySyntaxFactory.GenericObjectCreation(listType, arrayCreationSyntax == null ? null : new[] { arrayCreationSyntax }); var localVariableSyntax = MySyntaxFactory.LocalVariable(listType, VariableSyntaxName(), listCreationSyntax); expressions.Add(localVariableSyntax); }
private static ArrayCreationExpressionSyntax CreateArrayCreationExpression( ImplicitArrayCreationExpressionSyntax node, ArrayTypeSyntax arrayType) { return(SyntaxFactory.ArrayCreationExpression( node.NewKeyword, arrayType .WithSimplifierAnnotation() .WithTrailingTrivia(node.CloseBracketToken.TrailingTrivia), node.Initializer)); }
protected ExpressionSyntax GetCompiledBindingCreation(DefaultViewCompilerCodeEmitter emitter, string methodName, string updateMethodName, string originalString, ExpressionSyntax[] actionFilters, string javascript, string id) { var dict = new Dictionary <string, ExpressionSyntax>(); if (methodName != null) { dict.Add(nameof(CompiledBindingExpression.Delegate), SyntaxFactory.ParseName(methodName)); } if (updateMethodName != null) { dict.Add(nameof(CompiledBindingExpression.UpdateDelegate), SyntaxFactory.ParseName(updateMethodName)); } if (originalString != null) { dict.Add(nameof(CompiledBindingExpression.OriginalString), emitter.EmitValue(originalString)); } if (javascript != null) { dict.Add(nameof(CompiledBindingExpression.Javascript), emitter.EmitValue(javascript)); } if (id != null) { dict.Add(nameof(CompiledBindingExpression.Id), emitter.EmitValue(id)); } if (actionFilters != null) { dict.Add(nameof(CompiledBindingExpression.ActionFilters), SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType(SyntaxFactory.ParseTypeName(typeof(ActionFilterAttribute).FullName)) .WithRankSpecifiers( SyntaxFactory.SingletonList <ArrayRankSpecifierSyntax>( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression())))), SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList(actionFilters)))); } return(SyntaxFactory.ObjectCreationExpression( SyntaxFactory.ParseTypeName(typeof(CompiledBindingExpression).FullName), SyntaxFactory.ArgumentList(), SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression, SyntaxFactory.SeparatedList( dict.Select(p => (ExpressionSyntax)SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(p.Key), p.Value ) ) ) ) )); }
public override ExpressionSyntax Visit(ConversionContext context, ArrayCreationExpr expr) { var type = TypeHelper.ConvertType(expr.getType().toString()); var rankDimensions = expr.getDimensions().ToList <Expression>(); var initializer = expr.getInitializer(); var rankSyntaxes = new List <ExpressionSyntax>(); if (rankDimensions != null) { foreach (var dimension in rankDimensions) { var rankSyntax = ExpressionVisitor.VisitExpression(context, dimension); rankSyntaxes.Add(rankSyntax); } } var elementType = TypeHelper.GetTypeSyntax(type); if (initializer == null) { return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(elementType)) .AddTypeRankSpecifiers(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SeparatedList(rankSyntaxes, Enumerable.Repeat(SyntaxFactory.Token(SyntaxKind.CommaToken), rankSyntaxes.Count - 1))))); } // todo: support multi-dimensional and jagged arrays var values = initializer.getValues().ToList <Expression>(); //// empty array if (values.Count <= 0) { var rankSpecifiers = SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression()))); var initializerExpression = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression); var arrayCreationExpression = SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.ArrayType(elementType)) .WithRankSpecifiers(rankSpecifiers)) .WithInitializer(initializerExpression); return(arrayCreationExpression); } var syntaxes = new List <ExpressionSyntax>(); foreach (var value in values) { var syntax = ExpressionVisitor.VisitExpression(context, value); syntaxes.Add(syntax); } var initSyntax = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(syntaxes, Enumerable.Repeat(SyntaxFactory.Token(SyntaxKind.CommaToken), syntaxes.Count - 1))); return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(elementType), initSyntax)); }
public static ExpressionSyntax ArrayCreationExpression <T>([NotNull] this SyntaxGenerator syntax, [NotNull] SemanticModel semanticModel, [NotNull] IEnumerable <ExpressionSyntax> elements) { Requires.NotNull(syntax, nameof(syntax)); Requires.NotNull(semanticModel, nameof(semanticModel)); Requires.NotNull(elements, nameof(elements)); var elementList = SyntaxFactory.SeparatedList(elements); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, elementList); return(SyntaxFactory.ArrayCreationExpression(syntax.ArrayTypeExpression <T>(semanticModel), initializer)); }
private static MemberDeclarationSyntax[] GenerateMethods(IReadOnlyList <TableModel> tables, string tablePrefix) { var result = new List <MemberDeclarationSyntax>(tables.Count * 2 + 2); var identifierAliasType = SyntaxFactory.IdentifierName(nameof(Alias)); var arrayItems = tables.Select(t => SyntaxFactory.IdentifierName(GetMethodName(t, tablePrefix)).Invoke(identifierAliasType.MemberAccess(nameof(Alias.Empty)))); var arrayType = SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(nameof(TableBase)), new SyntaxList <ArrayRankSpecifierSyntax>(new[] { SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenBracketToken), new SeparatedSyntaxList <ExpressionSyntax>(), SyntaxFactory.Token(SyntaxKind.CloseBracketToken)) })); var array = SyntaxFactory.ArrayCreationExpression( arrayType, SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, new SeparatedSyntaxList <ExpressionSyntax>().AddRange(arrayItems)) ); result.Add( SyntaxFactory.MethodDeclaration(arrayType, "BuildAllTableList") .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword)) .WithExpressionBody(SyntaxFactory.ArrowExpressionClause( array )) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); foreach (var t in tables) { var aliasParamName = "alias"; result.Add(SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(t.Name), GetMethodName(t, tablePrefix)) .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword)) .AddParameterListParameters(SyntaxHelpers.FuncParameter(aliasParamName, nameof(Alias))) .WithExpressionBody(SyntaxFactory.ArrowExpressionClause( SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(t.Name), SyntaxHelpers.ArgumentList(SyntaxFactory.IdentifierName(aliasParamName)), null))) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); result.Add(SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(t.Name), GetMethodName(t, tablePrefix)) .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword)) .WithExpressionBody(SyntaxFactory.ArrowExpressionClause( SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(t.Name), SyntaxHelpers.ArgumentList(identifierAliasType.MemberAccess(nameof(Alias.Auto))), null))) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); } return(result.ToArray());
public ExpressionSyntax EmitCreateArray(Type arrayType, IEnumerable values) { return(SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType( ParseTypeName(arrayType), SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression())))), SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList( values.Cast <object>().Select(EmitValue))))); }
public static ExpressionSyntax ArrayCreation(string typeName, IEnumerable <ExpressionSyntax> expressions) { var initializer = SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, expressions.ToSeparatedList()); if (string.IsNullOrEmpty(typeName)) { return(SyntaxFactory.ImplicitArrayCreationExpression(initializer)); } return(SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType(SyntaxFactory.ParseTypeName(typeName), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())), initializer)); }
//OmittedArraySizeExpression case only: public static SyntaxNode MkCSharpArrayCreationExpression(string type, SyntaxNodeOrToken[] initializer) { return(SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(type)) .WithRankSpecifiers( SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression()))))) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(initializer)))); }
public override VisualBasicSyntaxNode VisitArrayCreationExpression(CSS.ArrayCreationExpressionSyntax node) { var upperBoundArguments = node.Type.RankSpecifiers.First()?.Sizes.Where(s => !(s is CSS.OmittedArraySizeExpressionSyntax)).Select( s => (ArgumentSyntax)SyntaxFactory.SimpleArgument(ReduceArrayUpperBoundExpression((ExpressionSyntax)s.Accept(this)))); var rankSpecifiers = node.Type.RankSpecifiers.Select(rs => (ArrayRankSpecifierSyntax)rs.Accept(this)); return(SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), SyntaxFactory.List <AttributeListSyntax>(), (TypeSyntax)node.Type.ElementType.Accept(this), upperBoundArguments.Any() ? SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(upperBoundArguments)) : null, upperBoundArguments.Any() ? SyntaxFactory.List(rankSpecifiers.Skip(1)) : SyntaxFactory.List(rankSpecifiers), (CollectionInitializerSyntax)node.Initializer?.Accept(this) )); }
protected virtual InterfaceDeclarationSyntax AddJsonConverter(InterfaceDeclarationSyntax target, OpenApiEnrichmentContext <OpenApiSchema> context) { OpenApiSchema schema = context.Element; var attribute = SyntaxFactory.Attribute(NewtonsoftJsonTypes.JsonConverterAttributeName).AddArgumentListArguments( SyntaxFactory.AttributeArgument( SyntaxFactory.TypeOfExpression(JsonSerializationNamespace.DiscriminatorConverter)), SyntaxFactory.AttributeArgument( SyntaxHelpers.StringLiteral(schema.Discriminator.PropertyName)), SyntaxFactory.AttributeArgument( SyntaxFactory.TypeOfExpression(Context.TypeGeneratorRegistry.Get(context.LocatedElement).TypeInfo.Name))); if (schema.Discriminator.Mapping != null) { var paramArray = SyntaxFactory.ArrayCreationExpression( SyntaxFactory .ArrayType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword))) .WithRankSpecifiers( SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression()))))) .WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( schema.Discriminator.Mapping .SelectMany(mapping => { // Add two parameters to the object array for each mapping // First is the string key of the mapping, second is the Type to deserialize OpenApiSchema referencedSchema = schema.OneOf .FirstOrDefault(p => p.Reference?.ReferenceV3 == mapping.Value); return(referencedSchema != null ? new ExpressionSyntax[] { SyntaxHelpers.StringLiteral(mapping.Key), SyntaxFactory.TypeOfExpression( Context.TypeGeneratorRegistry.Get( referencedSchema.CreateRoot(referencedSchema.Reference.Id)).TypeInfo.Name) } : Enumerable.Empty <ExpressionSyntax>()); })))); attribute = attribute.AddArgumentListArguments(SyntaxFactory.AttributeArgument(paramArray)); } return(target.AddAttributeLists(SyntaxFactory.AttributeList().AddAttributes(attribute))); }
public override SyntaxNode VisitElementAccessExpression(ElementAccessExpressionSyntax node) { bool isAssignment = node.Expression.IsMissing; bool isParam = node.Expression is InvocationExpressionSyntax; if (!isAssignment && !isParam) { return(node); } List <ExpressionSyntax> casting = new List <ExpressionSyntax>(); foreach (ArgumentSyntax arg in node.ArgumentList.Arguments) { casting.Add(arg.Expression); } ArrayCreationExpressionSyntax array = SyntaxFactory.ArrayCreationExpression( SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName("object[]")), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(casting))); if (isAssignment) { return(ctx_.AddLinker(array, linkArray)); } else if (isParam) { //first parameter is an array var invocation = (InvocationExpressionSyntax)node.Expression; var newInvocation = SyntaxFactory.InvocationExpression(invocation.Expression); var result = ctx_.AddLinker(newInvocation, (ctx, linkNode, newNode, model) => { var args = (ArgumentListSyntax)ctx.GetLinkData(linkNode); var inv = (InvocationExpressionSyntax)newNode; return(inv.WithArgumentList(args)); }); Debug.Assert(pending_ == null); pending_ = new ResolveArrayArgument(ctx_, result, array); return(result); } return(node); }
public static async Task <Document> RefactorAsync( Document document, ImplicitArrayCreationExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); var arrayType = CSharpFactory.Type(typeSymbol, semanticModel, expression.SpanStart) as ArrayTypeSyntax; ArrayCreationExpressionSyntax newNode = SyntaxFactory.ArrayCreationExpression( expression.NewKeyword, arrayType.WithTrailingTrivia(expression.CloseBracketToken.TrailingTrivia), expression.Initializer); newNode = newNode.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(expression, newNode, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Gets the parameter type array that can be used to retrieve the <paramref name="methodSymbol" /> via reflection. /// </summary> private SyntaxNode GetParameterTypeArray(IMethodSymbol methodSymbol) { var typeExpressions = methodSymbol.Parameters.Select(p => { var typeofExpression = SyntaxFactory.TypeOfExpression(Syntax.GlobalTypeExpression(p.Type)); if (p.RefKind == RefKind.None) { return(typeofExpression); } var makeRefType = Syntax.MemberAccessExpression(typeofExpression, "MakeByRefType"); return((ExpressionSyntax)Syntax.InvocationExpression(makeRefType)); }); var arguments = SyntaxFactory.SeparatedList(typeExpressions); var initialize = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, arguments); var arrayType = Syntax.ArrayTypeExpression(Syntax.TypeExpression <Type>(SemanticModel)); return(SyntaxFactory.ArrayCreationExpression((ArrayTypeSyntax)arrayType, initialize)); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is EmptyStatementSyntax) { var arguments = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(args_)); ctx_.AddLinkData(node_, arguments); action = LookAheadAction.SUCCEDED; return(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); } if (node is VariableDeclaratorSyntax) { //found another array var vard = (VariableDeclaratorSyntax)node; if (vard.ArgumentList != null) { var values = vard.ArgumentList.Arguments.Select <ArgumentSyntax, ExpressionSyntax>(arg => arg.Expression); var array = SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName("object[]")), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(values))); //td: link args_.Add(SyntaxFactory.Argument(array)); } action = LookAheadAction.CONTINUE; return(null); } if (node is ExpressionStatementSyntax) { var expr = (ExpressionStatementSyntax)transform.Visit(node); args_.Add(SyntaxFactory.Argument(expr.Expression)); action = LookAheadAction.CONTINUE; return(null); } action = LookAheadAction.FAILED; return(node); }
private static ArrayCreationExpressionSyntax GetArrayCreationExpression(IEnumerable <string> items) { return(SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword))) .WithRankSpecifiers( SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>( SyntaxFactory.OmittedArraySizeExpression() .WithOmittedArraySizeExpressionToken( SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)))) .WithOpenBracketToken(SyntaxFactory.Token(SyntaxKind.OpenBracketToken)) .WithCloseBracketToken(SyntaxFactory.Token(SyntaxKind.CloseBracketToken))))) .WithNewKeyword(SyntaxFactory.Token(SyntaxKind.NewKeyword)) .WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(items.Select( x => SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(x))))) .WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)))); }
/// <summary> /// Returns <see cref="ArrayCreationExpressionSyntax"/> representing the array creation form of <paramref name="arrayType"/>. /// </summary> /// <param name="separatedSyntaxList"> /// Args used in initialization. /// </param> /// <param name="arrayType"> /// The array type. /// </param> /// <returns> /// <see cref="ArrayCreationExpressionSyntax"/> representing the array creation form of <paramref name="arrayType"/>. /// </returns> public static ArrayCreationExpressionSyntax GetArrayCreationWithInitializerSyntax(this SeparatedSyntaxList <ExpressionSyntax> separatedSyntaxList, TypeSyntax arrayType) { var arrayRankSizes = new SeparatedSyntaxList <ExpressionSyntax>().Add(SyntaxFactory.OmittedArraySizeExpression( SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken))); var arrayRankSpecifier = SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), arrayRankSizes, SyntaxFactory.Token(SyntaxKind.CloseBracketToken)); var arrayRankSpecifierSyntaxList = new SyntaxList <ArrayRankSpecifierSyntax>().Add(arrayRankSpecifier); var arrayCreationExpressionSyntax = SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), SyntaxFactory.ArrayType(arrayType, arrayRankSpecifierSyntaxList), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.Token(SyntaxKind.OpenBraceToken), separatedSyntaxList, SyntaxFactory.Token(SyntaxKind.CloseBraceToken))); return(arrayCreationExpressionSyntax); }