示例#1
0
        protected TDeclaration WithAccessorList(
            TDeclaration declaration, OptionSet options, ParseOptions parseOptions)
        {
            var expressionBody = GetExpressionBody(declaration);
            var semicolonToken = GetSemicolonToken(declaration);

            var expressionBodyPreference = options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;

            expressionBody.TryConvertToBlock(GetSemicolonToken(declaration), CreateReturnStatementForExpression(declaration), out var block);

            var useExpressionBodyIfAvailable =
                expressionBodyPreference != ExpressionBodyPreference.Never &&
                ((CSharpParseOptions)parseOptions).LanguageVersion >= LanguageVersion.CSharp7;

            AccessorDeclarationSyntax accessor;

            if (block == null ||
                useExpressionBodyIfAvailable)
            {
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .WithExpressionBody(expressionBody)
                           .WithSemicolonToken(semicolonToken);
            }
            else
            {
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, block);
            }

            return(WithAccessorList(declaration, SyntaxFactory.AccessorList(
                                        SyntaxFactory.SingletonList(accessor))));
        }
        public StaticClassPropertyWithCodeAnalysis(
            ClassMemberVisibilityModifier visibility,
            ITypeReferenceWithCodeAnalysis type,
            string name,
            MethodBodyWithCodeAnalysis getAccessor,
            MethodBodyWithCodeAnalysis setAccessor)
            : this()
        {
            List <AccessorDeclarationSyntax> accessorSyntax = new List <AccessorDeclarationSyntax>();

            if (getAccessor != null)
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetKeyword, getAccessor.Syntax));
            }

            if (setAccessor != null)
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetKeyword, setAccessor.Syntax));
            }

            Syntax = SyntaxFactory.PropertyDeclaration(
                default(SyntaxList <AttributeListSyntax>),
                default(SyntaxTokenList).WithClassMemberVisibilityModifier(visibility),
                type.Syntax,
                null,
                SyntaxFactory.Identifier(name),
                SyntaxFactory.AccessorList(SyntaxFactory.List(accessorSyntax)));
        }
        public static TypeDeclarationSyntax ConvertToReadonly(TypeDeclarationSyntax typeDeclaration, SyntaxGenerator generator)
        {
            var propertiesToSetFrmConstructor = new List <PropertyDeclarationSyntax>();

            var newMembers = typeDeclaration.Members.Select(x =>
            {
                if (x is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Modifiers.Any(SyntaxKind.PublicKeyword) && propertyDeclaration.AccessorList != null)
                {
                    propertiesToSetFrmConstructor.Add(propertyDeclaration);
                    var accessorsWithoutSetter = propertyDeclaration.AccessorList.Accessors.Where(a => a.Kind() != SyntaxKind.SetAccessorDeclaration);
                    return(propertyDeclaration.WithAccessorList(SyntaxFactory.AccessorList(new SyntaxList <AccessorDeclarationSyntax>(accessorsWithoutSetter))));
                }
                return(x);
            }).ToList();

            var newConstructor              = GenerateConstructor(typeDeclaration, generator, propertiesToSetFrmConstructor) as ConstructorDeclarationSyntax;
            var newConstructorParameters    = GetConstructorParameters(newConstructor);
            var allConstructors             = typeDeclaration.Members.Where(x => x.IsKind(SyntaxKind.ConstructorDeclaration)).OfType <ConstructorDeclarationSyntax>();
            var newConstructorAlreadyExists = allConstructors.Any(c => GetConstructorParameters(c).SetEquals(newConstructorParameters));

            if (newConstructorAlreadyExists == false)
            {
                newMembers.Add(newConstructor);
            }

            return(typeDeclaration.WithMembers(newMembers));
        }
        private async Task <Document> ChangePropertySetAsync(Document document, PropertyDeclarationSyntax propertyStatement, CancellationToken cancellationToken, FixType fixType)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var getAcessor = (propertyStatement.AccessorList.Accessors[0].Keyword.Text == "get") ? propertyStatement.AccessorList.Accessors[0] : propertyStatement.AccessorList.Accessors[1];
            var setAcessor = (propertyStatement.AccessorList.Accessors[0].Keyword.Text == "set") ? propertyStatement.AccessorList.Accessors[0] : propertyStatement.AccessorList.Accessors[1];

            var privateprotectedModifier = SyntaxFactory.Token(fixType == FixType.PrivateFix ? SyntaxKind.PrivateKeyword : SyntaxKind.ProtectedKeyword)
                                           .WithAdditionalAnnotations(Formatter.Annotation);

            var modifiers = setAcessor.Modifiers.Add(privateprotectedModifier);

            setAcessor = setAcessor.WithModifiers(modifiers);

            var newProperty = SyntaxFactory.PropertyDeclaration(propertyStatement.Type, propertyStatement.Identifier)
                              .WithModifiers(propertyStatement.Modifiers)
                              .WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List <AccessorDeclarationSyntax>(new AccessorDeclarationSyntax[] { getAcessor, setAcessor })))
                              .WithLeadingTrivia(propertyStatement.GetLeadingTrivia()).WithTrailingTrivia(propertyStatement.GetTrailingTrivia())
                              .WithAdditionalAnnotations(Formatter.Annotation);
            var root = await document.GetSyntaxRootAsync();

            var newRoot     = root.ReplaceNode(propertyStatement, newProperty);
            var newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }
        private SyntaxList <MemberDeclarationSyntax> CreateProperties(IEnumerable <ParameterDefinition> parameters, Dictionary <string, SyntaxTriviaList> leadingTrivia)
        {
            var result = SyntaxFactory.List <MemberDeclarationSyntax>();

            foreach (var parameter in parameters)
            {
                string name        = Common.PascalCasing(parameter.Name);
                var    newProperty = SyntaxFactory.PropertyDeclaration(parameter.Type, name)
                                     .WithAccessorList(
                    SyntaxFactory.AccessorList(
                        SyntaxFactory.List(
                            new[] {
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                }
                            )
                        )
                    )
                                     .WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
                if (leadingTrivia.TryGetValue(name, out var lt))
                {
                    newProperty = newProperty.WithLeadingTrivia(lt);
                }
                result = result.Add(newProperty);
            }
            return(result);
        }
        private static List <PropertyDeclarationSyntax> NewPropertyClassFactory(MethodDeclarationSyntax methodOld)
        {
            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 propertys = new List <PropertyDeclarationSyntax>();

            foreach (ParameterSyntax param in methodOld.ParameterList.Parameters)
            {
                var property = SyntaxFactory.PropertyDeclaration(
                    default(SyntaxList <AttributeListSyntax>),
                    SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }),
                    param.Type,
                    default(ExplicitInterfaceSpecifierSyntax),
                    SyntaxFactory.Identifier(FirstLetteToUpper(param.Identifier.Text)),
                    acessorSyntax);

                propertys.Add(property);
            }

            return(propertys);
        }
