private static SyntaxTokenList GenerateModifiers(
            IEventSymbol @event, CodeGenerationDestination destination, CSharpCodeGenerationContextInfo info)
        {
            var tokens = ArrayBuilder <SyntaxToken> .GetInstance();

            // Most modifiers not allowed if we're an explicit impl.
            if ([email protected]())
            {
                // If we're generating into an interface, then allow modifiers for static abstract members
                if (destination is CodeGenerationDestination.InterfaceType)
                {
                    if (@event.IsStatic)
                    {
                        tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));

                        // We only generate the abstract keyword in interfaces for static abstract members
                        if (@event.IsAbstract)
                        {
                            tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
                        }
                    }
                }
                else
                {
                    AddAccessibilityModifiers(@event.DeclaredAccessibility, tokens, info, Accessibility.Private);

                    if (@event.IsStatic)
                    {
                        tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
                    }

                    // An event is readonly if its accessors are readonly.
                    // If one accessor is readonly and the other one is not,
                    // the event is malformed and cannot be properly displayed.
                    // See https://github.com/dotnet/roslyn/issues/34213
                    // Don't show the readonly modifier if the containing type is already readonly
                    if (@event.AddMethod?.IsReadOnly == true && [email protected])
                    {
                        tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
                    }

                    if (@event.IsAbstract)
                    {
                        tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
                    }

                    if (@event.IsOverride)
                    {
                        tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
                    }
                }
            }

            if (CodeGenerationEventInfo.GetIsUnsafe(@event))
            {
                tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
            }

            return(tokens.ToSyntaxTokenListAndFree());
        }
        private static AttributeSyntax?TryGenerateAttribute(AttributeData attribute, CSharpCodeGenerationContextInfo info)
        {
            if (IsCompilerInternalAttribute(attribute))
            {
                return(null);
            }

            if (!info.Context.MergeAttributes)
            {
                var reusableSyntax = GetReuseableSyntaxNodeForAttribute <AttributeSyntax>(attribute, info);
                if (reusableSyntax != null)
                {
                    return(reusableSyntax);
                }
            }

            if (attribute.AttributeClass == null)
            {
                return(null);
            }

            var attributeArguments = GenerateAttributeArgumentList(attribute);

            return(attribute.AttributeClass.GenerateTypeSyntax() is NameSyntax nameSyntax
                ? SyntaxFactory.Attribute(nameSyntax, attributeArguments)
                : null);
        }
 public static BracketedParameterListSyntax GenerateBracketedParameterList(
     ImmutableArray <IParameterSymbol> parameterDefinitions,
     bool isExplicit,
     CSharpCodeGenerationContextInfo info)
 {
     return(GenerateBracketedParameterList((IList <IParameterSymbol>)parameterDefinitions, isExplicit, info));
 }
 public static SyntaxList <AttributeListSyntax> GenerateAttributeLists(
     ImmutableArray <AttributeData> attributes,
     CSharpCodeGenerationContextInfo info,
     SyntaxToken?target = null)
 {
     if (info.Context.MergeAttributes)
     {
         var attributeNodes =
             attributes.OrderBy(a => a.AttributeClass?.Name)
             .Select(a => TryGenerateAttribute(a, info))
             .WhereNotNull().ToList();
         return(attributeNodes.Count == 0
             ? default
             : SyntaxFactory.SingletonList(SyntaxFactory.AttributeList(
                                               target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : null,
                                               SyntaxFactory.SeparatedList(attributeNodes))));
     }
     else
     {
         var attributeDeclarations =
             attributes.OrderBy(a => a.AttributeClass?.Name)
             .Select(a => TryGenerateAttributeDeclaration(a, target, info))
             .WhereNotNull().ToList();
         return(attributeDeclarations.Count == 0
             ? default
             : SyntaxFactory.List <AttributeListSyntax>(attributeDeclarations));
     }
 }
        private static SyntaxTokenList GenerateModifiers(IFieldSymbol field, CSharpCodeGenerationContextInfo info)
        {
            var tokens = ArrayBuilder <SyntaxToken> .GetInstance();

            AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, info, Accessibility.Private);
            if (field.IsConst)
            {
                tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword));
            }
            else
            {
                if (field.IsStatic)
                {
                    tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
                }

                if (field.IsReadOnly)
                {
                    tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
                }

                if (field.IsRequired)
                {
                    tokens.Add(SyntaxFactory.Token(SyntaxKind.RequiredKeyword));
                }
            }

            if (CodeGenerationFieldInfo.GetIsUnsafe(field))
            {
                tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
            }

            return(tokens.ToSyntaxTokenListAndFree());
        }
        public static FieldDeclarationSyntax GenerateFieldDeclaration(
            IFieldSymbol field, CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken)
        {
            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <FieldDeclarationSyntax>(field, info);

            if (reusableSyntax != null)
            {
                return(reusableSyntax);
            }

            var initializer = CodeGenerationFieldInfo.GetInitializer(field) is ExpressionSyntax initializerNode
                ? SyntaxFactory.EqualsValueClause(initializerNode)
                : GenerateEqualsValue(field);

            var fieldDeclaration = SyntaxFactory.FieldDeclaration(
                AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), info),
                GenerateModifiers(field, info),
                SyntaxFactory.VariableDeclaration(
                    field.Type.GenerateTypeSyntax(),
                    SyntaxFactory.SingletonSeparatedList(
                        AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer)))));

            return(AddFormatterAndCodeGeneratorAnnotationsTo(
                       ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, info, cancellationToken)));
        }
