コード例 #1
0
        protected override IEnumerable <AccessorDeclarationSyntax> GetAccessors()
        {
            yield return(SF.AccessorDeclaration(
                             SyntaxKind.GetAccessorDeclaration,
                             SF.List <AttributeListSyntax>(),
                             SF.TokenList(),
                             SF.ParseToken("get"),
                             null,
                             SF.ArrowExpressionClause
                             (
                                 SF.ParseToken("=>"),
                                 CreateGetPropertyInvocationExpression()
                             ),
                             SF.ParseToken(";")
                             ));

            if (!Property.IsImmutable())
            {
                yield return(SF.AccessorDeclaration(
                                 SyntaxKind.SetAccessorDeclaration,
                                 SF.List <AttributeListSyntax>(),
                                 SF.TokenList(),
                                 SF.ParseToken("set"),
                                 null,
                                 SF.ArrowExpressionClause
                                 (
                                     SF.ParseToken("=>"),
                                     CreateSetPropertyInvocationExpression()
                                 ),
                                 SF.ParseToken(";")
                                 ));
            }
        }
コード例 #2
0
        private PropertyDeclarationSyntax CreatePropertyImpl(TypeSyntax type, SymbolData symbol)
        {
            // public [type] [symbol.Name] { get; set; }
            var node = SF.PropertyDeclaration(type, symbol.Name)
                       .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                       .AddAccessorListAccessors(
                SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)));

            if (_options.IsJsonSerializable)
            {
                node = node.WithAttributeLists(CreateSerializationAttribute(symbol));
            }

            if (!string.IsNullOrEmpty(symbol.Summary))
            {
                var comment = new DocumentComment()
                {
                    Summary = symbol.Summary
                };
                node = node.WithLeadingTrivia(comment.ConstructTriviaList());
            }

            return(node);
        }
 private static PropertyDeclarationSyntax CreateNavigationProperty(PropertyDeclarationSyntax navigationProperty, TypeSyntax typeSyntax, string propertyName)
 {
     return(SF.PropertyDeclaration(typeSyntax, propertyName)
            .AddAccessorListAccessors(SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                                      SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)))
            .WithModifiers(navigationProperty.Modifiers.Remove(SF.Token(SyntaxKind.VirtualKeyword))));
 }
コード例 #4
0
        private MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var decoratedValueTypeSyntax = ValueTypeSyntax;

            if (Symbol.ReturnsByRef)
            {
                decoratedValueTypeSyntax = F.RefType(decoratedValueTypeSyntax);
            }
            else if (Symbol.ReturnsByRefReadonly)
            {
                decoratedValueTypeSyntax = F.RefType(decoratedValueTypeSyntax).WithReadOnlyKeyword(F.Token(SyntaxKind.ReadOnlyKeyword));
            }

            var mockedProperty = F.PropertyDeclaration(decoratedValueTypeSyntax, Symbol.Name)
                                 .WithExplicitInterfaceSpecifier(F.ExplicitInterfaceSpecifier(TypesForSymbols.ParseName(InterfaceSymbol)));

            if (Symbol.IsReadOnly)
            {
                ExpressionSyntax elementAccess = F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, F.IdentifierName(MemberMockName),
                                                                          F.IdentifierName("Value"));

                if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                {
                    elementAccess = TypesForSymbols.WrapByRef(elementAccess, ValueTypeSyntax);
                }

                mockedProperty = mockedProperty.WithExpressionBody(F.ArrowExpressionClause(elementAccess))
                                 .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken));
            }
            else
            {
                if (!Symbol.IsWriteOnly)
                {
                    mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                             .WithExpressionBody(F.ArrowExpressionClause(F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                                                                                                  F.IdentifierName(MemberMockName),
                                                                                                                                                  F.IdentifierName("Value"))))
                                                                             .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                             );
                }

                if (!Symbol.IsReadOnly)
                {
                    mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                                             .WithExpressionBody(
                                                                                 F.ArrowExpressionClause(
                                                                                     F.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                                            F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, F.IdentifierName(MemberMockName),
                                                                                                                                     F.IdentifierName("Value")),
                                                                                                            F.IdentifierName("value"))))
                                                                             .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                             );
                }
            }

            return(mockedProperty);
        }
