Ejemplo n.º 1
0
        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());
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
 public static BracketedParameterListSyntax GenerateBracketedParameterList(
     ImmutableArray <IParameterSymbol> parameterDefinitions,
     bool isExplicit,
     CSharpCodeGenerationContextInfo info)
 {
     return(GenerateBracketedParameterList((IList <IParameterSymbol>)parameterDefinitions, isExplicit, info));
 }
Ejemplo n.º 4
0
 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));
     }
 }
Ejemplo n.º 5
0
        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());
        }
Ejemplo n.º 6
0
        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)));
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 8
0
        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));
Ejemplo n.º 9
0
        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)))));
 }
Ejemplo n.º 11
0
        public static ParameterListSyntax GenerateParameterList(
            IEnumerable <IParameterSymbol> parameterDefinitions,
            bool isExplicit,
            CSharpCodeGenerationContextInfo info)
        {
            var parameters = GetParameters(parameterDefinitions, isExplicit, info);

            return(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)));
        }
Ejemplo n.º 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))));
        }
Ejemplo n.º 13
0
 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));
 }
Ejemplo n.º 14
0
        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()));
        }
Ejemplo n.º 15
0
        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)));
        }
Ejemplo n.º 16
0
 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())))))));
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 18
0
        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));
        }
Ejemplo n.º 19
0
        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))));
        }
Ejemplo n.º 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()));
        }
Ejemplo n.º 21
0
        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)));
        }
Ejemplo n.º 22
0
        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));
        }
Ejemplo n.º 23
0
        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));
        }
Ejemplo n.º 24
0
        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));
        }
Ejemplo n.º 25
0
        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,
Ejemplo n.º 26
0
        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)));
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 28
0
        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));
        }
Ejemplo n.º 29
0
        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()));
        }
Ejemplo n.º 30
0
        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));
        }