Exemple #7
0
        private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var hasNoBody = !info.Context.GenerateMethodBodies || method.IsExtern || method.IsAbstract;

            var operatorSyntaxKind = SyntaxFacts.GetOperatorKind(method.MetadataName);

            if (operatorSyntaxKind == SyntaxKind.None)
            {
                throw new ArgumentException(string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method));
            }

            var operatorToken = SyntaxFactory.Token(operatorSyntaxKind);
            var checkedToken  = SyntaxFacts.IsCheckedOperator(method.MetadataName)
                ? SyntaxFactory.Token(SyntaxKind.CheckedKeyword)
                : default;

            var operatorDecl = SyntaxFactory.OperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), info),
                modifiers: GenerateModifiers(method, destination, hasNoBody),
                returnType: method.ReturnType.GenerateTypeSyntax(),
                explicitInterfaceSpecifier: GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations),
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                checkedKeyword: checkedToken,
                operatorToken: operatorToken,
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, info: info),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                expressionBody: null,
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());

            operatorDecl = UseExpressionBodyIfDesired(info, operatorDecl);
            return(operatorDecl);
        }
        private static RecordDeclarationSyntax GenerateRecordMembers(
            ICodeGenerationService service,
            CSharpCodeGenerationContextInfo info,
            RecordDeclarationSyntax recordDeclaration,
            ImmutableArray <ISymbol> members,
            CancellationToken cancellationToken)
        {
            if (!info.Context.GenerateMembers)
            {
                members = ImmutableArray <ISymbol> .Empty;
            }

            // For a record, add record parameters if we have a primary constructor.
            var primaryConstructor = members.OfType <IMethodSymbol>().FirstOrDefault(m => CodeGenerationConstructorInfo.GetIsPrimaryConstructor(m));

            if (primaryConstructor != null)
            {
                var parameterList = ParameterGenerator.GenerateParameterList(primaryConstructor.Parameters, isExplicit: false, info);
                recordDeclaration = recordDeclaration.WithParameterList(parameterList);

                // remove the primary constructor from the list of members to generate.
                members = members.Remove(primaryConstructor);

                // remove any fields/properties that were created by the primary constructor
                members = members.WhereAsArray(m => m is not IPropertySymbol and not IFieldSymbol || !primaryConstructor.Parameters.Any(static (p, m) => p.Name == m.Name, m));
        private static MemberDeclarationSyntax GeneratePropertyDeclaration(
            IPropertySymbol property, CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode
                ? SyntaxFactory.EqualsValueClause(initializerNode)
                : null;

            var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);

            var accessorList = GenerateAccessorList(property, destination, info);

            var propertyDeclaration = SyntaxFactory.PropertyDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), info),
                modifiers: GenerateModifiers(property, destination, info),
                type: GenerateTypeSyntax(property),
                explicitInterfaceSpecifier: explicitInterfaceSpecifier,
                identifier: property.Name.ToIdentifierToken(),
                accessorList: accessorList,
                expressionBody: null,
                initializer: initializer);

            propertyDeclaration = UseExpressionBodyIfDesired(info, propertyDeclaration);

            return(AddFormatterAndCodeGeneratorAnnotationsTo(
                       AddAnnotationsTo(property, propertyDeclaration)));
        }
 public static TypeParameterListSyntax?GenerateTypeParameterList(
     ImmutableArray <ITypeParameterSymbol> typeParameters, CSharpCodeGenerationContextInfo info)
 {
     return(typeParameters.Length == 0
         ? null
         : SyntaxFactory.TypeParameterList(
                SyntaxFactory.SeparatedList(typeParameters.Select(t => GenerateTypeParameter(t, info)))));
 }
        public static ParameterListSyntax GenerateParameterList(
            IEnumerable <IParameterSymbol> parameterDefinitions,
            bool isExplicit,
            CSharpCodeGenerationContextInfo info)
        {
            var parameters = GetParameters(parameterDefinitions, isExplicit, info);

            return(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)));
        }
