private static AccessorDeclarationSyntax CreateSetAccessorWorker(
            SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods)
        {
            var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax;
            var setMethod            = getAndSetMethods.SetMethod;

            if (setMethodDeclaration == null || setMethod?.Parameters.Length != 1)
            {
                return(null);
            }

            var getMethod = getAndSetMethods.GetMethod;
            var accessor  = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration);

            if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility)
            {
                accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, setMethod.DeclaredAccessibility);
            }

            if (setMethodDeclaration.ExpressionBody != null)
            {
                var oldExpressionBody = setMethodDeclaration.ExpressionBody;
                var expression        = ReplaceReferencesToParameterWithValue(
                    semanticModel, setMethod.Parameters[0], oldExpressionBody.Expression);

                return(accessor.WithExpressionBody(oldExpressionBody.WithExpression(expression))
                       .WithSemicolonToken(setMethodDeclaration.SemicolonToken));
            }

            if (setMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None)
            {
                return(accessor.WithSemicolonToken(setMethodDeclaration.SemicolonToken));
            }

            if (setMethodDeclaration.Body != null)
            {
                var body = ReplaceReferencesToParameterWithValue(semanticModel, setMethod.Parameters[0], setMethodDeclaration.Body);
                return(accessor.WithBody(body.WithAdditionalAnnotations(Formatter.Annotation)));
            }

            return(accessor);
        }
Beispiel #2
0
        public override IEnumerable <SyntaxNode> BuildSyntax(IDom item)
        {
            var itemAsT        = item as IAccessor;
            var parentProperty = item.Parent as RDomProperty; // .NET specific

            if (itemAsT == null || parentProperty == null)
            {
                throw new InvalidOperationException();
            }
            var kind = (itemAsT.AccessorType == AccessorType.Get)
                     ? SyntaxKind.GetAccessorDeclaration : SyntaxKind.SetAccessorDeclaration;
            AccessorDeclarationSyntax node;

            if (itemAsT.Statements.Any() || !parentProperty.CanBeAutoProperty)
            {
                var statementBlock = (BlockSyntax)RoslynCSharpUtilities.BuildStatement(itemAsT.Statements, itemAsT, WhitespaceLookup);
                node = SyntaxFactory.AccessorDeclaration(kind, statementBlock);
            }
            else
            {
                node = SyntaxFactory.AccessorDeclaration(kind).WithSemicolonToken(
                    SyntaxFactory.Token(
                        SyntaxKind.SemicolonToken));
            }

            if (itemAsT.AccessModifier != parentProperty.AccessModifier)
            {
                var modifiers = item.BuildModfierSyntax();
                node = node.WithModifiers(modifiers);
            }

            node = BuildSyntaxHelpers.AttachWhitespace(node, itemAsT.Whitespace2Set, WhitespaceLookup);

            var attributeList = BuildSyntaxWorker.BuildAttributeSyntax(itemAsT.Attributes);

            if (attributeList.Any())
            {
                node = node.WithAttributeLists(attributeList);
            }

            return(node.PrepareForBuildSyntaxOutput(item, OutputContext));
        }
Beispiel #3
0
        /// <summary>
        /// 创建新属性
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        public PropertyDeclarationSyntax CreateProperty(CsharpProperty property)
        {
            var documentcomment     = GeneratorComment(property.PropertyComment);
            var propertyDeclaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(property.PropertyType), property.PropertyName)
                                      // .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                      .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))).WithModifiers(
                SyntaxFactory.TokenList(
                    new[] {
                SyntaxFactory.Token(
                    SyntaxFactory.TriviaList(
                        SyntaxFactory.Trivia(documentcomment)), // xmldoc
                    SyntaxKind.PublicKeyword,                   // original 1st token
                    SyntaxFactory.TriviaList())
                //, SyntaxFactory.Token(SyntaxKind.PrivateKeyword)
            }));

            return(propertyDeclaration);
        }