コード例 #5
0
        private MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var decoratedValueTypeSyntax = ValueTypeSyntax;

            if (Symbol.ReturnsByRef)
            {
                decoratedValueTypeSyntax = F.RefType(decoratedValueTypeSyntax);
            }
            else if (Symbol.ReturnsByRefReadonly)
            {
                decoratedValueTypeSyntax = F.RefType(decoratedValueTypeSyntax).WithReadOnlyKeyword(F.Token(SyntaxKind.ReadOnlyKeyword));
            }

            var mockedIndexer = F.IndexerDeclaration(decoratedValueTypeSyntax)
                                .WithParameterList(KeyType.BuildParameterList())
                                .WithExplicitInterfaceSpecifier(F.ExplicitInterfaceSpecifier(TypesForSymbols.ParseName(InterfaceSymbol)));

            var arguments = KeyType.BuildArgumentList();

            if (Symbol.IsReadOnly)
            {
                ExpressionSyntax elementAccess = F.ElementAccessExpression(F.IdentifierName(MemberMockName))
                                                 .WithExpressionsAsArgumentList(arguments);

                if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                {
                    elementAccess = TypesForSymbols.WrapByRef(elementAccess, ValueTypeSyntax);
                }

                mockedIndexer = mockedIndexer.WithExpressionBody(F.ArrowExpressionClause(elementAccess))
                                .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken));
            }
            else
            {
                if (!Symbol.IsWriteOnly)
                {
                    mockedIndexer = mockedIndexer.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                           .WithExpressionBody(F.ArrowExpressionClause(F.ElementAccessExpression(F.IdentifierName(MemberMockName))
                                                                                                                       .WithExpressionsAsArgumentList(arguments)))
                                                                           .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                           );
                }

                if (!Symbol.IsReadOnly)
                {
                    mockedIndexer = mockedIndexer.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                                           .WithExpressionBody(F.ArrowExpressionClause(
                                                                                                   F.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                                                          F.ElementAccessExpression(F.IdentifierName(MemberMockName)).WithExpressionsAsArgumentList(arguments),
                                                                                                                          F.IdentifierName("value"))))
                                                                           .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken)));
                }
            }

            return(mockedIndexer);
        }
コード例 #6
0
        public WebInfoGenerationData GetClassForWebElement(WebElementInfo info)
        {
            var className   = GetClassNameFromElementName(info.Name);
            var propName    = className.Substring(1);
            var constInfoCD = GetClassForConstInfo(info);

            var baseClassName = info.GetType().Name;
            var docComment    = GetDocCommentWithText(info.Description);

            var infoComment = GetDocCommentWithText("Information about element");

            var infoProperty = SF.PropertyDeclaration(
                SF.ParseTypeName($"{InfoStaticClassName}.{InfoClassName}"),
                SF.Identifier(InfoClassName)
                )
                               .WithAccessorList(
                SF.AccessorList(
                    SF.List(
                        new List <AccessorDeclarationSyntax>
            {
                SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
            }
                        )
                    )
                .WithOpenBraceToken(SF.Token(SyntaxKind.OpenBraceToken))
                .WithCloseBraceToken(SF.Token(SyntaxKind.CloseBraceToken))
                )
                               .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(infoComment)));

            var getInstMd = GetGetInstanceMethod(className);

            var cd = SF.ClassDeclaration(className)
                     .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(docComment)))
                     .AddBaseListTypes(SF.SimpleBaseType(SF.IdentifierName(baseClassName)))
                     .AddMembers(infoProperty, getInstMd, constInfoCD);

            var genData = new WebInfoGenerationData
            {
                ClassName    = className,
                PropertyName = propName,
                ClassSyntax  = cd,
                Element      = info
            };

            FillWithChildrenElementsProperties(genData, out List <WebInfoGenerationData> childrenGens);

            AddCtor(genData, childrenGens);

            FillWithChildrenElementsClasses(genData, childrenGens);

            return(genData);
        }