Exemple #12
0
        internal static ConversionOperatorDeclarationSyntax GenerateConversionDeclaration(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateConversionDeclarationWorker(method, destination, info);

            return(AddFormatterAndCodeGeneratorAnnotationsTo(AddAnnotationsTo(method,
                                                                              ConditionallyAddDocumentationCommentTo(declaration, method, info, cancellationToken))));
        }
 public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration(
     ICodeGenerationService service,
     SyntaxNode declaration,
     IList <ISymbol> newMembers,
     CSharpCodeGenerationContextInfo info,
     CancellationToken cancellationToken)
 {
     declaration = RemoveAllMembers(declaration);
     declaration = service.AddMembers(declaration, newMembers, info, cancellationToken);
     return(AddFormatterAndCodeGeneratorAnnotationsTo(declaration));
 }
        private static AccessorListSyntax GenerateAccessorList(
            IEventSymbol @event, CodeGenerationDestination destination, CSharpCodeGenerationContextInfo info)
        {
            var accessors = new List <AccessorDeclarationSyntax?>
            {
                GenerateAccessorDeclaration(@event, @event.AddMethod, SyntaxKind.AddAccessorDeclaration, destination, info),
                GenerateAccessorDeclaration(@event, @event.RemoveMethod, SyntaxKind.RemoveAccessorDeclaration, destination, info),
            };

            return(SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList()));
        }
        public static BracketedParameterListSyntax GenerateBracketedParameterList(
            IEnumerable <IParameterSymbol> parameterDefinitions,
            bool isExplicit,
            CSharpCodeGenerationContextInfo info)
        {
            // Bracketed parameter lists come from indexers.  Those don't have type parameters, so we
            // could never have a typeParameterMapping.
            var parameters = GetParameters(parameterDefinitions, isExplicit, info);

            return(SyntaxFactory.BracketedParameterList(
                       parameters: SyntaxFactory.SeparatedList(parameters)));
        }
 private static MemberDeclarationSyntax GenerateEventFieldDeclaration(
     IEventSymbol @event, CodeGenerationDestination destination, CSharpCodeGenerationContextInfo info)
 {
     return(AddFormatterAndCodeGeneratorAnnotationsTo(
                AddAnnotationsTo(@event,
                                 SyntaxFactory.EventFieldDeclaration(
                                     AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), info),
                                     GenerateModifiers(@event, destination, info),
                                     SyntaxFactory.VariableDeclaration(
                                         @event.Type.GenerateTypeSyntax(),
                                         SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(@event.Name.ToIdentifierToken())))))));
 }
Exemple #17
0
        internal static TypeDeclarationSyntax AddConversionTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var methodDeclaration = GenerateConversionDeclaration(method, GetDestination(destination), info, cancellationToken);
            var members           = Insert(destination.Members, methodDeclaration, info, availableIndices, after: LastOperator);

            return(AddMembersTo(destination, members, cancellationToken));
        }
        private static AccessorDeclarationSyntax?GenerateAccessorDeclaration(
            IEventSymbol @event,
            IMethodSymbol?accessor,
            SyntaxKind kind,
            CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var hasBody = info.Context.GenerateMethodBodies && HasAccessorBodies(@event, destination, accessor);

            return(accessor == null
                ? null
                : GenerateAccessorDeclaration(accessor, kind, hasBody));
        }
        private static MemberDeclarationSyntax GenerateEventDeclarationWorker(
            IEventSymbol @event, CodeGenerationDestination destination, CSharpCodeGenerationContextInfo info)
        {
            var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(@event.ExplicitInterfaceImplementations);

            return(AddFormatterAndCodeGeneratorAnnotationsTo(SyntaxFactory.EventDeclaration(
                                                                 attributeLists: AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), info),
                                                                 modifiers: GenerateModifiers(@event, destination, info),
                                                                 type: @event.Type.GenerateTypeSyntax(),
                                                                 explicitInterfaceSpecifier: explicitInterfaceSpecifier,
                                                                 identifier: @event.Name.ToIdentifierToken(),
                                                                 accessorList: GenerateAccessorList(@event, destination, info))));
        }
