private static void ExpectedResultSupplied(
            SyntaxNodeAnalysisContext context,
            IMethodSymbol methodSymbol,
            AttributeSyntax attributeNode,
            AttributeArgumentSyntax expectedResultNamedArgument)
        {
            var methodReturnValueType = methodSymbol.ReturnType;

            if (methodReturnValueType.IsAwaitable(out var awaitReturnType))
            {
                if (awaitReturnType.SpecialType == SpecialType.System_Void)
                {
                    context.ReportDiagnostic(Diagnostic.Create(asyncExpectedResultButReturnTypeNotGenericTask,
                                                               attributeNode.GetLocation(), methodReturnValueType.ToDisplayString()));
                }
                else
                {
                    ReportIfExpectedResultTypeCannotBeAssignedToReturnType(
                        ref context, expectedResultNamedArgument, awaitReturnType);
                }
            }
            else
            {
                if (methodReturnValueType.SpecialType == SpecialType.System_Void)
                {
                    context.ReportDiagnostic(Diagnostic.Create(specifiedExpectedResultForVoid,
                                                               expectedResultNamedArgument.GetLocation()));
                }
                else
                {
                    ReportIfExpectedResultTypeCannotBeAssignedToReturnType(
                        ref context, expectedResultNamedArgument, methodReturnValueType);
                }
            }
        }
Ejemplo n.º 2
0
        private static Location GetSecurityAttributeActionSyntaxLocation(
            AttributeSyntax?nodeOpt,
            TypedConstant typedValue,
            out object displayString
            )
        {
            if (nodeOpt == null)
            {
                displayString = "";
                return(NoLocation.Singleton);
            }

            var argList = nodeOpt.ArgumentList;

            if (argList == null || argList.Arguments.IsEmpty())
            {
                // Optional SecurityAction parameter with default value.
                displayString = (FormattableString)$"{typedValue.ValueInternal}";
                return(nodeOpt.Location);
            }

            AttributeArgumentSyntax argSyntax = argList.Arguments[0];

            displayString = argSyntax.ToString();
            return(argSyntax.Location);
        }
Ejemplo n.º 3
0
        public void ParseAttributeArgument(
            int argumentIndex,
            AttributeArgumentSyntax argumentSyntax,
            SemanticModel semanticModel,
            ExpressionSyntax argumentExpression,
            IDictionary <AttributeParamName, object> result)
        {
            switch (argumentIndex)
            {
            case 0:
                AttributeArgumentParserHelper.ParseExpression(
                    argumentExpression,
                    result,
                    AttributeParameterNames.Min
                    );
                break;

            case 1:
                AttributeArgumentParserHelper.ParseExpression(
                    argumentExpression,
                    result,
                    AttributeParameterNames.Max
                    );
                break;
            }
        }
Ejemplo n.º 4
0
        private string GetLiteral(AttributeArgumentSyntax argument, SemanticModel semanticModel)
        {
            var literal = argument.Expression.GetLiteral(semanticModel);

            // Literal would be wrapped in double quotes, removing them
            return(literal.Substring(1, literal.Length - 2));
        }
Ejemplo n.º 5
0
        private static async Task <Document> AddFriendClassAttributeAsync(Document document, ClassDeclarationSyntax?classDeclaration, string friendClassType, CancellationToken cancellationToken)
        {
            // 构造FriendClassAttribute 语法节点
            AttributeArgumentSyntax attributeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName(friendClassType)));
            AttributeSyntax         attributeSyntax   = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("FriendClassAttribute"))
                                                        .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(attributeArgument)));
            // 构造添加构造FriendClassAttribute 得AttributeList语法节点
            SyntaxList <AttributeListSyntax>?attributes = classDeclaration?.AttributeLists.Add(
                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attributeSyntax)).NormalizeWhitespace());

            if (attributes == null)
            {
                return(document);
            }
            // 构造替换AttributeList的 ClassDeclaration语法节点
            ClassDeclarationSyntax?newClassDeclaration = classDeclaration?.WithAttributeLists(attributes.Value).WithAdditionalAnnotations(Formatter.Annotation);

            SyntaxNode?root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            if (root == null || classDeclaration == null || newClassDeclaration == null)
            {
                return(document);
            }
            // 构造替换classDeclaration的root语法节点
            var newRoot = root.ReplaceNode(classDeclaration, newClassDeclaration);

            // 替换root语法节点
            return(document.WithSyntaxRoot(newRoot));
        }