コード例 #7
0
        private static ClassDeclarationSyntax AddMockBehaviorProperty(ClassDeclarationSyntax classDclr)
        {
            classDclr = classDclr.AddMembers(
                SF.PropertyDeclaration(SF.ParseTypeName("MockBehavior"), "MockBehavior")
                .AddAccessorListAccessors(
                    SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                    SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)))
                .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PublicKeyword))));

            return(classDclr);
        }
コード例 #8
0
        private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType)
        {
            var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName);
            var returnValue  = grainType.GetParseableName().GetLiteralExpression();

            return
                (SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name)
                 .AddAccessorListAccessors(
                     SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                     .AddBodyStatements(SF.ReturnStatement(returnValue)))
                 .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)));
        }
コード例 #9
0
        private void FillWithChildrenElementsProperties(WebInfoGenerationData genData, out List <WebInfoGenerationData> childrenGens)
        {
            childrenGens = null;
            if (!(genData.Element is CombinedWebElementInfo combinedInfo))
            {
                return;
            }

            childrenGens = combinedInfo.Elements
                           ?.Select(e => GetClassForWebElement(e)).ToList()
                           ?? new List <WebInfoGenerationData>();

            if (childrenGens.Count == 0)
            {
                return;
            }

            var members = new List <MemberDeclarationSyntax>();

            foreach (var childGen in childrenGens)
            {
                var docComment = GetDocCommentWithText(childGen.Element.Description);

                var pd = SF.PropertyDeclaration(
                    SF.IdentifierName(SF.Identifier(childGen.ClassName)),
                    SF.Identifier(childGen.PropertyName)
                    )
                         .WithAccessorList(
                    SF.AccessorList(
                        SF.List(
                            new List <AccessorDeclarationSyntax>
                {
                    SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                    SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                    .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
                }
                            )
                        )
                    .WithOpenBraceToken(SF.Token(SyntaxKind.OpenBraceToken))
                    .WithCloseBraceToken(SF.Token(SyntaxKind.CloseBraceToken))
                    )
                         .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(docComment)));

                members.Add(pd);
            }

            var cd = genData.ClassSyntax.AddMembers(members.ToArray());

            genData.ClassSyntax = cd;
        }
コード例 #10
0
        private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType)
        {
            var property    = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId);
            var returnValue = SF.LiteralExpression(
                SyntaxKind.NumericLiteralExpression,
                SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType)));

            return
                (SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name)
                 .AddAccessorListAccessors(
                     SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                     .AddBodyStatements(SF.ReturnStatement(returnValue)))
                 .AddModifiers(SF.Token(SyntaxKind.ProtectedKeyword), SF.Token(SyntaxKind.OverrideKeyword)));
        }
コード例 #11
0
        private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType)
        {
            var property    = TypeUtils.Member((GrainReference _) => _.InterfaceVersion);
            var returnValue = SF.LiteralExpression(
                SyntaxKind.NumericLiteralExpression,
                SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType)));

            return
                (SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name)
                 .AddAccessorListAccessors(
                     SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                     .AddBodyStatements(SF.ReturnStatement(returnValue)))
                 .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)));
        }