Exemple #20
0
        internal static BaseNamespaceDeclarationSyntax AddMethodTo(
            BaseNamespaceDeclarationSyntax destination,
            IMethodSymbol method,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, info, cancellationToken);

            var members = Insert(destination.Members, declaration, info, availableIndices, after: LastMethod);

            return(destination.WithMembers(members.ToSyntaxList()));
        }
        private static AttributeListSyntax?TryGenerateAttributeDeclaration(
            AttributeData attribute, SyntaxToken?target, CSharpCodeGenerationContextInfo info)
        {
            var attributeSyntax = TryGenerateAttribute(attribute, info);

            return(attributeSyntax == null
                ? null
                : SyntaxFactory.AttributeList(
                       target.HasValue
                        ? SyntaxFactory.AttributeTargetSpecifier(target.Value)
                        : null,
                       SyntaxFactory.SingletonSeparatedList(attributeSyntax)));
        }
        private static SyntaxNode GetDeclarationSyntaxWithoutMembers(
            INamespaceSymbol @namespace,
            INamespaceSymbol innermostNamespace,
            string name,
            CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <SyntaxNode>(@namespace, info);

            return(reusableSyntax == null
                ? GenerateNamespaceDeclarationWorker(name, innermostNamespace, destination, info)
                : RemoveAllMembers(reusableSyntax));
        }
        public static TypeDeclarationSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            TypeDeclarationSyntax destination,
            INamedTypeSymbol namedType,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), info, cancellationToken);
            var members     = Insert(destination.Members, declaration, info, availableIndices);

            return(AddMembersTo(destination, members, cancellationToken));
        }
        public static CompilationUnitSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            CompilationUnitSyntax destination,
            INamedTypeSymbol namedType,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, info, cancellationToken);
            var members     = Insert(destination.Members, declaration, info, availableIndices);

            return(destination.WithMembers(members));
        }
        internal static DestructorDeclarationSyntax GenerateDestructorDeclaration(
            IMethodSymbol destructor, CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken)
        {
            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <DestructorDeclarationSyntax>(destructor, info);

            if (reusableSyntax != null)
            {
                return(reusableSyntax);
            }

            var hasNoBody = !info.Context.GenerateMethodBodies;

            var declaration = SyntaxFactory.DestructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(destructor.GetAttributes(), info),
                modifiers: default,
        internal static ParameterSyntax GetParameter(IParameterSymbol p, CSharpCodeGenerationContextInfo info, bool isExplicit, bool isFirstParam, bool seenOptional)
        {
            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <ParameterSyntax>(p, info);

            if (reusableSyntax != null)
            {
                return(reusableSyntax);
            }

            return(SyntaxFactory.Parameter(p.Name.ToIdentifierToken())
                   .WithAttributeLists(GenerateAttributes(p, isExplicit, info))
                   .WithModifiers(GenerateModifiers(p, isFirstParam))
                   .WithType(p.Type.GenerateTypeSyntax())
                   .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)));
        }
Exemple #27
0
        internal static TypeDeclarationSyntax AddMethodTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var methodDeclaration = GenerateMethodDeclaration(
                method, GetDestination(destination), info, cancellationToken);

            // Create a clone of the original type with the new method inserted.
            var members = Insert(destination.Members, methodDeclaration, info, availableIndices, after: LastMethod);

            return(AddMembersTo(destination, members, cancellationToken));
        }
        public static BaseNamespaceDeclarationSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            BaseNamespaceDeclarationSyntax destination,
            INamedTypeSymbol namedType,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, info, cancellationToken);
            var members     = Insert(destination.Members, declaration, info, availableIndices);

            return(ConditionallyAddFormattingAnnotationTo(
                       destination.WithMembers(members),
                       members));
        }
        private static AccessorListSyntax?GenerateAccessorList(
            IPropertySymbol property, CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var setAccessorKind = property.SetMethod?.IsInitOnly == true ? SyntaxKind.InitAccessorDeclaration : SyntaxKind.SetAccessorDeclaration;
            var accessors       = new[]
            {
                GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, info),
                GenerateAccessorDeclaration(property, property.SetMethod, setAccessorKind, destination, info),
            };

            return(accessors[0] == null && accessors[1] == null
                ? null
                : SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList()));
        }
        internal static TypeDeclarationSyntax AddDestructorTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol destructor,
            CSharpCodeGenerationContextInfo info,
            IList <bool>?availableIndices,
            CancellationToken cancellationToken)
        {
            var destructorDeclaration = GenerateDestructorDeclaration(destructor, info, cancellationToken);

            // Generate after the last constructor, or after the last field, or at the start of the
            // type.
            var members = Insert(destination.Members, destructorDeclaration, info,
                                 availableIndices, after: LastConstructorOrField, before: FirstMember);

            return(AddMembersTo(destination, members, cancellationToken));
        }