Beispiel #4
0
        public string CreateSettingsInterface(CodeGenerationConfiguration configuration)
        {
            SyntaxNode compilationUnitSyntax = SyntaxFactory.CompilationUnit()
                                               .AddMembers(
                SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(configuration.CoreNamespace))
                .AddMembers(
                    SyntaxFactory.InterfaceDeclaration("IDatabaseSettings")
                    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                    .AddMembers(
                        SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("string"),
                                                          configuration.ConnectionStringName)
                        .AddAccessorListAccessors(
                            SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                            .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)))
                        )
                    ));
            var syntaxNode = Formatter.Format(compilationUnitSyntax, WorkSpace);

            return(syntaxNode.ToFullString());
        }
Beispiel #5
0
        public static IEnumerable <MemberDeclarationSyntax> Properties(SqModelMeta meta, IReadOnlyDictionary <string, SyntaxList <AttributeListSyntax> >?oldAttributes)
        {
            return(meta.Properties.Select(p =>
            {
                var res = SyntaxFactory.PropertyDeclaration(
                    SyntaxFactory.ParseTypeName(p.FinalType),
                    p.Name)
                          .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                          .AddAccessorListAccessors(
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                    );
                if (oldAttributes != null && oldAttributes.TryGetValue(p.Name, out var attributeList))
                {
                    res = res.WithAttributeLists(attributeList);
                }

                return res;
            }));
        }
Beispiel #6
0
        public CSharpSyntaxNode Convert(SetAccessor node)
        {
            PropertyDeclarationSyntax csProperty = SyntaxFactory
                                                   .PropertyDeclaration(node.Parameters[0].Type.ToCsNode <TypeSyntax>(), node.Name.Text)
                                                   .AddModifiers(node.Modifiers.ToCsNodes <SyntaxToken>());

            if (node.JsDoc.Count > 0)
            {
                csProperty = csProperty.WithLeadingTrivia(SyntaxFactory.Trivia(node.JsDoc[0].ToCsNode <DocumentationCommentTriviaSyntax>()));
            }

            AccessorDeclarationSyntax csSetAccess = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration);

            if (node.Body != null)
            {
                csSetAccess = csSetAccess.WithBody(node.Body.ToCsNode <BlockSyntax>());
            }

            return(csProperty.AddAccessorListAccessors(csSetAccess));
        }
        static PropertyDeclarationSyntax GeneratePropertyDeclaration(FieldDeclarationSyntax field, VariableDeclaratorSyntax initializer)
        {
            var modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            if (field.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)))
            {
                modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
            }

            string propertyName = NameProposalService.GetNameProposal(initializer.Identifier.ValueText, SyntaxKind.PropertyDeclaration);
            var    block        = SyntaxFactory.Block(SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(initializer.Identifier)));

            return(SyntaxFactory.PropertyDeclaration(field.Declaration.Type, propertyName)
                   .WithModifiers(modifiers)
                   .WithAccessorList(
                       SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
                                                      SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, block)
                                                      ))
                       ).WithAdditionalAnnotations(Formatter.Annotation));
        }