コード例 #12
0
        private MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var mockedIndexer = F.IndexerDeclaration(ValueWithReadonlyTypeSyntax)
                                .WithParameterList(F.BracketedParameterList(F.SeparatedList(Symbol.Parameters.Select(a =>
                                                                                                                     F.Parameter(F.Identifier(a.Name)).WithType(TypesForSymbols.ParseTypeName(a.Type, a.NullableOrOblivious()))))))
                                .WithExplicitInterfaceSpecifier(F.ExplicitInterfaceSpecifier(TypesForSymbols.ParseName(InterfaceSymbol)));

            if (Symbol.IsReadOnly)
            {
                ExpressionSyntax invocation = F.InvocationExpression(F.IdentifierName(MemberMockName),
                                                                     F.ArgumentList(F.SeparatedList(Symbol.Parameters.Select(a => F.Argument(F.IdentifierName(a.Name))))));
                if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                {
                    invocation = F.RefExpression(invocation);
                }

                mockedIndexer = mockedIndexer
                                .WithExpressionBody(F.ArrowExpressionClause(invocation))
                                .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken));
            }
            else
            {
                if (!Symbol.IsWriteOnly)
                {
                    var argumentList = F.SeparatedList(Symbol.Parameters.Select(a => F.Argument(F.IdentifierName(a.Name))));

                    mockedIndexer = mockedIndexer.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                           .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(F.IdentifierName(MemberMockName))
                                                                                                                       .WithArgumentList(F.ArgumentList(argumentList))))
                                                                           .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                           );
                }

                if (!Symbol.IsReadOnly)
                {
                    var argumentList = F.SeparatedList(Symbol.Parameters.Select(a => F.Argument(F.IdentifierName(a.Name))))
                                       .Add(F.Argument(F.IdentifierName("value")));

                    mockedIndexer = mockedIndexer.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                                           .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(F.IdentifierName(MemberMockName),
                                                                                                                                              F.ArgumentList(argumentList))))
                                                                           .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                           );
                }
            }

            return(mockedIndexer);
        }
コード例 #13
0
        public static string GenerateClass()
        {
            var @consoleWriteLine = Syntax.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                  Syntax.IdentifierName("Console"),
                                                                  name: Syntax.IdentifierName("WriteLine"));


            var @arguments = Syntax.ArgumentList(Syntax.SeparatedList(new[] {
                Syntax.Argument(
                    Syntax.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        Syntax.Literal(@"$""{this.Name} -> {this.counter}""", "${this.Name} -> {this.counter}")))
            }));

            var @consoleWriteLineStatement = Syntax.ExpressionStatement(Syntax.InvocationExpression(@consoleWriteLine, @arguments));

            var @voidType   = Syntax.ParseTypeName("void");
            var @stringType = Syntax.ParseTypeName("string");

            var @field    = Syntax.FieldDeclaration(Syntax.VariableDeclaration(Syntax.ParseTypeName("int"), Syntax.SeparatedList(new[] { Syntax.VariableDeclarator(Syntax.Identifier("counter")) }))).AddModifiers(Syntax.Token(SyntaxKind.PrivateKeyword)).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken));
            var @property = Syntax.PropertyDeclaration(stringType, "Name").AddAccessorListAccessors(Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                                                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)
                                                                                                                        )).AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword));

            @property = @property.AddAccessorListAccessors(Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)));

            var @printMethod = Syntax.MethodDeclaration(voidType, "Print").AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).WithBody(Syntax.Block(consoleWriteLineStatement));



            List <ParameterSyntax> @parameterList = new List <ParameterSyntax>
            {
                Syntax.Parameter(Syntax.Identifier("x")).WithType(Syntax.ParseTypeName("int"))
            };
            var @methodBody      = Syntax.ParseStatement("counter += x;");
            var @incrementMethod = Syntax.MethodDeclaration(voidType, "Increment").AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).WithBody(Syntax.Block(methodBody)).AddParameterListParameters(parameterList.ToArray());


            var @class = Syntax.ClassDeclaration("MyClass").WithMembers(Syntax.List(new MemberDeclarationSyntax[] { @property, @field, @incrementMethod, @printMethod })).AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).AddModifiers(Syntax.Token(SyntaxKind.SealedKeyword));

            var adhocWorkSpace = new AdhocWorkspace();

            adhocWorkSpace.Options.WithChangedOption(CSharpFormattingOptions.IndentBraces, true);
            var formattedCode = Formatter.Format(@class, adhocWorkSpace);

            return(formattedCode.ToFullString());
        }
            public AccessorDeclarationSyntax Build()
            {
                var acc = SF.AccessorDeclaration(_kind).AddModifiers(_modifiers.Build().ToArray());;

                if (_expr != null)
                {
                    return(acc.WithExpressionBody(SF.ArrowExpressionClause(_expr.Value.Build())).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)));
                }
                else if (_block != null)
                {
                    return(acc.WithBody(_block.Value.Build()));
                }
                else
                {
                    return(acc.WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)));
                }
            }