示例#7
0
    public static PropertyDeclarationSyntax CreateListAuto(
        string dataType,
        string propertyName,
        bool initializeList = true)
    {
        var propertyDeclaration = SyntaxFactory.PropertyDeclaration(
            SyntaxFactory.GenericName(SyntaxFactory.Identifier(Microsoft.OpenApi.Models.NameConstants.List))
            .WithTypeArgumentList(SyntaxTypeArgumentListFactory.CreateWithOneItem(dataType)),
            SyntaxFactory.Identifier(propertyName))
                                  .AddModifiers(SyntaxTokenFactory.PublicKeyword())
                                  .WithAccessorList(
            SyntaxFactory.AccessorList(
                SyntaxFactory.List(
                    new[]
        {
            SyntaxAccessorDeclarationFactory.Get(),
            SyntaxAccessorDeclarationFactory.Set(),
        })));

        if (initializeList)
        {
            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.ObjectCreationExpression(
                        SyntaxFactory.GenericName(SyntaxFactory.Identifier(Microsoft.OpenApi.Models.NameConstants.List))
                        .WithTypeArgumentList(SyntaxTypeArgumentListFactory.CreateWithOneItem(dataType)))
                    .WithArgumentList(
                        SyntaxFactory.ArgumentList())))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
        }

        return(propertyDeclaration);
    }