Beispiel #8
0
        private ClassDeclarationSyntax GenerateProperty(
            GraphQLObjectTypeDefinition objectType,
            ClassDeclarationSyntax classDeclaration,
            GraphQLFieldDefinition field,
            IEnumerable <ASTNode> allDefinitions)
        {
            var member = SyntaxFactory.PropertyDeclaration(
                this.GetCSharpTypeFromGraphQLType(field.Type, allDefinitions),
                PickFieldName(objectType, field, allDefinitions))
                         .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                         .AddModifiers(SyntaxFactory.Token(SyntaxKind.VirtualKeyword))
                         .AddAttributeLists(GetFieldAttributes(field))
                         .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

            return(classDeclaration.AddMembers(member));
        }
        private static SyntaxNode FixWithTrackNode(SyntaxNode root, PropertyDeclarationSyntax property, VariableDeclaratorSyntax fieldVariableDeclaratorSyntax, IEnumerable <SyntaxNode> nodesToUpdate)
        {
            var newRoot         = root.TrackNodes(nodesToUpdate);
            var fieldReferences = nodesToUpdate.OfType <IdentifierNameSyntax>();

            foreach (var identifier in fieldReferences)
            {
                var trackedIdentifierNode   = newRoot.GetCurrentNode(identifier);
                var newIdentifierExpression = SyntaxFactory.IdentifierName(property.Identifier.Text);
                newIdentifierExpression = newIdentifierExpression.WithLeadingTrivia(trackedIdentifierNode.GetLeadingTrivia()).WithTrailingTrivia(trackedIdentifierNode.GetTrailingTrivia()).WithAdditionalAnnotations(Formatter.Annotation);
                newRoot = newRoot.ReplaceNode(trackedIdentifierNode, newIdentifierExpression);
            }
            var prop = newRoot.GetCurrentNode(nodesToUpdate.OfType <PropertyDeclarationSyntax>().Single());
            var fieldInitilization = GetFieldInitialization(fieldVariableDeclaratorSyntax);
            var getter             = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var accessorList       = SyntaxFactory.AccessorList(
                SyntaxFactory.List(new[] {
                getter
            }));
            var newProp = prop.WithAccessorList(accessorList);

            if (fieldInitilization != null)
            {
                newProp = newProp.WithInitializer(fieldInitilization).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            }
            newProp = newProp.WithLeadingTrivia(prop.GetLeadingTrivia()).WithTrailingTrivia(prop.GetTrailingTrivia()).WithAdditionalAnnotations(Formatter.Annotation);
            newRoot = newRoot.ReplaceNode(prop, newProp);
            var variableDeclarator = newRoot.GetCurrentNode(nodesToUpdate.OfType <VariableDeclaratorSyntax>().Single());
            var declaration        = variableDeclarator.AncestorsAndSelf().OfType <VariableDeclarationSyntax>().First();

            if (declaration.Variables.Count == 1)
            {
                var fieldDeclaration = declaration.AncestorsAndSelf().OfType <FieldDeclarationSyntax>().First();
                newRoot = newRoot.RemoveNode(fieldDeclaration, SyntaxRemoveOptions.KeepUnbalancedDirectives);
            }
            else
            {
                newRoot = newRoot.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepUnbalancedDirectives);
            }
            return(newRoot);
        }
        protected override async Task <SyntaxNode> UpdatePropertyAsync(
            Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol,
            PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken)
        {
            var project        = propertyDocument.Project;
            var trailingTrivia = propertyDeclaration.GetTrailingTrivia();

            var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList))
                                  .WithExpressionBody(null)
                                  .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None));

            // We may need to add a setter if the field is written to outside of the constructor
            // of it's class.
            if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor))
            {
                var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                var generator = SyntaxGenerator.GetGenerator(project);

                if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility)
                {
                    accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility);
                }

                var modifiers = SyntaxFactory.TokenList(
                    updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword)));

                updatedProperty = updatedProperty.WithModifiers(modifiers)
                                  .AddAccessorListAccessors(accessor);
            }

            var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false);

            if (fieldInitializer != null)
            {
                updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer))
                                  .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            }

            return(updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation));
        }
Beispiel #11
0
            private void ProccessNode(CSharpSyntaxNode node)
            {
                var modifiers = GetModifiers(Command.Modifiers, Command.Abstract, Command.Static);

                var newGetAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                     .WithModifiers(Command.GetModifier)
                                     .WithExpressionBody(Command.GetExpression)
                                     .WithBody(Command.GetStatements);

                if (newGetAccessor.Body is null)
                {
                    newGetAccessor = newGetAccessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                }

                var newSetAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                     .WithModifiers(Command.SetModifier)
                                     .WithExpressionBody(Command.SetExpression)
                                     .WithBody(Command.SetStatements);

                if (newSetAccessor.Body is null)
                {
                    newSetAccessor = newSetAccessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                }

                var Accesors = new SyntaxList <AccessorDeclarationSyntax>().Add(newGetAccessor).Add(newSetAccessor);

                var property = SyntaxFactory.PropertyDeclaration(Command.ReturnType ?? SyntaxFactory.ParseTypeName("object"), Command.Name)
                               .WithAttributeLists(Command.Attributes)
                               .WithModifiers(modifiers)
                               .WithAdditionalAnnotations(new SyntaxAnnotation($"{Id}"))
                               .WithAccessorList(SyntaxFactory.AccessorList(Accesors));

                if (Command.InitializerExpression != null)
                {
                    property = property.WithInitializer(SyntaxFactory.EqualsValueClause(Command.InitializerExpression))
                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                }


                DocumentEditor.InsertMembers(node, 0, new[] { property });
            }