コード例 #15
0
ファイル: ClassGenerator.cs プロジェクト: bohoffi/xsd2code
 private SyntaxList <MemberDeclarationSyntax> GenerateProperties(List <Property> props)
 {
     return(SF.List(props.Select(p =>
     {
         //return (MemberDeclarationSyntax)SF.PropertyDeclaration(
         //            SF.PredefinedType(
         //                SF.Token(SyntaxKind.StringKeyword)),
         //            SF.Identifier(p.CleanName))
         //       .WithAttributeLists(
         //                SF.SingletonList(
         //                    SF.AttributeList(
         //                        GenerateAttributes(p.Attributes))))
         //       .WithModifiers(
         //            SF.TokenList(
         //                SF.Token(SyntaxKind.PublicKeyword)))
         //       .WithAccessorList(
         //            SF.AccessorList(
         //                SF.List(
         //                    new AccessorDeclarationSyntax[]{
         //                        SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
         //                            .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
         //                        SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
         //                            .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
         //                    })));
         return (MemberDeclarationSyntax)p.ToDeclarationSyntax()
         .WithAttributeLists(
             SF.SingletonList(
                 SF.AttributeList(
                     GenerateAttributes(p.XmlAttributes))))
         .WithModifiers(
             SF.TokenList(
                 SF.Token(SyntaxKind.PublicKeyword)))
         .WithAccessorList(
             SF.AccessorList(
                 SF.List(
                     new AccessorDeclarationSyntax[] {
             SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
             .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
             SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
             .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
         })));
     }).ToList()));
 }
コード例 #16
0
    public static void Generate()
    {
        // Make a namespace
        var nspaceDecl = SF.NamespaceDeclaration(SF.ParseName("ExampleNamespace"));

        // Make a class
        var classDecl = SF.ClassDeclaration("Order");

        // Class inherits base type and implements interface
        classDecl = classDecl.AddBaseListTypes(
            SF.SimpleBaseType(SF.ParseTypeName("BaseEntity<Order>")),
            SF.SimpleBaseType(SF.ParseTypeName("IHaveIdentity"))
            );

        var varDecl = SF.VariableDeclaration(SF.ParseTypeName("bool")).AddVariables(SF.VariableDeclarator("canceled"));

        var fieldDecl = SF.FieldDeclaration(varDecl).AddModifiers(SF.Token(SyntaxKind.PrivateKeyword));

        var propDecl = SF.PropertyDeclaration(SF.ParseTypeName("int"), "Quantity")
                       .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                       .AddAccessorListAccessors(
            SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
            SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
            );

        var methodBody = SF.ParseStatement("canceled = true");

        var methodDecl = SF.MethodDeclaration(SF.ParseTypeName("void"), "MarkAsCanceled")
                         .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                         .WithBody(SF.Block(methodBody));

        classDecl = classDecl.AddMembers(
            fieldDecl,
            propDecl,
            methodDecl);

        nspaceDecl = nspaceDecl.AddMembers(classDecl);

        var code = nspaceDecl.NormalizeWhitespace().ToFullString();

        Console.WriteLine(code);
    }
コード例 #17
0
        protected override IEnumerable <AccessorDeclarationSyntax> GetAccessors()
        {
            yield return(SF.AccessorDeclaration(
                             SyntaxKind.GetAccessorDeclaration,
                             SF.List <AttributeListSyntax>(),
                             SF.TokenList(),
                             SF.ParseToken("get"),
                             (BlockSyntax)null,
                             SF.ParseToken(";")
                             ));

            yield return(SF.AccessorDeclaration(
                             SyntaxKind.SetAccessorDeclaration,
                             SF.List <AttributeListSyntax>(),
                             SF.TokenList(),
                             SF.ParseToken("set"),
                             (BlockSyntax)null,
                             SF.ParseToken(";")
                             ));
        }