示例#8
0
        public void TestSpacingOnNullableDatetimeType()
        {
            var syntaxNode = SyntaxFactory
                             .CompilationUnit()
                             .WithMembers(
                SyntaxFactory.SingletonList <MemberDeclarationSyntax>(
                    SyntaxFactory
                    .ClassDeclaration("C")
                    .WithMembers(
                        SyntaxFactory.SingletonList <MemberDeclarationSyntax>(
                            SyntaxFactory
                            .PropertyDeclaration(
                                SyntaxFactory.NullableType(
                                    SyntaxFactory.ParseTypeName("DateTime")
                                    ),
                                SyntaxFactory.Identifier("P")
                                )
                            .WithAccessorList(SyntaxFactory.AccessorList())
                            )
                        )
                    )
                )
                             .NormalizeWhitespace();

            // no space between DateTime and ?
            Assert.Equal("class C\r\n{\r\n    DateTime? P { }\r\n}", syntaxNode.ToFullString());
        }
示例#9
0
        private static AccessorListSyntax GenerateAccessorList(
            IPropertySymbol property,
            CodeGenerationDestination destination,
            CodeGenerationOptions options,
            ParseOptions parseOptions
            )
        {
            var setAccessorKind =
                property.SetMethod?.IsInitOnly == true
                    ? SyntaxKind.InitAccessorDeclaration
                    : SyntaxKind.SetAccessorDeclaration;
            var accessors = new List <AccessorDeclarationSyntax>
            {
                GenerateAccessorDeclaration(
                    property,
                    property.GetMethod,
                    SyntaxKind.GetAccessorDeclaration,
                    destination,
                    options,
                    parseOptions
                    ),
                GenerateAccessorDeclaration(
                    property,
                    property.SetMethod,
                    setAccessorKind,
                    destination,
                    options,
                    parseOptions
                    ),
            };

            return(accessors[0] == null && accessors[1] == null
              ? null
              : SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList()));
        }
        private async Task <Solution> UsePropertyAsync(Document document, SyntaxNode statement)
        {
            // Create a new property
            // Using property naming conventions
            // Including possible initializers
            // And attributes

            var variableDeclarator  = statement.AncestorsAndSelf().OfType <VariableDeclaratorSyntax>().First();
            var fieldStatement      = variableDeclarator.AncestorsAndSelf().OfType <FieldDeclarationSyntax>().First();
            var variableDeclaration = variableDeclarator.AncestorsAndSelf().OfType <VariableDeclarationSyntax>().First();

            var newProperty = SyntaxFactory.PropertyDeclaration(variableDeclaration.Type, variableDeclarator.Identifier.WithConvention(NamingConvention.UpperCamelCase))
                              .WithAttributeLists(fieldStatement.AttributeLists)
                              .WithModifiers(fieldStatement.Modifiers)
                              .WithAdditionalAnnotations(Formatter.Annotation)
                              .WithAccessorList(
                SyntaxFactory.AccessorList(
                    SyntaxFactory.List(new[]
            {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            })));

            if (variableDeclarator.Initializer != null)
            {
                newProperty = newProperty.WithInitializer(variableDeclarator.Initializer).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            }

            var editor = await DocumentEditor.CreateAsync(document);

            editor.InsertAfter(statement, newProperty);
            editor.RemoveNode(variableDeclarator);
            return(editor.GetChangedDocument().Project.Solution);
        }
