private static LocalFunctionStatementSyntax CreateLocalFunctionStatement(
            LocalDeclarationStatementSyntax localDeclaration,
            AnonymousFunctionExpressionSyntax anonymousFunction,
            IMethodSymbol delegateMethod,
            ParameterListSyntax parameterList)
        {
            var modifiers = anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)
                ? new SyntaxTokenList(anonymousFunction.AsyncKeyword)
                : default;

            var returnType = delegateMethod.GenerateReturnTypeSyntax();

            var identifier        = localDeclaration.Declaration.Variables[0].Identifier;
            var typeParameterList = default(TypeParameterListSyntax);

            var constraintClauses = default(SyntaxList <TypeParameterConstraintClauseSyntax>);

            var body = anonymousFunction.Body.IsKind(SyntaxKind.Block)
                ? (BlockSyntax)anonymousFunction.Body
                : null;

            var expressionBody = anonymousFunction.Body is ExpressionSyntax expression
                ? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression)
                : null;

            var semicolonToken = anonymousFunction.Body is ExpressionSyntax
                ? localDeclaration.SemicolonToken
                : default;

            return(SyntaxFactory.LocalFunctionStatement(
                       modifiers, returnType, identifier, typeParameterList, parameterList,
                       constraintClauses, body, expressionBody, semicolonToken));
        }
예제 #2
0
        static void HandlePropertyCase(CodeRefactoringContext context, SyntaxNode root, SyntaxToken token, PropertyDeclarationSyntax property)
        {
            var getter = property.AccessorList.Accessors.FirstOrDefault(acc => acc.IsKind(SyntaxKind.GetAccessorDeclaration));
            ExpressionSyntax expr;

            if (getter == null || property.AccessorList.Accessors.Count != 1 || !IsSimpleReturn(getter.Body, out expr))
            {
                return;
            }
            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    token.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("To expression body"),
                    t2 =>
            {
                var newRoot = root.ReplaceNode((SyntaxNode)
                                               property,
                                               property
                                               .WithAccessorList(null)
                                               .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(expr))
                                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                                               .WithTrailingTrivia(expr.Parent.GetTrailingTrivia())
                                               .WithAdditionalAnnotations(Formatter.Annotation)
                                               );
                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }
                    )
                );
        }