コード例 #18
0
ファイル: SyntaxHelper.cs プロジェクト: alexandrvslv/datawf
        public static PropertyDeclarationSyntax GenProperty(string type, string name, bool setter, string initializer = null)
        {
            var accessors = setter
                ? new[] { SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                          .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                          SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                          .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)) }
                : new[] { SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                          .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)) };

            return(SF.PropertyDeclaration(
                       attributeLists: SF.List <AttributeListSyntax>(),
                       modifiers: SF.TokenList(SF.Token(SyntaxKind.PublicKeyword)),
                       type: SF.ParseTypeName(type),
                       explicitInterfaceSpecifier: null,
                       identifier: SF.Identifier(name),
                       accessorList: SF.AccessorList(SF.List(accessors)),
                       expressionBody: null,
                       initializer: initializer == null ? null : SF.EqualsValueClause(SF.ParseExpression(initializer)),
                       semicolonToken: initializer == null ? SF.Token(SyntaxKind.None) : SF.Token(SyntaxKind.SemicolonToken)));
        }
コード例 #19
0
        private MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var mockedProperty = F.EventDeclaration(EventHandlerTypeSyntax, Symbol.Name)
                                 .WithExplicitInterfaceSpecifier(F.ExplicitInterfaceSpecifier(TypesForSymbols.ParseName(InterfaceSymbol)));

            mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.AddAccessorDeclaration)
                                                                     .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(
                                                                                                                     F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, F.IdentifierName(MemberMockName),
                                                                                                                                              F.IdentifierName("Add")))
                                                                                                                 .WithExpressionsAsArgumentList(F.IdentifierName("value"))))
                                                                     .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                     );

            mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration)
                                                                     .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(
                                                                                                                     F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                                                                                              F.IdentifierName(MemberMockName), F.IdentifierName("Remove")))
                                                                                                                 .WithExpressionsAsArgumentList(F.IdentifierName("value"))))
                                                                     .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken)));

            return(mockedProperty);
        }
コード例 #20
0
        private MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var mockedProperty = F.PropertyDeclaration(ValueWithReadonlyTypeSyntax, Symbol.Name)
                                 .WithExplicitInterfaceSpecifier(F.ExplicitInterfaceSpecifier(TypesForSymbols.ParseName(InterfaceSymbol)));

            if (Symbol.IsReadOnly)
            {
                ExpressionSyntax invocation = F.InvocationExpression(F.IdentifierName(MemberMockName));
                if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                {
                    invocation = F.RefExpression(invocation);
                }

                mockedProperty = mockedProperty
                                 .WithExpressionBody(F.ArrowExpressionClause(invocation))
                                 .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken));
            }
            else
            {
                if (!Symbol.IsWriteOnly)
                {
                    mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                             .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(F.IdentifierName(MemberMockName))))
                                                                             .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                             );
                }

                if (!Symbol.IsReadOnly)
                {
                    mockedProperty = mockedProperty.AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                                             .WithExpressionBody(F.ArrowExpressionClause(F.InvocationExpression(F.IdentifierName(MemberMockName),
                                                                                                                                                F.ArgumentList(F.SeparatedList(new[] { F.Argument(F.IdentifierName("value")) })))))
                                                                             .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))
                                                                             );
                }
            }

            return(mockedProperty);
        }