示例#11
0
        public void TestSpacingOnNullableIntType()
        {
            var syntaxNode = SyntaxFactory
                             .CompilationUnit()
                             .WithMembers(
                SyntaxFactory.SingletonList <MemberDeclarationSyntax>(
                    SyntaxFactory
                    .ClassDeclaration("C")
                    .WithMembers(
                        SyntaxFactory.SingletonList <MemberDeclarationSyntax>(
                            SyntaxFactory
                            .PropertyDeclaration(
                                SyntaxFactory.NullableType(
                                    SyntaxFactory.PredefinedType(
                                        SyntaxFactory.Token(SyntaxKind.IntKeyword)
                                        )
                                    ),
                                SyntaxFactory.Identifier("P")
                                )
                            .WithAccessorList(SyntaxFactory.AccessorList())
                            )
                        )
                    )
                )
                             .NormalizeWhitespace();

            // no space between int and ?
            Assert.Equal("class C\r\n{\r\n    int? P { }\r\n}", syntaxNode.ToFullString());
        }
        public static ClassDeclarationSyntax AddProperty(this ClassDeclarationSyntax currentClass,
                                                         string name, INamedTypeSymbol type)
        {
            if (currentClass.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                .Any(p => p.Identifier.Text == name))
            {
                // class already has the specified property
                return(currentClass);
            }
            if (currentClass.DescendantNodes().OfType <PropertyDeclarationSyntax>().Count() > 128)
            {
                throw new Exception("Class already has too many properties");
            }
            var typeSentax  = SyntaxFactory.ParseTypeName(type.Name);
            var newProperty = SyntaxFactory.PropertyDeclaration(typeSentax, name)
                              .WithModifiers(
                SyntaxFactory.TokenList(
                    SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                              .WithAccessorList(
                SyntaxFactory.AccessorList(
                    SyntaxFactory.List(
                        new[]
            {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            })));

            return(currentClass.AddMembers(newProperty));
        }
示例#13
0
        public static PropertyDeclarationSyntax AutoPropertyDeclaration(
            IEnumerable <SyntaxKind> modifiers, TypeSyntax type, string propertyName,
            SyntaxKind?setModifier = null, SyntaxKind?getModifier = null, bool isAbstract = false)
        {
            var accesors = new List <AccessorDeclarationSyntax>();

            if (!(isAbstract && getModifier == SyntaxKind.PrivateKeyword))
            {
                accesors.Add(
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithModifiers(TokenList(getModifier))
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }
            if (!(isAbstract && setModifier == SyntaxKind.PrivateKeyword))
            {
                accesors.Add(
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                    .WithModifiers(TokenList(setModifier))
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            return(SyntaxFactory.PropertyDeclaration(type, propertyName)
                   .WithModifiers(TokenList(modifiers))
                   .WithAccessorList(SyntaxFactory.AccessorList(accesors.ToSyntaxList())));
        }
        public StructIndexerWithCodeAnalysis(
            StructMemberVisibilityModifier visibility,
            ITypeReferenceWithCodeAnalysis type,
            IEnumerable <IndexerParameterWithCodeAnalysis> parameters,
            MethodBodyWithCodeAnalysis getAccessor,
            MethodBodyWithCodeAnalysis setAccessor)
            : this()
        {
            var parameterSyntax = parameters.Select(parameter => parameter.Syntax);
            List <AccessorDeclarationSyntax> accessorSyntax = new List <AccessorDeclarationSyntax>();

            if (getAccessor != null)
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetKeyword, getAccessor.Syntax));
            }

            if (setAccessor != null)
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetKeyword, setAccessor.Syntax));
            }

            Syntax = SyntaxFactory.IndexerDeclaration(
                default(SyntaxList <AttributeListSyntax>),
                default(SyntaxTokenList).WithStructMemberVisibilityModifier(visibility),
                type.Syntax,
                null,
                SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameterSyntax)),
                SyntaxFactory.AccessorList(SyntaxFactory.List(accessorSyntax)));
        }