Ejemplo n.º 6
0
        private async Task <Document> MakeStringLengthSufficientForAutoNumberingAsync(Document document, TextSpan diagnosticSpan,
                                                                                      int minLengthForAutoNumbering, CancellationToken cancellationToken)
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            AttributeArgumentSyntax attributeArgument = GetAttributeArgumentNodeToBeReplaced(root, diagnosticSpan);

            if (attributeArgument == null || cancellationToken.IsCancellationRequested)
            {
                return(document);
            }

            AttributeArgumentSyntax modifiedArgument =
                attributeArgument.WithExpression(
                    SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
                                                    SyntaxFactory.Literal(minLengthForAutoNumbering)));

            if (modifiedArgument == null)
            {
                return(document);
            }

            var modifiedRoot = root.ReplaceNode(attributeArgument, modifiedArgument);

            return(document.WithSyntaxRoot(modifiedRoot));
        }
        private static Task <Document> ChangeLanguageNameAsync(
            Document document,
            AttributeArgumentSyntax attributeArgument,
            string languageName,
            CancellationToken cancellationToken)
        {
            if (_languageNames == null)
            {
                Interlocked.CompareExchange(ref _languageNames, LoadLanguageNames(), null);
            }

            AttributeArgumentSyntax newAttributeArgument = AttributeArgument(
                SimpleMemberAccessExpression(
                    ParseName("global::Microsoft.CodeAnalysis.LanguageNames").WithSimplifierAnnotation(),
                    IdentifierName(_languageNames[languageName])));

            return(document.ReplaceNodeAsync(attributeArgument, newAttributeArgument, cancellationToken));

            ImmutableDictionary <string, string> LoadLanguageNames()
            {
                return(typeof(LanguageNames)
                       .GetRuntimeFields()
                       .Where(f => f.IsPublic)
                       .ToImmutableDictionary(f => (string)f.GetValue(null), f => f.Name));
            }
        }
Ejemplo n.º 8
0
        public static IParameterSymbol GetCorrespondingParameter(this AttributeArgumentSyntax argumentSyntax, SyntaxNodeAnalysisContext context)
        {
            var argumentPosition   = argumentSyntax.GetArgumentPosition();
            var calledMethodSymbol = argumentSyntax.GetCalledMethod(context);

            return(argumentPosition < calledMethodSymbol?.Parameters.Length ? calledMethodSymbol.Parameters[argumentPosition] : null);
        }
Ejemplo n.º 9
0
        private static AttributeListSyntax CreateAttribute(string fieldName)
        {
            AttributeArgumentSyntax arg  = SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression("\"" + fieldName + "\""));
            AttributeSyntax         attr = SyntaxFactory.Attribute(SyntaxFactory.ParseName("XmlAttribute")).AddArgumentListArguments(arg);

            return(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[] { attr })));
        }
        async Task <Document> RemoveArgumentAsync(Document document, AttributeArgumentSyntax argument, CancellationToken ct)
        {
            var editor = await DocumentEditor.CreateAsync(document, ct).ConfigureAwait(false);

            editor.RemoveNode(argument);
            return(editor.GetChangedDocument());
        }