Beispiel #12
0
        public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax propertyDeclaration)
        {
            // Check each node until we find the property in question. When we have it, we'll replace it with an Auto Property
            if (propertyDeclaration == this._fullProperty)
            {
                // Create Empty getters and setters.
                var emptyGetter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                var emptySetter = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

                if (propertyDeclaration.HasGetter())
                {
                    // Put the original Get modifier on the Auto property
                    emptyGetter = emptyGetter.WithModifiers(propertyDeclaration.GetGetter().Modifiers);
                }
                else
                {
                    // Full property didn't have a getter, but no get in a Auto property makes no sense... We'll keep a get, but make it private
                    emptyGetter = emptyGetter.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)));
                }

                if (propertyDeclaration.HasSetter())
                {
                    // Put the original Set modifier on the Auto property
                    emptySetter = emptySetter.WithModifiers(propertyDeclaration.GetSetter().Modifiers);
                }
                else
                {
                    // Full property didn't have a setter, but no set in an Auto property makes no sense... We'll keep a set, but make it private
                    emptySetter = emptySetter.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)));
                }

                // Create a new auto property (without a body)
                var newProperty = _fullProperty.WithAccessorList(
                    SyntaxFactory.AccessorList(
                        SyntaxFactory.List(new[] { emptyGetter, emptySetter })));

                return(newProperty);
            }

            return(base.VisitPropertyDeclaration(propertyDeclaration));
        }
        private static List <PropertyDeclarationSyntax> CreateProperties(MethodDeclarationSyntax method)
        {
            var newGetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var newSetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var acessorSyntax = SyntaxFactory.AccessorList(
                SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
                SyntaxFactory.List(new[] { newGetSyntax, newSetSyntax }),
                SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
            var properties = new List <PropertyDeclarationSyntax>();

            foreach (ParameterSyntax param in method.ParameterList.Parameters)
            {
                var property = SyntaxFactory.PropertyDeclaration(param.Type, FirstLetteToUpper(param.Identifier.Text))
                               .WithModifiers(SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }))
                               .WithAccessorList(acessorSyntax);
                properties.Add(property);
            }
            return(properties);
        }
Beispiel #14
0
        private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
            IPropertySymbol property,
            IMethodSymbol accessor,
            SyntaxKind kind,
            bool hasBody,
            CodeGenerationOptions options,
            ParseOptions parseOptions
            )
        {
            var declaration = SyntaxFactory
                              .AccessorDeclaration(kind)
                              .WithModifiers(GenerateAccessorModifiers(property, accessor, options))
                              .WithBody(hasBody ? GenerateBlock(accessor) : null)
                              .WithSemicolonToken(
                hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)
                );

            declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions);

            return(AddAnnotationsTo(accessor, declaration));
        }
Beispiel #15
0
        public PropertyDeclarationSyntax GetPropertyDeclaration(bool allowGet = true, bool allowSet = false)
        {
            var declaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(_typeName), PropertyName)
                              .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            if (allowGet)
            {
                declaration = declaration.AddAccessorListAccessors(SyntaxFactory
                                                                   .AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                   .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            if (allowSet)
            {
                declaration = declaration.AddAccessorListAccessors(SyntaxFactory
                                                                   .AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                                   .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            return(declaration);
        }
Beispiel #16
0
        public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
        {
            node = (PropertyDeclarationSyntax)base.VisitPropertyDeclaration(node);

            if (node.ExpressionBody != null)
            {
                var block = SyntaxFactory.Block(
                    SyntaxFactory.ReturnStatement(node.ExpressionBody.Expression)
                    );

                return(node.WithExpressionBody(null)
                       .WithSemicolonToken(default(SyntaxToken))
                       .WithAccessorList(
                           SyntaxFactory.AccessorList(
                               SyntaxFactory.List(new[] { SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, block) })
                               )
                           ));
            }

            return(node);
        }
        protected virtual MemberDeclarationSyntax CreatePropertyDeclaration(ILocatedOpenApiElement <OpenApiSchema> property, string ownerName)
        {
            string propertyName = Context.NameFormatterSelector.GetFormatter(NameKind.Property).Format(property.Key);

            if (propertyName == ownerName)
            {
                // Properties can't have the same name as the class/interface
                propertyName += "Value";
            }

            var typeName = Context.TypeNameProvider.GetName(property);

            return(SyntaxFactory.PropertyDeclaration(typeName, propertyName)
                   .AddElementAnnotation(property, Context.ElementRegistry)
                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                   .AddAccessorListAccessors(
                       SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                       .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                       SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                       .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))));
        }