コード例 #21
0
        /// <summary>
        ///     Create a class that implements <see cref="ICommand"/>.
        ///
        ///     The implementation will execute the given <see cref="method"/>.
        /// </summary>
        /// <param name="id">The unique identifier of the command for <see cref="ICommand.Id"/>.</param>
        /// <param name="className">The new class name.</param>
        /// <param name="moduleType">The type that contains the <see cref="method"/>.</param>
        /// <param name="method">The method that should be executed when <see cref="ICommand.ExecuteAsync"/> is called.</param>
        /// <returns>The <see cref="ClassDeclarationSyntax"/>.</returns>
        private ClassDeclarationSyntax CreateCommandClass(
            string id,
            IReadOnlyList <string> aliases,
            string className,
            Type moduleType,
            MethodInfo method)
        {
            var permission      = ModuleUtils.GetPermissionName(moduleType, method);
            var moduleName      = ModuleUtils.GetModuleName(moduleType);
            var attr            = method.GetCustomAttribute <CommandAttribute>();
            var guildOnly       = attr.GuildOnly;
            var permissionGroup = attr.PermissionGroup.ToString();

            return(S.ClassDeclaration(className)
                   .AddBaseListTypes(S.SimpleBaseType(CommandType))
                   .AddMembers(
                       // ICommand.Id
                       S.PropertyDeclaration(StringType, nameof(ICommand.Id))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(id))))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.Aliases
                       S.PropertyDeclaration(ReadOnlyStringList, nameof(ICommand.Aliases))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.ArrayCreationExpression(
                                                                    S.ArrayType(StringType)
                                                                    .WithRankSpecifiers(S.SingletonList(S.ArrayRankSpecifier(S.SingletonSeparatedList <ExpressionSyntax>(S.OmittedArraySizeExpression())))),
                                                                    S.InitializerExpression(SyntaxKind.ArrayInitializerExpression,
                                                                                            new SeparatedSyntaxList <ExpressionSyntax>()
                                                                                            .AddRange(aliases.Select(s => S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(s))))))))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.Module
                       S.PropertyDeclaration(StringType, nameof(ICommand.Module))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(moduleName))))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.Permission
                       S.PropertyDeclaration(StringType, nameof(ICommand.Permission))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(permission))))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.PermissionGroup
                       S.PropertyDeclaration(S.ParseName(nameof(PermissionGroup)), nameof(ICommand.PermissionGroup))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, S.IdentifierName(nameof(PermissionGroup)), S.IdentifierName(permissionGroup))))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.GuildOnly
                       S.PropertyDeclaration(BoolType, nameof(ICommand.GuildOnly))
                       .AddAccessorListAccessors(
                           S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(guildOnly ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression)))
                           .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken))
                           )
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword)),

                       // ICommand.ExecuteAsync
                       S.MethodDeclaration(TaskType, nameof(ICommand.ExecuteAsync))
                       .AddModifiers(S.Token(SyntaxKind.PublicKeyword), S.Token(SyntaxKind.AsyncKeyword))
                       .AddParameterListParameters(Parameter(ArgumentContext, MessageContextType))
                       .AddBodyStatements(
                           S.ExpressionStatement(InvokeCommand(moduleType, method))
                           )
                       ));
        }
コード例 #22
0
 public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, BlockSyntax body)
 {
     return(SyntaxFactory.AccessorDeclaration(kind, default(SyntaxList <AttributeListSyntax>), default(SyntaxTokenList), SyntaxFactory.Token(GetAccessorDeclarationKeywordKind(kind)), body, expressionBody: null, default(SyntaxToken)));
 }