示例#15
0
        public PropertyDeclarationSyntax ConvertMethodsToPropertyWorker(
            DocumentOptionSet documentOptions, ParseOptions parseOptions,
            SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
            string propertyName, bool nameChanged)
        {
            var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax;
            var getAccessor          = CreateGetAccessor(getAndSetMethods, documentOptions, parseOptions);
            var setAccessor          = CreateSetAccessor(semanticModel, generator, getAndSetMethods, documentOptions, parseOptions);

            var property = SyntaxFactory.PropertyDeclaration(
                getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers,
                getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier,
                GetPropertyName(getMethodDeclaration.Identifier, propertyName, nameChanged), accessorList: null);

            IEnumerable <SyntaxTrivia> trivia = getMethodDeclaration.GetLeadingTrivia();
            var setMethodDeclaration          = getAndSetMethods.SetMethodDeclaration;

            if (setMethodDeclaration != null)
            {
                trivia = trivia.Concat(setMethodDeclaration.GetLeadingTrivia());
            }
            property = property.WithLeadingTrivia(trivia.Where(t => !t.IsDirective));

            var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getAccessor));

            if (setAccessor != null)
            {
                accessorList = accessorList.AddAccessors(setAccessor);
            }

            property = property.WithAccessorList(accessorList);

            return(property.WithAdditionalAnnotations(Formatter.Annotation));
        }
示例#16
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))
            }))
                       .WithCloseBraceToken(
                           SyntaxFactory.Token(
                               SyntaxFactory.TriviaList(),
                               SyntaxKind.CloseBraceToken,
                               SyntaxFactory.TriviaList(
                                   new[] { SyntaxFactory.Space, SyntaxFactory.LineFeed })))));
        }
        public PropertyDeclarationSyntax GeneratePropertyForName(FieldInfo fieldInfo, string fieldName, string clsName = "")
        {
            var identifier = SyntaxFactory.Identifier(fieldName);

            SyntaxList <AccessorDeclarationSyntax> accessors = new SyntaxList <AccessorDeclarationSyntax>()
            {
            };

            string cvname = FieldGenerator.GetPrefixedName(fieldName);

            string hookexpr = HookTemplates.FieldUpdateHook(fieldName, clsName, "value");

            accessors = accessors.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, GetAccessorBody(cvname)));
            accessors = accessors.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, SetAccessorBody(cvname, hookexpr)));

            var accessList = SyntaxFactory.AccessorList(accessors);

            var outProp = SyntaxFactory.PropertyDeclaration(
                new SyntaxList <AttributeListSyntax>()
            {
            },
                fieldInfo.Modifiers,
                fieldInfo.Type,
                null,
                identifier,
                accessList
                );

            return(outProp);
        }