예제 #3
0
 private static MethodDeclarationSyntax CreateTypeRequestWithMessageAllowNull(
     string className,
     HttpStatusCode httpStatusCode,
     string typeRequestName,
     string parameterName = "message")
 {
     return(SyntaxFactory.MethodDeclaration(
                SyntaxFactory.IdentifierName(className),
                SyntaxFactory.Identifier(httpStatusCode.ToNormalizedString()))
            .WithModifiers(SyntaxTokenListFactory.PublicStaticKeyword())
            .WithParameterList(
                SyntaxFactory.ParameterList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Parameter(SyntaxFactory.Identifier(parameterName))
                        .WithType(SyntaxFactory.NullableType(SyntaxFactory.PredefinedType(SyntaxTokenFactory.StringKeyword())))
                        .WithDefault(
                            SyntaxFactory.EqualsValueClause(
                                SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression))))))
            .WithExpressionBody(
                SyntaxFactory.ArrowExpressionClause(
                    SyntaxObjectCreationExpressionFactory.Create(className)
                    .WithArgumentList(
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SingletonSeparatedList(
                                SyntaxFactory.Argument(
                                    SyntaxObjectCreationExpressionFactory.Create(typeRequestName)
                                    .WithArgumentList(
                                        SyntaxArgumentListFactory.CreateWithOneItem(parameterName))))))))
            .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
 }
        public void TestNull()
        {
            var syntaxNode = default(SyntaxNode);
            var wrapper    = (LocalFunctionStatementSyntaxWrapper)syntaxNode;

            Assert.Null(wrapper.SyntaxNode);
            Assert.Throws <NullReferenceException>(() => wrapper.Modifiers);
            Assert.Throws <NullReferenceException>(() => wrapper.ReturnType);
            Assert.Throws <NullReferenceException>(() => wrapper.Identifier);
            Assert.Throws <NullReferenceException>(() => wrapper.TypeParameterList);
            Assert.Throws <NullReferenceException>(() => wrapper.ParameterList);
            Assert.Throws <NullReferenceException>(() => wrapper.ConstraintClauses);
            Assert.Throws <NullReferenceException>(() => wrapper.Body);
            Assert.Throws <NullReferenceException>(() => wrapper.ExpressionBody);
            Assert.Throws <NullReferenceException>(() => wrapper.SemicolonToken);
            Assert.Throws <NullReferenceException>(() => wrapper.WithModifiers(SyntaxFactory.TokenList()));
            Assert.Throws <NullReferenceException>(() => wrapper.WithReturnType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword))));
            Assert.Throws <NullReferenceException>(() => wrapper.WithIdentifier(SyntaxFactory.Identifier("Identifier")));
            Assert.Throws <NullReferenceException>(() => wrapper.WithTypeParameterList(SyntaxFactory.TypeParameterList()));
            Assert.Throws <NullReferenceException>(() => wrapper.WithParameterList(SyntaxFactory.ParameterList()));
            Assert.Throws <NullReferenceException>(() => wrapper.WithConstraintClauses(SyntaxFactory.List <TypeParameterConstraintClauseSyntax>()));
            Assert.Throws <NullReferenceException>(() => wrapper.WithBody(SyntaxFactory.Block()));
            Assert.Throws <NullReferenceException>(() => wrapper.WithExpressionBody(SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)))));
            Assert.Throws <NullReferenceException>(() => wrapper.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            Assert.Throws <NullReferenceException>(() => wrapper.AddModifiers());
            Assert.Throws <NullReferenceException>(() => wrapper.AddTypeParameterListParameters());
            Assert.Throws <NullReferenceException>(() => wrapper.AddParameterListParameters());
            Assert.Throws <NullReferenceException>(() => wrapper.AddConstraintClauses());
            Assert.Throws <NullReferenceException>(() => wrapper.AddBodyStatements());
        }
예제 #5
0
        public static bool TryConvertToArrowExpressionBody(
            this BlockSyntax block, SyntaxKind declarationKind,
            ParseOptions options, ExpressionBodyPreference preference,
            out ArrowExpressionClauseSyntax arrowExpression,
            out SyntaxToken semicolonToken)
        {
            var version = ((CSharpParseOptions)options).LanguageVersion;

            // We can always use arrow-expression bodies in C# 7 or above.
            // We can also use them in C# 6, but only a select set of member kinds.
            var acceptableVersion =
                version >= LanguageVersion.CSharp7 ||
                (version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));

            if (!acceptableVersion ||
                !block.TryConvertToExpressionBody(
                    declarationKind, options, preference,
                    out var expression, out semicolonToken))
            {
                arrowExpression = null;
                semicolonToken  = default;
                return(false);
            }

            arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);
            return(true);
        }
예제 #6
0
 /// <summary>
 /// Creates the public properties for each Mvvm library.
 /// </summary>
 /// <returns>The public properties.</returns>
 /// <param name="property">The property to generate.</param>
 public virtual PropertyDeclarationSyntax CreatePublicProperties(Property property)
 {
     return(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(property.Type.FindType()), property.Name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.GetAccessorDeclaration)
                .WithExpressionBody(
                    SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(property.Name.ToCamelCase()))))
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.SetAccessorDeclaration)
                .WithExpressionBody(
                    SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName("Set")))
                        .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(
                                                                         new SyntaxNodeOrToken[]
     {
         SyntaxFactory.Argument(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(property.Name.ToCamelCase())))
         .WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument(SyntaxFactory.IdentifierName("value"))
     })))))
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)))
            .WithModifiers(FormatterHelper.GenerateComment(property.Comment)));
 }