Ejemplo n.º 11
0
        public static Location FindTypeExpressionOrNullLocation(this AttributeArgumentSyntax attributeArgumentSyntax)
        {
            var walker = new FindTypeLocationWalker();

            walker.Visit(attributeArgumentSyntax);
            return(walker.TypeExpressionLocation);
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            AttributeSyntax attribute,
            CancellationToken cancellationToken)
        {
            TypeDeclarationSyntax typeDeclaration = attribute.FirstAncestor <TypeDeclarationSyntax>();

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            string propertyName = NameGenerator.Default.EnsureUniqueName(DefaultNames.DebuggerDisplayPropertyName, semanticModel, typeDeclaration.OpenBraceToken.Span.End);

            AttributeArgumentSyntax argument = attribute.ArgumentList.Arguments.First();

            TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNode(
                argument,
                argument.WithExpression(
                    StringLiteralExpression($"{{{propertyName},nq}}")).WithTriviaFrom(argument.Expression));

            string value = semanticModel
                           .GetDeclaredSymbol(typeDeclaration, cancellationToken)
                           .GetAttribute(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute)
                           .ConstructorArguments[0]
                           .Value
                           .ToString();

            bool isVerbatim = SyntaxInfo.StringLiteralExpressionInfo(argument.Expression).IsVerbatim;

            ExpressionSyntax returnExpression = GetReturnExpression(value, isVerbatim);

            PropertyDeclarationSyntax propertyDeclaration = MarkTypeWithDebuggerDisplayAttributeRefactoring.DebuggerDisplayPropertyDeclaration(propertyName, returnExpression);

            newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, propertyDeclaration);

            return(await document.ReplaceNodeAsync(typeDeclaration, newTypeDeclaration, cancellationToken).ConfigureAwait(false));
        }
Ejemplo n.º 13
0
        private static AttributeArgumentSyntax AddParameterName(
            AttributeArgumentSyntax argument,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (argument.NameColon == null || argument.NameColon.IsMissing)
            {
                IParameterSymbol parameterSymbol = CSharpAnalysis.DetermineParameter(
                    argument,
                    semanticModel,
                    allowParams: false,
                    cancellationToken: cancellationToken);

                if (parameterSymbol != null)
                {
                    return(argument
                           .WithNameColon(
                               NameColon(parameterSymbol.ToDisplayString(_symbolDisplayFormat))
                               .WithTrailingSpace())
                           .WithTriviaFrom(argument));
                }
            }

            return(argument);
        }
        public static string GetAttributeParamterLiteralValue(
            this AttributeArgumentSyntax @this)
        {
            var literalExpresion = @this.Expression as LiteralExpressionSyntax;

            return(literalExpresion != null ? literalExpresion.Token.ValueText : string.Empty);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            if (root is null)
            {
                return;
            }

            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            ExpressionSyntax?syntax = root.FindNode(diagnosticSpan) switch
            {
                AttributeArgumentSyntax attributeArgumentSyntax => attributeArgumentSyntax.Expression,
                ExpressionSyntax expressionSyntax => expressionSyntax,
                            _ => null,
            };

            if (syntax != null)
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: Resources.OptionLongNameMustBePascalCaseFix,
                        createChangedSolution: c => MakePascalCaseAsync(context.Document, syntax, c),
                        equivalenceKey: Resources.OptionLongNameMustBePascalCaseFix),
                    diagnostic);
            }
        }
Ejemplo n.º 16
0
 public OneWayOperationMakeIsOneWayFalseCodeAction(
     IDocument document,
     AttributeArgumentSyntax attributeArgumentSyntax)
 {
     this.document = document;
     this.attributeArgumentSyntax = attributeArgumentSyntax;
 }
Ejemplo n.º 17
0
 public static AttributeSyntax Attribute(NameSyntax name, AttributeArgumentSyntax argument)
 {
     return(SyntaxFactory.Attribute(
                name,
                AttributeArgumentList(
                    SingletonSeparatedList(argument))));
 }
Ejemplo n.º 18
0
        private static MethodDeclarationSyntax CreateMethodFromExceptionType(AttributeArgumentSyntax attributeArgument, MethodDeclarationSyntax node)
        {
            var exceptionType = attributeArgument.GetExceptionType();
            var rawStatement  = CreateAssert(exceptionType, node);

            return(ReplaceMethodBody(rawStatement, node));
        }