示例#18
0
        public override SyntaxNode VisitEventDeclaration(EventDeclarationSyntax node)
        {
            if (!node.Identifier.IsMissing)
            {
                return(node);
            }

            string event_name    = node.Type.ToString();
            string delegate_name = event_name + "_delegate";

            Debug.Assert(pending_ == null);
            pending_ = new ResolveEventArguments(delegate_name, ctx_, members_, node.Modifiers);

            return(SyntaxFactory.EventDeclaration(SyntaxFactory.IdentifierName(delegate_name), SyntaxFactory.Identifier(event_name)).
                   WithModifiers(node.Modifiers).
                   WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List(new AccessorDeclarationSyntax[]
            {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.AddAccessorDeclaration,
                                                  SyntaxFactory.Block(SyntaxFactory.List(new StatementSyntax[]
                {
                    Compiler.EventAccessor(event_name, true)
                }))),

                SyntaxFactory.AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration,
                                                  SyntaxFactory.Block(SyntaxFactory.List(new StatementSyntax[]
                {
                    Compiler.EventAccessor(event_name, false)
                }))),
            }))));
        }
        public void TestCanAccessNonExistentProperty()
        {
            var propertyAccessor = LightupHelpers.CreateSyntaxPropertyAccessor <SyntaxNode, object>(typeof(SyntaxNode), "NonExistentProperty");

            Assert.NotNull(propertyAccessor);
            Assert.Null(propertyAccessor(SyntaxFactory.AccessorList()));
            Assert.Throws <NullReferenceException>(() => propertyAccessor(null));

            var withPropertyAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor <SyntaxNode, object>(typeof(SyntaxNode), "NonExistentProperty");

            Assert.NotNull(withPropertyAccessor);
            Assert.NotNull(withPropertyAccessor(SyntaxFactory.AccessorList(), null));
            Assert.ThrowsAny <NotSupportedException>(() => withPropertyAccessor(SyntaxFactory.AccessorList(), new object()));
            Assert.Throws <NullReferenceException>(() => withPropertyAccessor(null, new object()));

            var separatedListPropertyAccessor = LightupHelpers.CreateSeparatedSyntaxListPropertyAccessor <SyntaxNode, SyntaxNode>(typeof(SyntaxNode), "NonExistentProperty");

            Assert.NotNull(separatedListPropertyAccessor);
            Assert.NotNull(separatedListPropertyAccessor(SyntaxFactory.AccessorList()));
            Assert.Throws <NullReferenceException>(() => separatedListPropertyAccessor(null));

            var separatedListWithPropertyAccessor = LightupHelpers.CreateSeparatedSyntaxListWithPropertyAccessor <SyntaxNode, SyntaxNode>(typeof(SyntaxNode), "NonExistentProperty");

            Assert.NotNull(separatedListWithPropertyAccessor);
            Assert.NotNull(separatedListWithPropertyAccessor(SyntaxFactory.AccessorList(), null));
            Assert.ThrowsAny <NotSupportedException>(() => separatedListWithPropertyAccessor(SyntaxFactory.AccessorList(), new SeparatedSyntaxListWrapper <SyntaxNode> .AutoWrapSeparatedSyntaxList <LiteralExpressionSyntax>(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)))));
            Assert.Throws <NullReferenceException>(() => separatedListWithPropertyAccessor(null, SeparatedSyntaxListWrapper <SyntaxNode> .UnsupportedEmpty));
        }
示例#20
0
        /// <summary>
        ///   Normalizes the <paramref name="declaration" />.
        /// </summary>
        public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax declaration)
        {
            // Nothing to do here for properties without expression bodies
            if (declaration.ExpressionBody == null)
            {
                return(declaration);
            }

            // Nothing to do here for properties not defined in fault effects or for properties that are no overrides of some port
            var propertySymbol = declaration.GetPropertySymbol(SemanticModel);

            if (!propertySymbol.ContainingType.IsFaultEffect(SemanticModel) || !propertySymbol.IsOverride)
            {
                return(declaration);
            }

            var originalDeclaration = declaration;
            var statements          = AsStatementBody(propertySymbol.GetMethod, declaration.ExpressionBody.Expression);

            var getter       = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, statements);
            var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getter));

            declaration = declaration.WithAccessorList(accessorList);

            declaration = declaration.WithExpressionBody(null).WithSemicolonToken(default(SyntaxToken));
            return(declaration.EnsureLineCount(originalDeclaration));
        }
 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);
     }
 }
示例#22
0
        public override SyntaxNode VisitIndexerDeclaration(IndexerDeclarationSyntax node)
        {
            if (node.ExpressionBody == null)
            {
                return(base.VisitIndexerDeclaration(node));
            }

            if (node.AccessorList != null)
            {
                //Invalid indexer declaration. No need to pass it further. Let compiler deal with it directly.
                return(node);
            }

            var blockResumeLocation = GetBlockResumeLocation(node.ExpressionBody);

            node = (IndexerDeclarationSyntax)base.VisitIndexerDeclaration(node);
            return(node.WithExpressionBody(null)
                   .WithAccessorList(
                       SyntaxFactory.AccessorList(
                           new SyntaxList <AccessorDeclarationSyntax>().Add(
                               SyntaxFactory.AccessorDeclaration(
                                   SyntaxKind.GetAccessorDeclaration,
                                   CreateDelegateMethodBody(
                                       node.ExpressionBody.Expression,
                                       blockResumeLocation,
                                       hasReturnValue: true
                                       )
                                   )
                               )
                           )
                       ));
        }
        public PropertyDeclarationSyntax GetPropertyDeclarationSyntax(string propertyName, SyntaxKind underlyingSyntaxKind)
        {
            var typeSyntax = GetTypeSyntax(propertyName, underlyingSyntaxKind);

            return(SyntaxFactory.PropertyDeclaration(
                       SyntaxFactory.GenericName(
                           SyntaxFactory.Identifier("List"))
                       .WithTypeArgumentList(
                           SyntaxFactory.TypeArgumentList(
                               SyntaxFactory.SingletonSeparatedList <TypeSyntax>(typeSyntax))),
                       SyntaxFactory.Identifier(propertyName))
                   .WithModifiers(
                       SyntaxFactory.TokenList(
                           SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                   .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))
            }))));
        }