예제 #7
0
        private PropertyDeclarationSyntax CreateCommandProperty(Command command)
        {
            var name = command.FormatCommandName();
            var type = this.GetCommandType(command);

            return(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(typeof(System.Windows.Input.ICommand).ToString()), name)
                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                   .AddAccessorListAccessors(
                       SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                       .WithExpressionBody(
                           SyntaxFactory.ArrowExpressionClause(
                               SyntaxFactory.BinaryExpression(
                                   SyntaxKind.CoalesceExpression,
                                   SyntaxFactory.MemberAccessExpression(
                                       SyntaxKind.SimpleMemberAccessExpression,
                                       SyntaxFactory.ThisExpression(),
                                       SyntaxFactory.IdentifierName(name.ToCamelCase())),
                                   SyntaxFactory.ParenthesizedExpression(
                                       SyntaxFactory.AssignmentExpression(
                                           SyntaxKind.SimpleAssignmentExpression,
                                           SyntaxFactory.MemberAccessExpression(
                                               SyntaxKind.SimpleMemberAccessExpression,
                                               SyntaxFactory.ThisExpression(),
                                               SyntaxFactory.IdentifierName(name.ToCamelCase())),
                                           SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName(type))
                                           .WithArgumentList(this.GetCommandMethodSyntax(command)))))))
                       .WithSemicolonToken(SyntaxFactory.Token(
                                               SyntaxFactory.TriviaList(),
                                               SyntaxKind.SemicolonToken,
                                               SyntaxFactory.TriviaList(SyntaxFactory.Comment(this.GenerateCommandComment(command))))))
                   .WithModifiers(FormatterHelper.GenerateComment(command.Comment)));
        }
        private LocalFunctionStatementSyntax CreateLocalFunctionStatement(
            LocalDeclarationStatementSyntax localDeclaration,
            LambdaExpressionSyntax lambda,
            INamedTypeSymbol delegateType,
            ParameterListSyntax parameterList,
            CancellationToken cancellationToken)
        {
            var modifiers = lambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)
                ? new SyntaxTokenList(lambda.AsyncKeyword)
                : default;

            var invokeMethod = delegateType.DelegateInvokeMethod;
            var returnType   = invokeMethod.GenerateReturnTypeSyntax();

            var identifier        = localDeclaration.Declaration.Variables[0].Identifier;
            var typeParameterList = default(TypeParameterListSyntax);

            var constraintClauses = default(SyntaxList <TypeParameterConstraintClauseSyntax>);

            var body = lambda.Body.IsKind(SyntaxKind.Block)
                ? (BlockSyntax)lambda.Body
                : null;

            var expressionBody = lambda.Body is ExpressionSyntax expression
                ? SyntaxFactory.ArrowExpressionClause(lambda.ArrowToken, expression)
                : null;

            var semicolonToken = lambda.Body is ExpressionSyntax
                ? localDeclaration.SemicolonToken
                : default;

            return(SyntaxFactory.LocalFunctionStatement(
                       modifiers, returnType, identifier, typeParameterList, parameterList,
                       constraintClauses, body, expressionBody, semicolonToken));
        }
예제 #9
0
        public static bool TryConvertToExpressionBody(
            this BlockSyntax block, ParseOptions options,
            ExpressionBodyPreference preference,
            out ArrowExpressionClauseSyntax arrowExpression,
            out SyntaxToken semicolonToken)
        {
            if (preference != ExpressionBodyPreference.Never &&
                (options as CSharpParseOptions)?.LanguageVersion >= LanguageVersion.CSharp7)
            {
                if (block != null && block.Statements.Count == 1)
                {
                    var firstStatement = block.Statements[0];

                    if (TryGetExpression(firstStatement, out var expression, out semicolonToken) &&
                        MatchesPreference(expression, preference))
                    {
                        arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);

                        // The close brace of the block may have important trivia on it (like
                        // comments or directives).  Preserve them on the semicolon when we
                        // convert to an expression body.
                        semicolonToken = semicolonToken.WithAppendedTrailingTrivia(
                            block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine()));
                        return(true);
                    }
                }
            }

            arrowExpression = null;
            semicolonToken  = default(SyntaxToken);
            return(false);
        }
 private MemberDeclarationSyntax CreatePropertyForStatusCodeContent(
     HttpStatusCode statusCode,
     string resultTypeName)
 => SyntaxFactory.PropertyDeclaration(
     SyntaxFactory.IdentifierName(resultTypeName),
     SyntaxFactory.Identifier(statusCode.ToNormalizedString() + "Content"))
 .WithModifiers(SyntaxTokenListFactory.PublicKeyword())
 .WithExpressionBody(
     SyntaxFactory.ArrowExpressionClause(
         SyntaxFactory.ConditionalExpression(
             SyntaxFactory.BinaryExpression(
                 SyntaxKind.LogicalAndExpression,
                 SyntaxFactory.IdentifierName("Is" + statusCode.ToNormalizedString()),
                 SyntaxFactory.IsPatternExpression(
                     SyntaxFactory.IdentifierName("ContentObject"),
                     SyntaxFactory.DeclarationPattern(
                         SyntaxFactory.IdentifierName(resultTypeName),
                         SyntaxFactory.SingleVariableDesignation(
                             SyntaxFactory.Identifier("result"))))),
             SyntaxFactory.IdentifierName("result"),
             SyntaxFactory.ThrowExpression(
                 SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName(nameof(InvalidOperationException)))
                 .WithArgumentList(
                     SyntaxFactory.ArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.Argument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal($"Content is not the expected type - please use the Is{statusCode.ToNormalizedString()} property first."))))))))))
 .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
예제 #11
0
 /// <summary>
 /// Creates the public properties for each Mvvm library.
 /// </summary>
 /// <returns>The public properties.</returns>
 /// <param name="property">The property to generate.</param>
 public override PropertyDeclarationSyntax CreatePublicProperties(Property property)
 {
     return(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(property.Type.FindType()), property.Name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.GetAccessorDeclaration)
                .WithExpressionBody(
                    SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(property.Name.ToCamelCase()))))
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.SetAccessorDeclaration)
                .WithBody(
                    SyntaxFactory.Block(
                        SyntaxFactory.ExpressionStatement(
                            SyntaxFactory.AssignmentExpression(
                                SyntaxKind.SimpleAssignmentExpression,
                                SyntaxFactory.IdentifierName(property.Name.ToCamelCase()),
                                SyntaxFactory.IdentifierName("value"))),
                        SyntaxFactory.ExpressionStatement(
                            SyntaxFactory.InvocationExpression(
                                SyntaxFactory.IdentifierName("RaisePropertyChanged"))))))
            .WithModifiers(FormatterHelper.GenerateComment(property.Comment)));
 }
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            if (!HasClosedSourceAttribute(node, node.AttributeLists))
            {
                return(node);
            }

            if (node.Modifiers.Any(m => m.Text == "abstract"))
            {
                return(node);
            }

            var returntype = node.ReturnType.ToString();

            ExpressionSyntax expression = null;

            if (returntype != "void")
            {
                expression = SyntaxFactory.DefaultExpression(node.ReturnType.WithoutTrivia());
            }
            else
            {
                expression = SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName(@"System.Linq.Expressions.Expression"),
                                                                                                     SyntaxFactory.IdentifierName(@"Empty")).WithOperatorToken(SyntaxFactory.Token(SyntaxKind.DotToken)));
            }

            ArrowExpressionClauseSyntax arrowExpressionClause = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken).WithTrailingTrivia(SyntaxFactory.Space).WithLeadingTrivia(SyntaxFactory.Space), expression);

            return(SyntaxFactory.MethodDeclaration(node.AttributeLists, node.Modifiers,
                                                   node.ReturnType, node.ExplicitInterfaceSpecifier, node.Identifier,
                                                   node.TypeParameterList, node.ParameterList.WithoutTrivia(), node.ConstraintClauses, null, arrowExpressionClause, SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(SyntaxFactory.EndOfLine("\r\n")));
        }
예제 #13
0
        static void HandleMethodCase(CodeRefactoringContext context, SyntaxNode root, SyntaxToken token, MethodDeclarationSyntax method)
        {
            ExpressionSyntax expr;

            if (!IsSimpleReturn(method.Body, out expr))
            {
                if (!IsSimpleExpressionInVoidMethod(method, out expr))
                {
                    return;
                }
            }
            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    token.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("To expression body"),
                    t2 =>
            {
                var newRoot = root.ReplaceNode((SyntaxNode)
                                               method,
                                               method
                                               .WithBody(null)
                                               .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(expr))
                                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                                               .WithTrailingTrivia(expr.Parent.GetTrailingTrivia())
                                               .WithAdditionalAnnotations(Formatter.Annotation)
                                               );
                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }
                    )
                );
        }
예제 #14
0
 internal static ArrowExpressionClauseSyntax MethodPointer(
     string identifier,
     ParameterListSyntax parameters
     ) =>
 SyntaxFactory.ArrowExpressionClause(
     SyntaxFactory.InvocationExpression(
         SyntaxFactory.IdentifierName(identifier),
         FromParams(parameters)));
예제 #15
0
 private PropertyDeclarationSyntax CreateReadOnlyPropertyWithDefultValue(PropertyTemplateData propertyTemplate)
 {
     return(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(propertyTemplate.Type), propertyTemplate.Name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .WithExpressionBody(
                SyntaxFactory.ArrowExpressionClause(
                    SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(propertyTemplate.DefaultValue))))
            .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
 }
        public void TestWithExpressionBody()
        {
            var syntax         = SyntaxFactory.ConstructorDeclaration(SyntaxFactory.Identifier("Anything"));
            var expressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
            var syntaxWithBody = ConstructorDeclarationSyntaxExtensions.WithExpressionBody(syntax, expressionBody);

            Assert.Null(syntax.ExpressionBody);
            Assert.NotNull(syntaxWithBody.ExpressionBody);
            Assert.Equal(SyntaxKind.NullLiteralExpression, syntaxWithBody.ExpressionBody.Expression.Kind());
        }
        public void TestWithExpressionBody()
        {
            var accessorDeclarationSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);
            var expressionBody            = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
            var accessorWithBody          = AccessorDeclarationSyntaxExtensions.WithExpressionBody(accessorDeclarationSyntax, expressionBody);

            Assert.Null(accessorDeclarationSyntax.ExpressionBody);
            Assert.NotNull(accessorWithBody.ExpressionBody);
            Assert.Equal(SyntaxKind.NullLiteralExpression, accessorWithBody.ExpressionBody.Expression.Kind());
        }
예제 #18
0
            TCommand WithSetBody(CodeContext code)
            {
                var body = code.GetCode();

                SetStatements = body as BlockSyntax;
                if (body is ExpressionSyntax bodyexpr)
                {
                    SetExpression = SyntaxFactory.ArrowExpressionClause(bodyexpr);
                }
                return((TCommand)this);
            }
        public async Task FormatElasticTriviaBetweenPropertiesWithoutAccessors()
        {
            var expected = @"class PropertyTest
{
    string MyProperty => ""42"";

    string MyProperty => ""42"";
}";
            var property = SyntaxFactory.PropertyDeclaration(
                attributeLists: default(SyntaxList <AttributeListSyntax>),
                modifiers: SyntaxFactory.TokenList(),
                refKeyword: default(SyntaxToken),
                type: SyntaxFactory.PredefinedType(
                    SyntaxFactory.Token(
                        SyntaxKind.StringKeyword)),
                explicitInterfaceSpecifier: null,
                identifier: SyntaxFactory.Identifier("MyProperty"),
                accessorList: null,
                expressionBody:
                SyntaxFactory.ArrowExpressionClause(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        SyntaxFactory.Literal("42"))),
                initializer: null,
                semicolonToken: SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            var compilation = SyntaxFactory.CompilationUnit(
                externs: default(SyntaxList <ExternAliasDirectiveSyntax>),
                usings: default(SyntaxList <UsingDirectiveSyntax>),
                attributeLists: default(SyntaxList <AttributeListSyntax>),
                members: SyntaxFactory.List(
                    new MemberDeclarationSyntax[]
            {
                SyntaxFactory.ClassDeclaration(
                    attributeLists: default(SyntaxList <AttributeListSyntax>),
                    modifiers: SyntaxFactory.TokenList(),
                    identifier: SyntaxFactory.Identifier("PropertyTest"),
                    typeParameterList: null,
                    baseList: null,
                    constraintClauses: default(SyntaxList <TypeParameterConstraintClauseSyntax>),
                    members: SyntaxFactory.List(
                        new MemberDeclarationSyntax[]
                {
                    property,
                    property
                }))
            }));

            Assert.NotNull(compilation);

            var newCompilation = await Formatter.FormatAsync(compilation, new AdhocWorkspace());

            Assert.Equal(expected, newCompilation.ToFullString());
        }
예제 #20
0
 private LocalFunctionStatementSyntax CreateLocalFunctionStatement()
 {
     return(SyntaxFactory.LocalFunctionStatement(
                modifiers: SyntaxFactory.TokenList(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))),
                returnType: SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)),
                identifier: SyntaxFactory.Identifier("Identifier"),
                typeParameterList: SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(ImmutableArray.Create(SyntaxFactory.TypeParameter("T1")))),
                parameterList: SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(ImmutableArray.Create(SyntaxFactory.Parameter(SyntaxFactory.Identifier("param1"))))),
                constraintClauses: SyntaxFactory.List <TypeParameterConstraintClauseSyntax>(ImmutableArray.Create(SyntaxFactory.TypeParameterConstraintClause(SyntaxFactory.IdentifierName("constraint1")))),
                body: SyntaxFactory.Block(SyntaxFactory.BreakStatement()),
                expressionBody: SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)))));
 }
예제 #21
0
        public async Task <CSharpSyntaxNode> Convert(VBSyntax.LambdaExpressionSyntax vbNode,
                                                     ParameterListSyntax param, IReadOnlyCollection <StatementSyntax> convertedStatements)
        {
            BlockSyntax                 block          = null;
            ExpressionSyntax            expressionBody = null;
            ArrowExpressionClauseSyntax arrow          = null;

            if (convertedStatements.TryUnpackSingleStatement(out StatementSyntax singleStatement) &&
                singleStatement.TryUnpackSingleExpressionFromStatement(out expressionBody))
            {
                arrow = SyntaxFactory.ArrowExpressionClause(expressionBody);
            }
예제 #22
0
 private static AccessorDeclarationSyntax CreateGetter(string backingFieldName)
 {
     return(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
            .WithKeyword(CreateTokenWithTrailingSpace(SyntaxKind.GetKeyword))
            .WithExpressionBody(
                SyntaxFactory.ArrowExpressionClause(
                    SyntaxFactory.MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        SyntaxFactory.ThisExpression(),
                        SyntaxFactory.IdentifierName(backingFieldName)))
                .WithArrowToken(CreateTokenWithTrailingSpace(SyntaxKind.EqualsGreaterThanToken)))
            .WithSemicolonToken(CreateTokenWithTrailingSpace(SyntaxKind.SemicolonToken)));
 }
 private MemberDeclarationSyntax CreatePropertyForIsStatusCode(
     HttpStatusCode statusCode)
 => SyntaxFactory.PropertyDeclaration(
     SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
     SyntaxFactory.Identifier("Is" + statusCode.ToNormalizedString()))
 .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
 .WithExpressionBody(
     SyntaxFactory.ArrowExpressionClause(
         SyntaxFactory.BinaryExpression(
             SyntaxKind.EqualsExpression,
             SyntaxFactory.IdentifierName("StatusCode"),
             SyntaxMemberAccessExpressionFactory.Create(statusCode.ToString(), nameof(HttpStatusCode)))))
 .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
예제 #24
0
파일: Task.cs 프로젝트: legigor/Nake
        public MethodDeclarationSyntax Replace(MethodDeclarationSyntax method)
        {
            var originalBody = MethodBody(method);
            var proxyBody    = ProxyBody(method, originalBody);

            var newBody        = SyntaxFactory.ParseExpression(proxyBody);
            var expressionBody = SyntaxFactory.ArrowExpressionClause(newBody);

            return(method
                   .WithBody(null)
                   .WithoutTrailingTrivia()
                   .WithExpressionBody(expressionBody));
        }
예제 #25
0
        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());
예제 #26
0
        public void TestWithExpressionBody()
        {
            var accessorDeclarationSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);

            // With default value is allowed
            var accessorWithDefaultBody = AccessorDeclarationSyntaxExtensions.WithExpressionBody(accessorDeclarationSyntax, null);

            Assert.Null(AccessorDeclarationSyntaxExtensions.ExpressionBody(accessorWithDefaultBody));

            // Non-default throws an exception
            var expressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));

            Assert.Throws <NotSupportedException>(() => AccessorDeclarationSyntaxExtensions.WithExpressionBody(accessorDeclarationSyntax, expressionBody));
        }