Beispiel #18
0
        public static PropertyDeclarationSyntax GenProperty(string type, string name, bool setter, string initializer = null)
        {
            var accessors = setter
                ? new[] { SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                          SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) }
                : new[] { SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) };

            return(SyntaxFactory.PropertyDeclaration(
                       attributeLists: SyntaxFactory.List <AttributeListSyntax>(),
                       modifiers: SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)),
                       type: SyntaxFactory.ParseTypeName(type),
                       explicitInterfaceSpecifier: null,
                       identifier: SyntaxFactory.Identifier(name),
                       accessorList: SyntaxFactory.AccessorList(SyntaxFactory.List(accessors)),
                       expressionBody: null,
                       initializer: initializer == null ? null : SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression(initializer)),
                       semicolonToken: initializer == null ? SyntaxFactory.Token(SyntaxKind.None) : SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
        }
Beispiel #19
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            List <PropertyDeclarationSyntax> newDeclarations = new List <PropertyDeclarationSyntax>();

            foreach (var prop in this.propertiesToAdd)
            {
                var newDeclaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(prop.Value), prop.Key)
                                     .WithAccessorList(SyntaxFactory.AccessorList(new SyntaxList <AccessorDeclarationSyntax>(new AccessorDeclarationSyntax[] {
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                })))
                                     .WithModifiers(new SyntaxTokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));

                newDeclaration = newDeclaration.WithAdditionalAnnotations(new SyntaxAnnotation(this.AnnotationKey));
                newDeclarations.Add(newDeclaration);
            }

            var changedClass = node.AddMembers(newDeclarations.ToArray());

            return(base.VisitClassDeclaration(changedClass));
        }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var changedClass   = node;
            var declaredSymbol = this.semanticModel.GetDeclaredSymbol(node);
            var typeName       = declaredSymbol.GetFullMetadataName();

            if (parameters.TypePropertyNames.ContainsKey(typeName))
            {
                foreach (var name in parameters.TypePropertyNames[typeName])
                {
                    changedClass = changedClass.AddMembers(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("int"), name)
                                                           .WithAccessorList(SyntaxFactory.AccessorList(new SyntaxList <AccessorDeclarationSyntax>(new AccessorDeclarationSyntax[] {
                        SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                        SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                    })))
                                                           .WithModifiers(new SyntaxTokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))));
                }
            }

            return(changedClass);
        }
Beispiel #21
0
        private PropertyDeclarationSyntax GenerateProperty(FieldType metaData,
                                                           PropertyConfiguration propertyConfiguration,
                                                           RoslynGeneratorUtils roslynGeneratorUtils,
                                                           IGeneratorConfiguration config)
        {
            var propertyName        = propertyConfiguration.PropertyName ?? roslynGeneratorUtils.NormalizeIdentifiers(metaData.Term, config.PascalCase);
            var propertyDeclaration = SyntaxFactory
                                      .PropertyDeclaration(SyntaxFactory.ParseTypeName(propertyConfiguration.TypeName), propertyName)
                                      .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                      .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

            if (config.TermAttribute != TermAttributeType.none)
            {
                AttributeListSyntax attributeList = GenerateTermAttribute(metaData, config);
                propertyDeclaration = propertyDeclaration.AddAttributeLists(attributeList);
            }

            return(propertyDeclaration);
        }
Beispiel #22
0
        private CSharpSyntaxNode ToGetSet(PropertyDeclaration node)
        {
            List <Node> modifiers = node.Modifiers.FindAll(n => n.Kind != NodeKind.ReadonlyKeyword);

            PropertyDeclarationSyntax csProperty = SyntaxFactory
                                                   .PropertyDeclaration(node.Type.ToCsNode <TypeSyntax>(), node.Name.Text)
                                                   .AddModifiers(modifiers.ToCsNodes <SyntaxToken>());

            if (node.JsDoc.Count > 0)
            {
                csProperty = csProperty.WithLeadingTrivia(SyntaxFactory.Trivia(node.JsDoc[0].ToCsNode <DocumentationCommentTriviaSyntax>()));
            }

            //GetAccess
            AccessorDeclarationSyntax csGetAccess = SyntaxFactory
                                                    .AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            //    if (node.Initializer != null)
            //    {
            //        csGetAccess = csGetAccess.WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(node.Initializer.ToCsNode<ExpressionSyntax>())));
            //    }
            csProperty = csProperty.AddAccessorListAccessors(csGetAccess);

            //SetsAccess
            if ((node.IsReadonly && !node.IsAbstract) || (!node.IsReadonly))
            {
                AccessorDeclarationSyntax csSetAccess = SyntaxFactory
                                                        .AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                                        .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

                if (node.IsReadonly)
                {
                    csSetAccess = csSetAccess.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
                }
                csProperty = csProperty.AddAccessorListAccessors(csSetAccess);
            }

            return(csProperty);
        }
Beispiel #23
0
        public override PropertyDeclarationSyntax EmitSyntax()
        {
            OutputSyntax = SyntaxFactory.PropertyDeclaration(
                Member.PropertyType.GetTypeNameSyntax(),
                SyntaxFactory.Identifier(Member.Name)
                );

            OutputSyntax = OutputSyntax.WithModifiers(EmitMemberModifiers());

            OutputSyntax = OutputSyntax.WithAccessorList(
                SyntaxFactory.AccessorList(
                    SyntaxFactory.List <AccessorDeclarationSyntax>(new[] {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            })
                    )
                );

            return(OutputSyntax);
        }
Beispiel #24
0
        public ClassEventPropertyWithCodeAnalysis(
            ClassMemberVisibilityModifier visibility,
            DelegateReferenceWithCodeAnalysis type,
            string name,
            MethodBodyWithCodeAnalysis addAccessor,
            MethodBodyWithCodeAnalysis removeAccessor)
            : this()
        {
            IEnumerable <AccessorDeclarationSyntax> accessors = new AccessorDeclarationSyntax[]
            {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.AddKeyword, addAccessor.Syntax),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.RemoveKeyword, removeAccessor.Syntax)
            };

            Syntax = SyntaxFactory.EventDeclaration(
                default(SyntaxList <AttributeListSyntax>),
                default(SyntaxTokenList).WithClassMemberVisibilityModifier(visibility),
                type.Syntax,
                null,
                SyntaxFactory.Identifier(name),
                SyntaxFactory.AccessorList(SyntaxFactory.List(accessors)));
        }
Beispiel #25
0
        public PropertyDeclarationSyntax GetPropertyDeclarationSyntax(string propertyName, SyntaxKind syntaxKind)
        {
            var typeSyntax = ListPropertyDeclarationSyntaxGenerator.GetTypeSyntax(propertyName, syntaxKind);

            return(SyntaxFactory.PropertyDeclaration(
                       typeSyntax,
                       SyntaxFactory.Identifier(
                           SyntaxFactory.TriviaList(),
                           propertyName,
                           SyntaxFactory.TriviaList(
                               SyntaxFactory.Space)))
                   .WithModifiers(
                       SyntaxFactory.TokenList(
                           SyntaxFactory.Token(
                               SyntaxFactory.TriviaList(),
                               SyntaxKind.PublicKeyword,
                               SyntaxFactory.TriviaList(
                                   SyntaxFactory.Space))))
                   .WithAccessorList(
                       SyntaxFactory.AccessorList(
                           SyntaxFactory.List <AccessorDeclarationSyntax>(
                               new AccessorDeclarationSyntax[]
            {
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(
                    SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(
                    SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            }))
                       .WithCloseBraceToken(
                           SyntaxFactory.Token(
                               SyntaxFactory.TriviaList(),
                               SyntaxKind.CloseBraceToken,
                               SyntaxFactory.TriviaList(
                                   new[] { SyntaxFactory.Space, SyntaxFactory.LineFeed })))));
        }
        protected override async Task <SyntaxNode> UpdatePropertyAsync(
            Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol,
            PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken)
        {
            var project    = propertyDocument.Project;
            var sourceText = await propertyDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var getAccessor = propertyDeclaration.AccessorList.Accessors.First(d => d.IsKind(SyntaxKind.GetAccessorDeclaration));

            var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList));

            // We may need to add a setter if the field is written to outside of the constructor
            // of it's class.
            if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor))
            {
                var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                               .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                var generator = SyntaxGenerator.GetGenerator(project);

                if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility)
                {
                    accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility);
                }

                updatedProperty = updatedProperty.AddAccessorListAccessors(accessor);
            }

            var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false);

            if (fieldInitializer != null)
            {
                updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer))
                                  .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            }

            updatedProperty = updatedProperty.WithAdditionalAnnotations(SpecializedFormattingAnnotation);

            return(updatedProperty);
        }
Beispiel #27
0
        public string GetClassDefinition(CodeViewModel m)
        {
            var classDeclaration = SyntaxFactory.ClassDeclaration(m.Name)
                                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

            var propertyDeclarations = new List <MemberDeclarationSyntax>();

            foreach (var p in m.Fields)
            {
                var propertyDeclaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(p.Type), p.Name)
                                          .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                          .AddAccessorListAccessors(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)))
                                          .AddAccessorListAccessors(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

                propertyDeclarations.Add(propertyDeclaration);
            }

            classDeclaration = classDeclaration.AddMembers(propertyDeclarations.ToArray());

            return(classDeclaration.NormalizeWhitespace()
                   .ToFullString());
        }
Beispiel #28
0
        public static PropertyDeclarationSyntax Create(IProperty element)
        {
            var propertyDeclaration = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(element.Type), element.Name)
                                      .AddModifiers(SyntaxFactory.ParseToken(element.ModifierDeclaration));

            if (element.SetAccessor)
            {
                propertyDeclaration = propertyDeclaration.AddAccessorListAccessors(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            if (element.GetAccessor)
            {
                propertyDeclaration = propertyDeclaration.AddAccessorListAccessors(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            if (element.Attributes?.Any() ?? false)
            {
                propertyDeclaration = propertyDeclaration.AddAttributeLists(element.Attributes.Select(item => ConstructAttribute.Create(item)).ToArray());
            }

            return(propertyDeclaration);
        }
        private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body)
        {
            switch (node)
            {
            case BasePropertyDeclarationSyntax baseProperty:
                var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
                                                                  SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)));
                return(baseProperty
                       .TryWithExpressionBody(null)
                       .WithAccessorList(accessorList)
                       .TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
                       .WithTriviaFrom(baseProperty));

            case AccessorDeclarationSyntax accessor:
                return(accessor
                       .WithExpressionBody(null)
                       .WithBody(body)
                       .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
                       .WithTriviaFrom(accessor));

            case BaseMethodDeclarationSyntax baseMethod:
                return(baseMethod
                       .WithExpressionBody(null)
                       .WithBody(body)
                       .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
                       .WithTriviaFrom(baseMethod));

            case LocalFunctionStatementSyntax localFunction:
                return(localFunction
                       .WithExpressionBody(null)
                       .WithBody(body)
                       .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
                       .WithTriviaFrom(localFunction));

            default:
                throw ExceptionUtilities.UnexpectedValue(node);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Generates a class declaration for a record schema.
        /// </summary>
        /// <param name="schema">
        /// The schema to generate a class for.
        /// </param>
        /// <returns>
        /// A class declaration with a property for each field of the record schema.
        /// </returns>
        /// <throws cref="UnsupportedSchemaException">
        /// Thrown when a field schema is not recognized.
        /// </throws>
        public virtual ClassDeclarationSyntax GenerateClass(RecordSchema schema)
        {
            var declaration = SyntaxFactory.ClassDeclaration(schema.Name)
                              .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                              .AddMembers(schema.Fields
                                          .Select(field =>
            {
                var child = SyntaxFactory
                            .PropertyDeclaration(
                    GetPropertyType(field.Type),
                    field.Name
                    )
                            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                            .AddAccessorListAccessors(
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                    );

                if (!string.IsNullOrEmpty(field.Documentation))
                {
                    child = AddSummaryComment(child, field.Documentation);
                }

                return(child);
            })
                                          .Where(field => field != null)
                                          .ToArray()
                                          );

            if (!string.IsNullOrEmpty(schema.Documentation))
            {
                declaration = AddSummaryComment(declaration, schema.Documentation);
            }

            return(declaration);
        }