示例#24
0
        protected TDeclaration WithAccessorList(SemanticModel semanticModel, TDeclaration declaration)
        {
            var expressionBody = GetExpressionBody(declaration);
            var semicolonToken = GetSemicolonToken(declaration);

            // When converting an expression-bodied property to a block body, always attempt to
            // create an accessor with a block body (even if the user likes expression bodied
            // accessors.  While this technically doesn't match their preferences, it fits with
            // the far more likely scenario that the user wants to convert this property into
            // a full property so that they can flesh out the body contents.  If we keep around
            // an expression bodied accessor they'll just have to convert that to a block as well
            // and that means two steps to take instead of one.

            expressionBody.TryConvertToBlock(
                GetSemicolonToken(declaration),
                CreateReturnStatementForExpression(semanticModel, declaration),
                out var block);

            var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);

            accessor = block != null
                ? accessor.WithBody(block)
                : accessor.WithExpressionBody(expressionBody)
                       .WithSemicolonToken(semicolonToken);

            return(WithAccessorList(declaration, SyntaxFactory.AccessorList(
                                        SyntaxFactory.SingletonList(accessor))));
        }
示例#25
0
        protected TDeclaration WithAccessorList(
            TDeclaration declaration, OptionSet options)
        {
            var expressionBody = GetExpressionBody(declaration);
            var semicolonToken = GetSemicolonToken(declaration);

            var preferExpressionBodiedAccessors = options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;

            AccessorDeclarationSyntax accessor;

            if (preferExpressionBodiedAccessors)
            {
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                           .WithExpressionBody(expressionBody)
                           .WithSemicolonToken(semicolonToken);
            }
            else
            {
                var block = expressionBody.ConvertToBlock(
                    GetSemicolonToken(declaration),
                    CreateReturnStatementForExpression(declaration));
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, block);
            }

            return(WithAccessorList(declaration, SyntaxFactory.AccessorList(
                                        SyntaxFactory.SingletonList(accessor))));
        }
        private static PropertyDeclarationSyntax ToStaticGetOnly(PropertyDeclarationSyntax property)
        {
            if (!property.Modifiers.Any(SyntaxKind.StaticKeyword))
            {
                property = property.WithModifiers(property.Modifiers.WithStatic());
            }

            if (property.TryGetSetter(out var setter) &&
                setter.Body == null)
            {
                return(property.RemoveNode(setter, SyntaxRemoveOptions.KeepNoTrivia));
            }

            if (property.ExpressionBody != null)
            {
                return(property
                       .WithInitializer(SyntaxFactory.EqualsValueClause(property.ExpressionBody.Expression))
                       .WithExpressionBody(null)
                       .WithAccessorList(
                           SyntaxFactory.AccessorList(
                               SyntaxFactory.SingletonList(
                                   SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                   .WithSemicolonToken(
                                       SyntaxFactory.Token(SyntaxKind.SemicolonToken))))));
            }

            return(property);
        }