예제 #27
0
        public void TestExpressionBody_Method()
        {
            var syntax = SyntaxFactory.MethodDeclaration(
                SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)),
                SyntaxFactory.Identifier("Anything"));

            Assert.Null(BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax));

            var expressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));

            syntax = syntax.WithExpressionBody(expressionBody);
            Assert.NotNull(BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax));
            Assert.Equal(SyntaxKind.NullLiteralExpression, BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax).Expression.Kind());
        }
예제 #28
0
        public void TestExpressionBody_ConversionOperator()
        {
            var syntax = SyntaxFactory.ConversionOperatorDeclaration(
                SyntaxFactory.Token(SyntaxKind.ExplicitKeyword),
                SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)));

            Assert.Null(BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax));

            var expressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));

            syntax = syntax.WithExpressionBody(expressionBody);
            Assert.NotNull(BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax));
            Assert.Equal(SyntaxKind.NullLiteralExpression, BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntax).Expression.Kind());
        }
        public void TestWithExpressionBody()
        {
            var syntax = SyntaxFactory.DestructorDeclaration(SyntaxFactory.Identifier("Anything"));

            // With default value is allowed
            var syntaxWithDefaultBody = DestructorDeclarationSyntaxExtensions.WithExpressionBody(syntax, null);

            Assert.Null(BaseMethodDeclarationSyntaxExtensions.ExpressionBody(syntaxWithDefaultBody));

            // Non-default throws an exception
            var expressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));

            Assert.Throws <NotSupportedException>(() => DestructorDeclarationSyntaxExtensions.WithExpressionBody(syntax, expressionBody));
        }
 private static MethodDeclarationSyntax CreateTypeRequestWithObject(
     string className,
     HttpStatusCode httpStatusCode,
     string typeRequestName,
     string parameterName = "message")
 {
     return(SyntaxFactory.MethodDeclaration(
                SyntaxFactory.IdentifierName(className),
                SyntaxFactory.Identifier(httpStatusCode.ToNormalizedString()))
            .WithModifiers(SyntaxTokenListFactory.PublicStaticKeyword())
            .WithParameterList(
                SyntaxFactory.ParameterList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Parameter(SyntaxFactory.Identifier(parameterName))
                        .WithType(SyntaxFactory.NullableType(SyntaxFactory.PredefinedType(SyntaxTokenFactory.StringKeyword())))
                        .WithDefault(
                            SyntaxFactory.EqualsValueClause(
                                SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression))))))
            .WithExpressionBody(
                SyntaxFactory.ArrowExpressionClause(
                    SyntaxObjectCreationExpressionFactory.Create(className)
                    .WithArgumentList(
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SingletonSeparatedList(
                                SyntaxFactory.Argument(
                                    SyntaxObjectCreationExpressionFactory.Create(typeRequestName)
                                    .WithInitializer(
                                        SyntaxFactory.InitializerExpression(
                                            SyntaxKind.ObjectInitializerExpression,
                                            SyntaxFactory.SeparatedList <ExpressionSyntax>(
                                                new SyntaxNodeOrToken[]
     {
         SyntaxFactory.AssignmentExpression(
             SyntaxKind.SimpleAssignmentExpression,
             SyntaxFactory.IdentifierName("StatusCode"),
             SyntaxFactory.CastExpression(
                 SyntaxFactory.PredefinedType(
                     SyntaxFactory.Token(SyntaxKind.IntKeyword)),
                 SyntaxFactory.MemberAccessExpression(
                     SyntaxKind.SimpleMemberAccessExpression,
                     SyntaxFactory.IdentifierName(nameof(HttpStatusCode)),
                     SyntaxFactory.IdentifierName(httpStatusCode.ToNormalizedString())))),
         SyntaxTokenFactory.Comma(),
         SyntaxFactory.AssignmentExpression(
             SyntaxKind.SimpleAssignmentExpression,
             SyntaxFactory.IdentifierName("Content"),
             SyntaxFactory.IdentifierName(parameterName)),
     })))))))))
            .WithSemicolonToken(SyntaxTokenFactory.Semicolon()));
 }