コード例 #23
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
            var diagnostic = context.Diagnostics.First();

            if (diagnostic.Id == StacksAnalyzer.CommandsEndWithCommand.Id)
            {
                var diagnosticSpan = diagnostic.Location.SourceSpan;

                // Find the type declaration identified by the diagnostic.
                var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <TypeDeclarationSyntax>().First();

                // Register a code action that will invoke the fix.
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: "Append 'Command'",
                        createChangedSolution: c => this.AppendCommandText(context.Document, "Command", declaration, c),
                        equivalenceKey: "Append 'Command'"),
                    diagnostic);
            }
            else if (diagnostic.Id == StacksAnalyzer.EventsEndWithEvents.Id)
            {
                var diagnosticSpan = diagnostic.Location.SourceSpan;

                // Find the type declaration identified by the diagnostic.
                var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <TypeDeclarationSyntax>().First();

                // Register a code action that will invoke the fix.
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: "Append 'Event'",
                        createChangedSolution: c => this.AppendCommandText(context.Document, "Event", declaration, c),
                        equivalenceKey: "Append 'Event'"),
                    diagnostic);
            }
            else if (diagnostic.Id == StacksAnalyzer.MessagePropertiesAreImmutable.Id)
            {
                var diagnosticSpan = diagnostic.Location.SourceSpan;

                var property = root.FindNode(diagnosticSpan) as PropertyDeclarationSyntax;

                // Register a code action that will invoke the fix.
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: "Remove setter",
                        createChangedDocument: async c =>
                {
                    var previousWhiteSpacesToken = SF.Token(property.GetLeadingTrivia(), SyntaxKind.StringLiteralToken, SyntaxTriviaList.Empty);

                    var target = property.WithModifiers(SF.TokenList(previousWhiteSpacesToken, SF.Token(SyntaxKind.PublicKeyword)))
                                 .WithAccessorList(SF.AccessorList(SF.List(new[]
                    {
                        SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                        .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
                    })));

                    var updated = await context.Document.GetSyntaxRootAsync(c);
                    return(context.Document.WithSyntaxRoot(updated.ReplaceNode(property, new[] { target })));
                },
                        equivalenceKey: "Remove setter"),
                    diagnostic);

                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: "Make setter private",
                        createChangedDocument: async c =>
                {
                    var previousWhiteSpacesToken = SF.Token(property.GetLeadingTrivia(), SyntaxKind.StringLiteralToken, SyntaxTriviaList.Empty);

                    var target = property.WithModifiers(SF.TokenList(previousWhiteSpacesToken, SF.Token(SyntaxKind.PublicKeyword)))
                                 .WithAccessorList(SF.AccessorList(SF.List(new[]
                    {
                        SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                        .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                        SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                        .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PrivateKeyword)))
                        .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
                    })));

                    var updated = await context.Document.GetSyntaxRootAsync(c);
                    return(context.Document.WithSyntaxRoot(updated.ReplaceNode(property, new[] { target })));
                },
                        equivalenceKey: "Make setter private"),
                    diagnostic);
            }
            else if (diagnostic.Id == StacksAnalyzer.UseCaseShouldHaveRules.Id)
            {
                var diagnosticSpan = diagnostic.Location.SourceSpan;

                var property = root.FindNode(diagnosticSpan) as ClassDeclarationSyntax;

                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: "Create business rule",
                        createChangedDocument: async c =>
                {
                    //property.Identifier.ValueText;

                    var cu = SF.CompilationUnit().AddUsings(
                        SF.UsingDirective(SF.IdentifierName("System")),
                        SF.UsingDirective(SF.IdentifierName("Slalom.Stacks.Messaging.Validation")));


                    NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;
                    if (!SyntaxNodeHelper.TryGetParentSyntax(property, out namespaceDeclarationSyntax))
                    {
                    }

                    var ns = SF.NamespaceDeclaration(namespaceDeclarationSyntax.Name);

                    var comp    = await context.Document.Project.GetCompilationAsync();
                    string name = property.Identifier.Value + "_rule";
                    var command = ((IdentifierNameSyntax)((GenericNameSyntax)property.BaseList.Types[0].Type).TypeArgumentList.Arguments[0]).Identifier.ValueText;
                    //if (comp.GetSymbolsWithName(x => x == name) != null)
                    //{
                    //    int i = 1;
                    //    var current = name + i;
                    //    while (comp.GetSymbolsWithName(x => x == current) != null)
                    //    {
                    //        i++;
                    //    }
                    //}

                    var cl = SF.ClassDeclaration(name)
                             .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PublicKeyword)))
                             .AddBaseListTypes(SF.SimpleBaseType(SF.ParseTypeName("BusinessRule<" + command + ">")));
                    ns = ns.AddMembers(cl);
                    cu = cu.AddMembers(ns);

                    SyntaxNode formattedNode = Formatter.Format(cu, context.Document.Project.Solution.Workspace);
                    StringBuilder sb         = new StringBuilder();
                    using (StringWriter writer = new StringWriter(sb))
                    {
                        formattedNode.WriteTo(writer);
                    }

                    return(context.Document.Project.AddDocument(name + ".cs", sb.ToString(), namespaceDeclarationSyntax.Name.ToString().Split('.').Skip(1).Concat(new[] { "Rules" })));
                },
                        equivalenceKey: "Create business rule"),
                    diagnostic);
            }
        }
コード例 #24
0
ファイル: PropertyBasedMock.cs プロジェクト: mocklis/mocklis
 protected PropertyDeclarationSyntax MockProperty(TypeSyntax mockPropertyType)
 {
     return(F.PropertyDeclaration(mockPropertyType, MemberMockName).AddModifiers(F.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(F.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                      .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken))));
 }