示例#27
0
        private static PropertyDeclarationSyntax ExpandProperty(PropertyDeclarationSyntax property, string backingFieldName)
        {
            AccessorDeclarationSyntax getter, setter;

            if (!ExpansionChecker.TryGetAccessors(property, out getter, out setter))
            {
                throw new ArgumentException();
            }

            if (getter.Body == null)
            {
                var returnFieldStatement = SyntaxFactory.ParseStatement(string.Format("return {0};", backingFieldName));
                getter = getter
                         .WithBody(SyntaxFactory.Block(SyntaxFactory.SingletonList(returnFieldStatement)));
            }

            getter = getter
                     .WithSemicolonToken(default(SyntaxToken));

            var setPropertyStatement = SyntaxFactory.ParseStatement(string.Format("SetProperty(ref {0}, value, \"{1}\");", backingFieldName, property.Identifier.ValueText));

            setter = setter
                     .WithBody(SyntaxFactory.Block(SyntaxFactory.SingletonList(setPropertyStatement)))
                     .WithSemicolonToken(default(SyntaxToken));

            var newProperty = property
                              .WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getter, setter })))
                              .WithAdditionalAnnotations(Formatter.Annotation);

            return(newProperty);
        }
示例#28
0
        public AbstractIndexerWithCodeAnalysis(
            ClassMemberVisibilityModifier visibility,
            ITypeReferenceWithCodeAnalysis type,
            IEnumerable <IndexerParameterWithCodeAnalysis> parameters,
            AccessorTypes accessors)
            : this()
        {
            var parameterSyntax = parameters.Select(parameter => parameter.Syntax);
            List <AccessorDeclarationSyntax> accessorSyntax = new List <AccessorDeclarationSyntax>();

            if (accessors.HasFlag(AccessorTypes.Get))
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetKeyword));
            }

            if (accessors.HasFlag(AccessorTypes.Set))
            {
                accessorSyntax.Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetKeyword));
            }

            Syntax = SyntaxFactory.IndexerDeclaration(
                default(SyntaxList <AttributeListSyntax>),
                default(SyntaxTokenList).WithClassMemberVisibilityModifier(visibility).Add(SyntaxKind.AbstractKeyword),
                type.Syntax,
                null,
                SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameterSyntax)),
                SyntaxFactory.AccessorList(SyntaxFactory.List(accessorSyntax)));
        }
示例#29
0
        private SyntaxNode VisitBasePropertyDeclaration(BasePropertyDeclarationSyntax node)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }
            //HACK: Must cast to dynamic because expression body is only defined on subclasses
            if (((dynamic)node).ExpressionBody == null)
            {
                return(node);
            }

            var expr      = ((dynamic)node).ExpressionBody.Expression;
            var statement = SyntaxFactory.ReturnStatement(expr);

            var getter = SyntaxFactory.AccessorDeclaration(
                SyntaxKind.GetAccessorDeclaration,
                SyntaxFactory.Block(statement));

            var accessors = SyntaxFactory.AccessorList(
                SyntaxFactory.List <AccessorDeclarationSyntax>()
                .Add(getter));

            return(nodeRewriter
                   .Try(node, n => ((dynamic)n).WithExpressionBody(null)
                        .WithAccessorList(accessors))
                   .Result);
        }
        private async Task <Document> HandleIndexerDeclaration(IndexerDeclarationSyntax declaration, Document document, CancellationToken cancellationToken)
        {
            var returnStatement = SyntaxFactory.ReturnStatement(
                returnKeyword: SyntaxFactory.Token(SyntaxKind.ReturnKeyword),
                expression: declaration.ExpressionBody.Expression,
                semicolonToken: declaration.SemicolonToken);

            var accessorDeclaration = SyntaxFactory.AccessorDeclaration(
                kind: SyntaxKind.GetAccessorDeclaration,
                body: SyntaxFactory.Block(returnStatement));

            var newDeclaration = declaration
                                 .WithAccessorList(
                SyntaxFactory.AccessorList(
                    SyntaxFactory.SingletonList(accessorDeclaration)))
                                 .WithExpressionBody(null)
                                 .WithSemicolonToken(default(SyntaxToken))
                                 .WithAdditionalAnnotations(Formatter.Annotation);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = oldRoot.ReplaceNode(declaration, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }