コード例 #1
0
ファイル: BasicTypes.cs プロジェクト: jaredpar/random
        internal static AttributeSyntax UpdateAttribute(AttributeSyntax node, int id, string url)
        {
            var descriptionArg = SyntaxFactory.SimpleArgument(
                SyntaxFactory.LiteralExpression(
                    SyntaxKind.StringLiteralExpression,
                    SyntaxFactory.Literal(value: url).WithLeadingTrivia(SyntaxFactory.Space)));
            var idArg = SyntaxFactory.SimpleArgument(
                SyntaxFactory.LiteralExpression(
                    SyntaxKind.NumericLiteralExpression,
                    SyntaxFactory.Literal(value: id)));

            var list = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(new[] { idArg, descriptionArg }));
            return node.WithArgumentList(list);
        }
コード例 #2
0
        private static Task <Document> SpecifyNameAsync(
            Document document,
            AttributeSyntax attribute,
            CancellationToken cancellationToken)
        {
            AttributeArgumentSyntax newAttributeArgument = AttributeArgument(
                NameEquals("Name"),
                NameOfExpression(
                    IdentifierName(attribute.FirstAncestor <ClassDeclarationSyntax>().Identifier.WithNavigationAnnotation())));

            AttributeArgumentListSyntax argumentList = attribute.ArgumentList;

            SeparatedSyntaxList <AttributeArgumentSyntax> arguments = argumentList.Arguments.Add(newAttributeArgument);

            AttributeArgumentListSyntax newArgumentList = argumentList.WithArguments(arguments);

            AttributeSyntax newAttribute = attribute.WithArgumentList(newArgumentList);

            return(document.ReplaceNodeAsync(attribute, newAttribute, cancellationToken));
        }
コード例 #3
0
        public static AttributeSyntax ConvertArgumentsToString(this AttributeSyntax node, List <Diagnostic> diagnostics = null, Location location = null)
        {
            var newList = new SeparatedSyntaxList <AttributeArgumentSyntax>();

            foreach (var entry in node.ArgumentList.Arguments)
            {
                if (entry.Expression.Kind() != SyntaxKind.StringLiteralExpression)
                {
                    var existingToken = entry.Expression.GetFirstToken();
                    diagnostics?.Add(Diagnostic.Create(DiagnosticsDescriptors.ConvertedArgumentValueToString, node.GetLocation(location), existingToken.ValueText));

                    var newEntry = entry.WithExpression(ToLiteralExpression(existingToken.Text, s_singleWhitespace, SyntaxTriviaList.Empty));
                    newList = newList.Add(newEntry);
                }
                else
                {
                    newList = newList.Add(entry);
                }
            }

            return(node.WithArgumentList(SyntaxFactory.AttributeArgumentList(newList)));
        }
コード例 #4
0
        protected AttributeSyntax ResolveAttribute(Type attribute, params ExpressionSyntax[] paramz)
        {
            Debug.Assert(typeof(Attribute).IsAssignableFrom(attribute));

            AttributeSyntax attr = Attribute
                                   (
                (NameSyntax)ResolveType(MetadataTypeInfo.CreateFrom(attribute))
                                   );

            if (paramz.Length > 0)
            {
                attr = attr.WithArgumentList
                       (
                    argumentList: AttributeArgumentList
                    (
                        arguments: paramz.ToSyntaxList(AttributeArgument)
                    )
                       );
            }

            return(attr);
        }
コード例 #5
0
            /// <inheritdoc />
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                CancellationToken token  = cancellationToken;
                INamedTypeSymbol  symbol = semanticModel.GetDeclaredSymbol(node, token);

                if (symbol == null)
                {
                    return(node);
                }

                int totalAttributes = 0;
                ImmutableArray <AttributeData> attrs = symbol.GetAttributes();

                if (attrs.IsDefaultOrEmpty)
                {
                    return(node);
                }

                SyntaxList <AttributeListSyntax> attributeLists = node.AttributeLists;

                for (int i = 0; i < attributeLists.Count; i++)
                {
                    AttributeListSyntax attributeList = attributeLists[i];
                    SeparatedSyntaxList <AttributeSyntax> attributes = attributeList.Attributes;

                    for (int j = 0; j < attributes.Count; j++, totalAttributes++)
                    {
                        AttributeSyntax attr     = attributes[j];
                        string          attrName = attr.Name.ToString();

                        if (attrName == "Component" || attrName == nameof(ComponentAttribute))
                        {
                            // There is a 'Component' attribute: Specify its content.
                            string contentStr = node.ToString();

                            // TODO: Use b64 and serialization
                            // It works, except Roslyn <= 2.0.0 has a bug with serialization
                            //using (MemoryStream ms = new MemoryStream())
                            //{
                            //    node.SerializeTo(ms, cancellationToken);

                            //    contentStr = ms.TryGetBuffer(out ArraySegment<byte> buffer)
                            //        ? Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count)
                            //        : Convert.ToBase64String(ms.ToArray());
                            //}

                            AttributeArgumentSyntax contentArg = SyntaxFactory.AttributeArgument(
                                SyntaxFactory.LiteralExpression(
                                    SyntaxKind.StringLiteralExpression,
                                    SyntaxFactory.Literal(contentStr)
                                    )
                                );

                            node = node.WithAttributeLists(
                                attributeLists.Replace(
                                    attributeList,
                                    attributeList.WithAttributes(
                                        attributes.Replace(attr, attr.WithArgumentList(
                                                               SyntaxFactory.AttributeArgumentList().AddArguments(contentArg)
                                                               ))
                                        )
                                    )
                                );
                        }

                        // Maybe a component?
                        AttributeData attrData = attrs[totalAttributes];

                        if (attrData.AttributeClass.MetadataName == nameof(CopyFromAttribute))
                        {
                            // CopyFrom component: copy members
                            node = CopyMembers(node, attrData, token);
                        }
                        else if (InheritsCompositionAttribute(attrData.AttributeClass))
                        {
                            // Component: apply it
                            CompositionAttribute builtAttr = attrData.Construct <CompositionAttribute>();

                            try
                            {
                                node = builtAttr.Component.Apply(node, symbol, token);

                                if (node == null)
                                {
                                    throw new NullReferenceException("A component cannot return null.");
                                }
                            }
                            catch (Exception e)
                            {
                                throw new DiagnosticException($"Error applying the {builtAttr.Component} component.", e, attr.GetLocation());
                            }
                        }
                    }
                }

                return(node);
            }
コード例 #6
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                if (!string.Equals(diagnostic.Id, JsonObjectOptInAnalyzer.DiagnosticId, StringComparison.Ordinal))
                {
                    continue;
                }

                var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

                AttributeSyntax syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan) as AttributeSyntax;
                if (syntax == null)
                {
                    continue;
                }

                ExpressionSyntax expression =
                    SyntaxFactory.ParseExpression("global::Newtonsoft.Json.MemberSerialization.OptIn")
                    .WithAdditionalAnnotations(Simplifier.Annotation);

                AttributeSyntax             newAttribute = null;
                AttributeArgumentListSyntax argumentList = syntax.ArgumentList;
                if (argumentList != null)
                {
                    AttributeArgumentSyntax existingArgument = null;
                    foreach (var attributeArgument in argumentList.Arguments)
                    {
                        if (string.Equals("MemberSerialization", attributeArgument.NameEquals?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            existingArgument = attributeArgument;
                            break;
                        }
                    }

                    if (existingArgument == null)
                    {
                        SemanticModel semanticModel = null;
                        foreach (var attributeArgument in argumentList.Arguments)
                        {
                            // this time only interested in arguments (no NameEquals clause)
                            if (attributeArgument.NameEquals != null)
                            {
                                continue;
                            }

                            if (string.Equals("memberSerialization", attributeArgument.NameColon?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                            {
                                existingArgument = attributeArgument;
                                break;
                            }

                            if (attributeArgument.NameColon != null)
                            {
                                continue;
                            }

                            if (semanticModel == null)
                            {
                                semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
                            }

                            if (IsMemberSerializationArgument(semanticModel, attributeArgument.Expression, context.CancellationToken))
                            {
                                existingArgument = attributeArgument;
                                break;
                            }
                        }
                    }

                    if (existingArgument != null)
                    {
                        var newArgument =
                            existingArgument
                            .WithExpression(expression)
                            .WithTriviaFrom(existingArgument)
                            .WithoutFormatting();

                        newAttribute = syntax.ReplaceNode(existingArgument, newArgument);
                    }
                }

                if (newAttribute == null)
                {
                    if (argumentList == null)
                    {
                        argumentList = SyntaxFactory.AttributeArgumentList();
                    }

                    NameEqualsSyntax nameEquals;
                    if (argumentList.Arguments.Any(argument => argument.NameEquals == null))
                    {
                        nameEquals = SyntaxFactory.NameEquals("MemberSerialization");
                    }
                    else
                    {
                        nameEquals = null;
                    }

                    AttributeArgumentSyntax defaultValueArgument = SyntaxFactory.AttributeArgument(nameEquals, null, expression);

                    argumentList = argumentList.AddArguments(defaultValueArgument);
                    newAttribute = syntax.WithArgumentList(argumentList);
                }

                SyntaxNode newRoot     = documentRoot.ReplaceNode(syntax, newAttribute);
                Document   newDocument = context.Document.WithSyntaxRoot(newRoot);
                context.RegisterCodeFix(CodeAction.Create("Add MemberSerialization.OptIn", _ => Task.FromResult(newDocument)), diagnostic);
            }
        }
コード例 #7
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                if (!string.Equals(diagnostic.Id, JsonPropertyDefaultValueHandlingAnalyzer.DiagnosticId, StringComparison.Ordinal))
                {
                    continue;
                }

                var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

                AttributeSyntax syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan) as AttributeSyntax;
                if (syntax == null)
                {
                    continue;
                }

                ExpressionSyntax expression =
                    SyntaxFactory.ParseExpression("global::Newtonsoft.Json.DefaultValueHandling.Ignore")
                    .WithAdditionalAnnotations(Simplifier.Annotation);

                AttributeSyntax             newAttribute = null;
                AttributeArgumentListSyntax argumentList = syntax.ArgumentList;
                if (argumentList != null)
                {
                    AttributeArgumentSyntax existingArgument = null;
                    foreach (var attributeArgument in argumentList.Arguments)
                    {
                        if (string.Equals("DefaultValueHandling", attributeArgument.NameEquals?.Name?.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            existingArgument = attributeArgument;
                            break;
                        }
                    }

                    if (existingArgument != null)
                    {
                        var newArgument =
                            existingArgument
                            .WithExpression(expression)
                            .WithTriviaFrom(existingArgument)
                            .WithoutFormatting();

                        newAttribute = syntax.ReplaceNode(existingArgument, newArgument);
                    }
                }

                if (newAttribute == null)
                {
                    NameEqualsSyntax nameEquals = SyntaxFactory.NameEquals("DefaultValueHandling");

                    AttributeArgumentSyntax defaultValueArgument = SyntaxFactory.AttributeArgument(nameEquals, null, expression);

                    if (argumentList == null)
                    {
                        argumentList = SyntaxFactory.AttributeArgumentList();
                    }

                    argumentList = argumentList.AddArguments(defaultValueArgument);

                    newAttribute = syntax.WithArgumentList(argumentList);
                }

                SyntaxNode newRoot     = documentRoot.ReplaceNode(syntax, newAttribute);
                Document   newDocument = context.Document.WithSyntaxRoot(newRoot);
                context.RegisterCodeFix(CodeAction.Create("Add DefaultValueHandling.Ignore", _ => Task.FromResult(newDocument)), diagnostic);
            }
        }
コード例 #8
0
    /// <summary>
    ///   Takes an OperationContract attribute node and returns a new node with 'AsyncPattern = true'
    /// </summary>
    /// <param name="originalAttribute"></param>
    /// <returns></returns>
    private static AttributeSyntax ComputeNewOperationContractAttributeNode(AttributeSyntax originalAttribute)
    {
      var newAttributeArguments = new List<AttributeArgumentSyntax>
                              {
                                Syntax.AttributeArgument(Syntax.LiteralExpression(SyntaxKind.TrueLiteralExpression))
                                  .WithNameEquals(Syntax.NameEquals(Syntax.IdentifierName("AsyncPattern"), Syntax.Token(SyntaxKind.EqualsToken)))
                              };

      SeparatedSyntaxList<AttributeArgumentSyntax> newAttributeArgumentList;

      if (originalAttribute.ArgumentList == null)
      {
        newAttributeArgumentList = Syntax.SeparatedList(
          newAttributeArguments,
          Enumerable.Empty<SyntaxToken>());
      }
      else
      {
        newAttributeArgumentList = Syntax.SeparatedList(
          originalAttribute.ArgumentList.Arguments.Concat(newAttributeArguments),
          Enumerable.Range(0, originalAttribute.ArgumentList.Arguments.SeparatorCount + 1).Select(i => Syntax.Token(SyntaxKind.CommaToken)));
      }

      return originalAttribute.WithArgumentList(Syntax.AttributeArgumentList(newAttributeArgumentList));
    }
コード例 #9
0
        private void SetArguments(SeparatedSyntaxList <AttributeArgumentSyntax> syntax)
        {
            AttributeSyntax attribute = node.Syntax;

            node.Syntax = attribute.WithArgumentList((attribute.ArgumentList ?? SyntaxFactory.AttributeArgumentList()).WithArguments(syntax));
        }