Ejemplo n.º 19
0
        private string GetUnionTypeFromAttribute(AttributeArgumentSyntax args)
        {
            switch (args.Expression)
            {
            case LiteralExpressionSyntax attrLiteral:
                var literalValue = attrLiteral.Token.ValueText;
                if (literalValue != "null")
                {
                    throw new Exception($"Union parameters must ne types or null at line {attrLiteral.GetLocation().GetLineSpan().StartLinePosition.Line}");
                }

                return("null");

            case TypeOfExpressionSyntax attrTypeOf:
                var typeSyntax = attrTypeOf.Type as IdentifierNameSyntax;
                if (typeSyntax != null)
                {
                    return(typeSyntax.Identifier.ValueText);
                }
                else
                {
                    var attrPredefined = attrTypeOf.Type as PredefinedTypeSyntax;
                    if (attrPredefined == null)
                    {
                        throw new Exception($"Cant process identifier in AvroField attribute {args.Expression} at line {attrTypeOf.GetLocation().GetLineSpan().StartLinePosition.Line}");
                    }
                    return(attrPredefined.Keyword.ValueText);
                }

            default:
                throw new Exception($"Unknown attribute expression type {args.Expression} at line {args.Expression.GetLocation().GetLineSpan().StartLinePosition.Line}");
            }
        }
Ejemplo n.º 20
0
        public IEnumerable <DiagnosticInfo> GetDiagnosticInfo(SyntaxNodeAnalysisContext context)
        {
            var result = new List <DiagnosticInfo>();
            var method = context.Node as MethodDeclarationSyntax;

            foreach (AttributeListSyntax attributeList in method.AttributeLists)
            {
                foreach (AttributeSyntax attribute in attributeList.Attributes)
                {
                    if (string.Compare(attribute.Name?.ToString(), "ValidateInput") != 0)
                    {
                        continue;
                    }

                    //Verify the namespace before proceeding
                    var symbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol as ISymbol;
                    if (string.Compare(symbol?.ContainingNamespace.ToString(), "System.Web.Mvc", StringComparison.Ordinal) != 0)
                    {
                        continue;
                    }

                    AttributeArgumentListSyntax argumentList = attribute.ArgumentList;
                    AttributeArgumentSyntax     argument     = argumentList.Arguments.First();
                    var value = context.SemanticModel.GetConstantValue(argument?.Expression);

                    if (value.HasValue && (bool)value.Value == false)
                    {
                        result.Add(new DiagnosticInfo(attribute.GetLocation()));
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 21
0
        public static object GetArgumentValue(this AttributeArgumentSyntax arg, SemanticModel semanticModel)
        {
            var argExpr = arg.ChildNodes().First();

            return
                ((argExpr as MemberAccessExpressionSyntax)?.GetMemberValue(semanticModel) ??
                 throw new NotImplementedException());
        }
Ejemplo n.º 22
0
        private static MethodDeclarationSyntax CreateMethodFromExceptionMessage(AttributeArgumentSyntax expectedException, MethodDeclarationSyntax node)
        {
            var exceptionMessage = expectedException.Expression.ToString();
            var rawStatement     = CreateAssertFromExceptionMessage(node);
            var statementToAdd   = CreateExtraAssert(exceptionMessage);

            return(ReplaceMethodBody(rawStatement, node).AddBodyStatements(statementToAdd));
        }
Ejemplo n.º 23
0
        public override Evaluation VisitAttributeArgument(AttributeArgumentSyntax node)
        {
            node.NameEquals?.Accept <Evaluation>(this);
            node.NameColon?.Accept <Evaluation>(this);
            node.Expression?.Accept <Evaluation>(this);

            return(base.VisitAttributeArgument(node));
        }
Ejemplo n.º 24
0
        public static Tuple <AttributeArgumentSyntax, object> EvaluateExpression(this AttributeArgumentSyntax syntax)
        {
            object value;

            return(syntax.Expression.TryEvaluateArgument(out value)
                ? new Tuple <AttributeArgumentSyntax, object>(syntax, value)
                : null);
        }
Ejemplo n.º 25
0
 public static string ExtractArgumentFromAttribute(this AttributeArgumentSyntax arg)
 {
     return(arg.Expression switch
     {
         LiteralExpressionSyntax les when les.Kind() == SyntaxKind.StringLiteralExpression
         => les.Token.ValueText,
         _ => arg.ToString()
     });
Ejemplo n.º 26
0
 public void ParseAttributeArgument(
     int argumentIndex,
     AttributeArgumentSyntax argumentSyntax,
     SemanticModel semanticModel,
     ExpressionSyntax argumentExpression,
     IDictionary <AttributeParamName, object> result)
 {
 }
Ejemplo n.º 27
0
        public override void VisitAttributeArgument(AttributeArgumentSyntax node)
        {
            node.NameEquals?.Accept(this);
            node.NameColon?.Accept(this);
            node.Expression?.Accept(this);

            base.VisitAttributeArgument(node);
        }
        private void HandleAttribute(SyntaxNodeAnalysisContext context)
        {
            AttributeSyntax syntax       = (AttributeSyntax)context.Node;
            SymbolInfo      symbolInfo   = context.SemanticModel.GetSymbolInfo(syntax, context.CancellationToken);
            IMethodSymbol   methodSymbol = symbolInfo.Symbol as IMethodSymbol;

            if (methodSymbol == null)
            {
                return;
            }

            if (!string.Equals("JsonObjectAttribute", methodSymbol.ContainingType?.Name, StringComparison.Ordinal))
            {
                return;
            }

            if (syntax.ArgumentList?.Arguments.Count > 0)
            {
                bool?isOptIn = null;

                // check property assignments first, because they override the first argument when both are specified
                foreach (var attributeArgumentSyntax in syntax.ArgumentList.Arguments)
                {
                    if (attributeArgumentSyntax.NameEquals == null)
                    {
                        continue;
                    }

                    if (!string.Equals("MemberSerialization", attributeArgumentSyntax.NameEquals.Name?.ToString(), StringComparison.Ordinal))
                    {
                        continue;
                    }

                    if (IsMemberSerializationOptIn(context, attributeArgumentSyntax.Expression))
                    {
                        return;
                    }

                    isOptIn = false;
                }

                if (!isOptIn.HasValue)
                {
                    AttributeArgumentSyntax firstArgument = syntax.ArgumentList.Arguments[0];
                    if (firstArgument?.Expression != null &&
                        (firstArgument.NameColon == null || string.Equals("memberSerialization", firstArgument.NameColon?.Name?.ToString(), StringComparison.Ordinal)) &&
                        firstArgument.NameEquals == null)
                    {
                        if (IsMemberSerializationOptIn(context, firstArgument?.Expression))
                        {
                            return;
                        }
                    }
                }
            }

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, syntax.GetLocation()));
        }
Ejemplo n.º 29
0
 public static string AttributeArgument(AttributeArgumentSyntax arg)
 {
     var output = SyntaxNode(arg.Expression);
     if (arg.NameColon != null)
     {
         output = SyntaxNode(arg.NameColon.Name) + ": " + output;
     }
     return output;
 }
Ejemplo n.º 30
0
            public override SyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node)
            {
                if (Array.IndexOf(_arguments, node) != -1)
                {
                    return(AddParameterName(node, _semanticModel));
                }

                return(base.VisitAttributeArgument(node));
            }
Ejemplo n.º 31
0
 public static IParameterSymbol DetermineParameter(
     this SemanticModel semanticModel,
     AttributeArgumentSyntax attributeArgument,
     bool allowParams    = false,
     bool allowCandidate = false,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(DetermineParameterHelper.DetermineParameter(attributeArgument, semanticModel, allowParams, allowCandidate, cancellationToken));
 }
Ejemplo n.º 32
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitAttributeArgument(AttributeArgumentSyntax node)
 {
     this.OnNodeVisited(node);
     if (!this.traverseRootOnly) base.VisitAttributeArgument(node);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitAttributeArgument(AttributeArgumentSyntax node)
 {
     this.OnNodeVisited(node, this.type.IsInstanceOfType(node));
     base.VisitAttributeArgument(node);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AttributeArgument"/> class.
 /// </summary>
 /// <param name="syntaxNode"></param>
 /// <param name="kind"></param>
 /// <remarks>
 /// When providing the semantic model, some properites will be devised from that.
 /// </remarks>
 public AttributeArgument(AttributeArgumentSyntax syntaxNode, SemanticModel semanticModel)
     : base(syntaxNode, semanticModel)
 {
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AttributeArgument"/> class.
 /// </summary>
 /// <param name="syntaxNode"></param>
 public AttributeArgument(AttributeArgumentSyntax syntaxNode)
     : this(syntaxNode, null)
 {
 }
            public override void VisitAttributeArgument(AttributeArgumentSyntax node)
            {
                var saveCurrentScope = currentScope;
                currentScope = new DeclarationScope(saveCurrentScope);

                Visit(node.Expression);

                Debug.Assert(currentScope.Parent == saveCurrentScope);
                currentScope = saveCurrentScope;
            }
Ejemplo n.º 37
0
 private Symbol BindNamedAttributeArgumentName(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, DiagnosticBag diagnostics, out bool wasError, out LookupResultKind resultKind)
 {
     var identifierName = namedArgument.NameEquals.Name;
     var name = identifierName.Identifier.ValueText;
     LookupResult result = LookupResult.GetInstance();
     HashSet<DiagnosticInfo> useSiteDiagnostics = null;
     this.LookupMembersWithFallback(result, attributeType, name, 0, ref useSiteDiagnostics);
     diagnostics.Add(identifierName, useSiteDiagnostics);
     Symbol resultSymbol = this.ResultSymbol(result, name, 0, identifierName, diagnostics, false, out wasError);
     resultKind = result.Kind;
     result.Free();
     return resultSymbol;
 }
            private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument(
                int index,
                IEnumerable<ImmutableArray<IParameterSymbol>> parameterizedSymbols,
                AttributeArgumentSyntax argumentOpt = null)
            {
                if (argumentOpt != null && argumentOpt.NameEquals != null)
                {
                    // [MyAttribute(Prop = ...

                    return InferTypeInNameEquals(argumentOpt.NameEquals, argumentOpt.NameEquals.EqualsToken);
                }

                var name = argumentOpt != null && argumentOpt.NameColon != null ? argumentOpt.NameColon.Name.Identifier.ValueText : null;
                return InferTypeInArgument(index, parameterizedSymbols, name);
            }
 private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument(int index, IEnumerable<IMethodSymbol> methods, AttributeArgumentSyntax argumentOpt = null)
 {
     return InferTypeInAttributeArgument(index, methods.Select(m => m.Parameters), argumentOpt);
 }
 private IEnumerable<ITypeSymbol> InferTypeInAttribute(AttributeSyntax attribute, int index, AttributeArgumentSyntax argumentOpt = null)
 {
     var info = this.semanticModel.GetSymbolInfo(attribute, cancellationToken);
     var methods = info.GetBestOrAllSymbols().OfType<IMethodSymbol>();
     return InferTypeInAttributeArgument(index, methods, argumentOpt);
 }
            private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument(AttributeArgumentSyntax argument, SyntaxToken? previousToken = null, ArgumentSyntax argumentOpt = null)
            {
                if (previousToken.HasValue)
                {
                    // If we have a position, then it must be after the colon or equals in an argument.
                    if (argument.NameColon == null || argument.NameColon.ColonToken != previousToken || argument.NameEquals.EqualsToken != previousToken)
                    {
                        return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                    }
                }

                if (argument.Parent != null)
                {
                    var attribute = argument.Parent.Parent as AttributeSyntax;
                    if (attribute != null)
                    {
                        var index = attribute.ArgumentList.Arguments.IndexOf(argument);
                        return InferTypeInAttribute(attribute, index, argument);
                    }
                }

                return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
            }
Ejemplo n.º 42
0
 public static IUnifiedArgumentSyntax Create(AttributeArgumentSyntax argument)
 {
     return new UnifiedArgumentSyntax(argument);
 }
Ejemplo n.º 43
0
        public void VisitAttributeArgument(AttributeArgumentSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            if (node.NameColon != null)
                node.NameColon.Accept(this);
            if (node.NameEquals != null)
                node.NameEquals.Accept(this);

            node.Expression.Accept(this);
        }
        private Document Delete(Document document, AttributeArgumentSyntax node)
        {
            var argumentList = node.FirstAncestorOrSelf<AttributeArgumentListSyntax>();
            var newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);

            return document.ReplaceNodeAsync(argumentList, newArgumentList, CancellationToken.None)
                           .WaitAndGetResult_CodeModel(CancellationToken.None);
        }
Ejemplo n.º 45
0
        private BoundExpression BindNamedAttributeArgument(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, DiagnosticBag diagnostics)
        {
            bool wasError;
            LookupResultKind resultKind;
            Symbol namedArgumentNameSymbol = BindNamedAttributeArgumentName(namedArgument, attributeType, diagnostics, out wasError, out resultKind);

            ReportDiagnosticsIfObsolete(diagnostics, namedArgumentNameSymbol, namedArgument, hasBaseReceiver: false);

            Debug.Assert(resultKind == LookupResultKind.Viable || wasError);

            TypeSymbol namedArgumentType;
            if (wasError)
            {
                namedArgumentType = CreateErrorType();  // don't generate cascaded errors.
            }
            else
            {
                namedArgumentType = BindNamedAttributeArgumentType(namedArgument, namedArgumentNameSymbol, attributeType, diagnostics);
            }

            // BindRValue just binds the expression without doing any validation (if its a valid expression for attribute argument).
            // Validation is done later by AttributeExpressionVisitor
            BoundExpression namedArgumentValue = this.BindValue(namedArgument.Expression, diagnostics, BindValueKind.RValue);
            namedArgumentValue = GenerateConversionForAssignment(namedArgumentType, namedArgumentValue, diagnostics);

            // TODO: should we create an entry even if there are binding errors?
            var fieldSymbol = namedArgumentNameSymbol as FieldSymbol;
            IdentifierNameSyntax nameSyntax = namedArgument.NameEquals.Name;
            BoundExpression lvalue;
            if ((object)fieldSymbol != null)
            {
                var containingAssembly = fieldSymbol.ContainingAssembly as SourceAssemblySymbol;

                // We do not want to generate any unassigned field or unreferenced field diagnostics.
                containingAssembly?.NoteFieldAccess(fieldSymbol, read: true, write: true);

                lvalue = new BoundFieldAccess(nameSyntax, null, fieldSymbol, ConstantValue.NotAvailable, resultKind, fieldSymbol.Type);
            }
            else
            {
                var propertySymbol = namedArgumentNameSymbol as PropertySymbol;
                if ((object)propertySymbol != null)
                {
                    lvalue = new BoundPropertyAccess(nameSyntax, null, propertySymbol, resultKind, namedArgumentType);
                }
                else
                {
                    lvalue = BadExpression(nameSyntax, resultKind);
                }
            }

            return new BoundAssignmentOperator(namedArgument, lvalue, namedArgumentValue, namedArgumentType);
        }
            private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
            {
                int endPosition;

                switch (part)
                {
                    case EnvDTE.vsCMPart.vsCMPartName:
                    case EnvDTE.vsCMPart.vsCMPartAttributes:
                    case EnvDTE.vsCMPart.vsCMPartHeader:
                    case EnvDTE.vsCMPart.vsCMPartWhole:
                    case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
                        throw Exceptions.ThrowENotImpl();

                    case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartBody:
                    case EnvDTE.vsCMPart.vsCMPartNavigate:
                        throw Exceptions.ThrowEFail();

                    case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
                        endPosition = node.Span.End;
                        break;

                    default:
                        throw Exceptions.ThrowEInvalidArg();
                }

                return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
            }
Ejemplo n.º 47
0
        private TypeSymbol BindNamedAttributeArgumentType(AttributeArgumentSyntax namedArgument, Symbol namedArgumentNameSymbol, NamedTypeSymbol attributeType, DiagnosticBag diagnostics)
        {
            if (namedArgumentNameSymbol.Kind == SymbolKind.ErrorType)
            {
                return (TypeSymbol)namedArgumentNameSymbol;
            }

            // SPEC:    For each named-argument Arg in named-argument-list N:
            // SPEC:        Let Name be the identifier of the named-argument Arg.
            // SPEC:        Name must identify a non-static read-write public field or property on 
            // SPEC:            attribute class T. If T has no such field or property, then a compile-time error occurs.

            bool invalidNamedArgument = false;
            TypeSymbol namedArgumentType = null;
            invalidNamedArgument |= (namedArgumentNameSymbol.DeclaredAccessibility != Accessibility.Public);
            invalidNamedArgument |= namedArgumentNameSymbol.IsStatic;

            if (!invalidNamedArgument)
            {
                switch (namedArgumentNameSymbol.Kind)
                {
                    case SymbolKind.Field:
                        var fieldSymbol = (FieldSymbol)namedArgumentNameSymbol;
                        namedArgumentType = fieldSymbol.Type;
                        invalidNamedArgument |= fieldSymbol.IsReadOnly;
                        invalidNamedArgument |= fieldSymbol.IsConst;
                        break;

                    case SymbolKind.Property:
                        var propertySymbol = ((PropertySymbol)namedArgumentNameSymbol).GetLeastOverriddenProperty(this.ContainingType);
                        namedArgumentType = propertySymbol.Type;
                        invalidNamedArgument |= propertySymbol.IsReadOnly;
                        var getMethod = propertySymbol.GetMethod;
                        var setMethod = propertySymbol.SetMethod;
                        invalidNamedArgument = invalidNamedArgument || (object)getMethod == null || (object)setMethod == null;
                        if (!invalidNamedArgument)
                        {
                            invalidNamedArgument =
                                getMethod.DeclaredAccessibility != Accessibility.Public ||
                                setMethod.DeclaredAccessibility != Accessibility.Public;
                        }
                        break;

                    default:
                        invalidNamedArgument = true;
                        break;
                }
            }

            if (invalidNamedArgument)
            {
                return new ExtendedErrorTypeSymbol(attributeType,
                    namedArgumentNameSymbol,
                    LookupResultKind.NotAVariable,
                    diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgument,
                        namedArgument.NameEquals.Name.Location,
                        namedArgumentNameSymbol.Name));
            }
            if (!namedArgumentType.IsValidAttributeParameterType(Compilation))
            {
                return new ExtendedErrorTypeSymbol(attributeType,
                    namedArgumentNameSymbol,
                    LookupResultKind.NotAVariable,
                    diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgumentType,
                        namedArgument.NameEquals.Name.Location,
                        namedArgumentNameSymbol.Name));
            }

            return namedArgumentType;
        }
 private static Task<Document> UpdateValueOfArgumentAsync(Document document, SyntaxNode root, AttributeArgumentSyntax argument)
 {
     var newArgument = argument.WithExpression(GetNewAttributeValue());
     return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(argument, newArgument)));
 }
		public static string GenerateNameForArgument(
			this SemanticModel semanticModel, AttributeArgumentSyntax argument)
		{
			// If it named argument then we use the name provided.
			if (argument.NameEquals != null)
			{
				return argument.NameEquals.Name.Identifier.ValueText;
			}

			return semanticModel.GenerateNameForExpression(argument.Expression);
		}
 private string GetLiteral(AttributeArgumentSyntax argument, SemanticModel semanticModel)
 {
     var literal = argument.Expression.GetLiteral(semanticModel);
     // Literal would be wrapped in double quotes, removing them
     return literal.Substring(1, literal.Length - 2);
 }