/// <summary>
        ///     Builds attributes of the <paramref name="parameterSymbol"/>.
        /// </summary>
        /// <param name="parameterSymbol">
        ///     The parameter attributes that you want as string.
        /// </param>
        /// <returns>
        ///     Attributes of the <paramref name="parameterSymbol"/> as string.
        /// </returns>
        public string BuildAttributes(IParameterSymbol parameterSymbol)
        {
            var attributes = parameterSymbol.GetAttributes();

            return attributes.Any()
                       ? string.Format("[{0}]", string.Join(",", attributes.Select(x => x.ToString())))
                       : string.Empty;
        }
 public static IParameterSymbol WithAttributes(this IParameterSymbol parameter, ImmutableArray <AttributeData> attributes)
 {
     return(parameter.GetAttributes() == attributes
         ? parameter
         : CodeGenerationSymbolFactory.CreateParameterSymbol(
                attributes,
                parameter.RefKind,
                parameter.IsParams,
                parameter.Type,
                parameter.Name,
                parameter.IsOptional,
                parameter.HasExplicitDefaultValue,
                parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null));
 }
 public static IParameterSymbol RenameParameter(this IParameterSymbol parameter, string parameterName)
 {
     return(parameter.Name == parameterName
         ? parameter
         : CodeGenerationSymbolFactory.CreateParameterSymbol(
                parameter.GetAttributes(),
                parameter.RefKind,
                parameter.IsParams,
                parameter.Type,
                parameterName,
                parameter.IsOptional,
                parameter.HasExplicitDefaultValue,
                parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null));
 }
Example #4
0
        protected bool GetNativeStringParamAttribute(IParameterSymbol parameter, out AttributeData attribute)
        {
            foreach (var a in parameter.GetAttributes())
            {
                var type = a.AttributeClass;
                if (type.ContainingNamespace.Name == "CS2X" && type.Name == "NativeStringParamAttribute")
                {
                    attribute = a;
                    return(true);
                }
            }

            attribute = null;
            return(false);
        }
Example #5
0
        public static bool HasPropertyIdentifierAttribute(IParameterSymbol parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var attributes = parameter.GetAttributes();

            return(attributes.Any(a =>
                                  (a.AttributeClass.Name == "PropertyIdentifierAttribute") &&
                                  (a.AttributeClass.ContainingAssembly != null) &&
                                  (a.AttributeClass.ContainingAssembly.Name == AnalyserAssemblyName)
                                  ));
        }
Example #6
0
        internal static bool IsCallerMemberName(this IParameterSymbol parameter)
        {
            if (parameter.HasExplicitDefaultValue)
            {
                foreach (var attribute in parameter.GetAttributes())
                {
                    if (attribute.AttributeClass == KnownSymbol.CallerMemberNameAttribute)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #7
0
        private static bool IsMarkedReadOnly(
            INamedTypeSymbol readOnlyAttribute,
            IParameterSymbol parameterSymbol
            )
        {
            foreach (AttributeData attribute in parameterSymbol.GetAttributes())
            {
                if (IsReadOnlyAttribute(readOnlyAttribute, attribute.AttributeClass))
                {
                    return(true);
                }
            }

            return(false);
        }
		public string GetPathParameterAttribute(IParameterSymbol parameterSymbol, string route)
		{
			if (route == null)
				return null;
			if (route.Contains($"{{{parameterSymbol.Name}}}"))
				return "[Path]";

			var routeAttributeData = parameterSymbol.GetAttributes().FirstOrDefault(a => _fromRouteAttributeSymbol.Equals(a.AttributeClass, SymbolEqualityComparer.Default));
			if (routeAttributeData != null)
			{
				var routeParamName = routeAttributeData.NamedArguments.Where(na => na.Key == "Name").Select(na => na.Value.ToCSharpString()).FirstOrDefault();
				if (routeParamName != null && route.Contains($"{{{routeParamName.Trim('"')}}}"))
					return $"[Path({routeParamName})]";
			}
			return null;
		}
Example #9
0
        /// <summary>
        /// Construct a new ParameterApiView instance, represented by the provided symbol.
        /// </summary>
        /// <param name="symbol">The symbol representing the parameter.</param>
        public ParameterApiView(IParameterSymbol symbol)
        {
            this.Name    = symbol.Name;
            this.Type    = new TypeReferenceApiView(symbol.Type);
            this.RefKind = symbol.RefKind;

            this.HasExplicitDefaultValue = symbol.HasExplicitDefaultValue;
            this.ExplicitDefaultValue    = HasExplicitDefaultValue ? symbol.ExplicitDefaultValue : null;

            List <string> attributes = new List <string>();

            foreach (AttributeData attribute in symbol.GetAttributes())
            {
                attributes.Add(attribute.ToString());
            }
            this.Attributes = attributes.ToArray();
        }
Example #10
0
        private static SyntaxList <AttributeListSyntax> GenerateAttributes(
            IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options)
        {
            if (isExplicit)
            {
                return(default(SyntaxList <AttributeListSyntax>));
            }

            var attributes = parameter.GetAttributes();

            if (attributes.Length == 0)
            {
                return(default(SyntaxList <AttributeListSyntax>));
            }

            return(AttributeGenerator.GenerateAttributeLists(attributes, options));
        }
Example #11
0
        public bool TryGetCallerMemberInfo(IParameterSymbol parameter, ISymbol callerMember, SyntaxNode callerNode, out string value)
        {
            var callerAttribute = parameter.GetAttributes().FirstOrDefault(
                a => a.AttributeClass.Equals(GetPhaseType("System.Runtime.CompilerServices.CallerMemberNameAttribute"))
                    || a.AttributeClass.Equals(GetPhaseType("System.Runtime.CompilerServices.CallerLineNumberAttribute"))
                    || a.AttributeClass.Equals(GetPhaseType("System.Runtime.CompilerServices.CallerFilePathAttribute"))
            );
            if (callerAttribute == null)
            {
                value = null;
                return false;
            }
            switch (callerAttribute.AttributeClass.Name)
            {
                case "CallerMemberNameAttribute":
                    if (callerMember == null)
                    {
                        value = null;
                        Log.Warn("Could not get caller member name");
                        return false;
                    }
                    value = "\"" + GetSymbolName(callerMember) + "\"";
                    return true;
                case "CallerLineNumberAttribute":
                    if (callerNode == null)
                    {
                        value = null;
                        Log.Warn("Could not get caller line number");
                        return false;
                    }
                    value = callerNode.GetText().Lines[0].LineNumber.ToString();
                    return true;
                case "CallerFilePathAttribute":
                    if (callerNode == null)
                    {
                        value = null;
                        Log.Warn("Could not get caller file path");
                        return false;
                    }
                    value = "\"" + callerNode.SyntaxTree.FilePath.Replace("\\", "\\\\") + "\"";
                    return true;
            }

            value = null;
            return false;
        }
Example #12
0
        public static AttributeData GetWebJobsAttribute(this IParameterSymbol parameter)
        {
            var parameterAttributes = parameter.GetAttributes();

            foreach (var parameterAttribute in parameterAttributes)
            {
                var attributeAttributes = parameterAttribute.AttributeClass.GetAttributes();

                foreach (var attribute in attributeAttributes)
                {
                    if (string.Equals(attribute.AttributeClass.ToDisplayString(), Constants.Types.WebJobsBindingAttribute, StringComparison.Ordinal))
                    {
                        return(parameterAttribute);
                    }
                }
            }

            return(null);
        }
Example #13
0
        public static IEnumerable <Contract> GetDeclaredPreconditions(this IParameterSymbol @this, SemanticModel model, IContractProvider contractProvider)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (contractProvider == null)
            {
                throw new ArgumentNullException(nameof(contractProvider));
            }

            return(@this
                   .GetAttributes()
                   .Where(a => a.IsContractAttribute(model))
                   .Select(a => contractProvider[a.AttributeClass.Name.ToString().Trim()]));
        }
Example #14
0
        /// <summary>
        /// Check if the parameter has [CallerMemberName].
        /// </summary>
        /// <param name="parameter">The <see cref="IParameterSymbol"/>.</param>
        /// <returns>True if the parameter has [CallerMemberName].</returns>
        public static bool IsCallerMemberName(this IParameterSymbol parameter)
        {
            if (parameter is null)
            {
                throw new System.ArgumentNullException(nameof(parameter));
            }

            if (parameter.HasExplicitDefaultValue &&
                parameter.Type == QualifiedType.System.String)
            {
                foreach (var attribute in parameter.GetAttributes())
                {
                    if (attribute.AttributeClass == QualifiedType.System.Runtime.CompilerServices.CallerMemberNameAttribute)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        private static bool IsParameterMarkedStateless(
            SemanticModel model,
            ISymbol statelessFuncAttr,
            IdentifierNameSyntax identifer,
            CancellationToken ct
            )
        {
            ISymbol symbol = model.GetSymbolInfo(identifer).Symbol;

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

            var declarations = symbol.DeclaringSyntaxReferences;

            if (declarations.Length != 1)
            {
                return(false);
            }

            ParameterSyntax parameterSyntax = declarations[0].GetSyntax(ct) as ParameterSyntax;

            if (parameterSyntax == null)
            {
                return(false);
            }

            IParameterSymbol parameter = model.GetDeclaredSymbol(parameterSyntax, ct);

            foreach (AttributeData attr in parameter.GetAttributes())
            {
                if (attr.AttributeClass == statelessFuncAttr)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #16
0
        /// <summary>
        /// Extract the <see cref="ImportAttribute.ServiceId"/> for the given <paramref name="parameter"/>.
        /// </summary>
        /// <param name="parameter"> The constructor parameter whose optional ServiceId should be retrieved. </param>
        /// <returns> The parameter's optioal ServiceId. </returns>
        private static string?GetServiceId(IParameterSymbol parameter)
        {
            var serviceId = (string?)null;

            foreach (var attribute in parameter.GetAttributes())
            {
                if (nameof(ImportAttribute).Equals(attribute.AttributeClass?.Name, StringComparison.Ordinal))
                {
                    foreach (var argument in attribute.ConstructorArguments)
                    {
                        if (argument.Kind == TypedConstantKind.Primitive &&
                            argument.Value is string value)
                        {
                            serviceId = value;
                            break;
                        }
                    }
                }
            }

            return(serviceId);
        }
Example #17
0
        public static SortDirection?GetSortDirection(this IParameterSymbol parameter, Compilation compilation)
        {
            bool isAsc      = false;
            bool isDesc     = false;
            var  attributes = parameter.GetAttributes();

            for (int i = 0; i < attributes.Length; i++)
            {
                var attributeClass = attributes[i].AttributeClass;
                if (attributeClass.EqualsTo(KnownTypes.AscAttribute, compilation))
                {
                    isAsc = true;
                }
                else if (attributeClass.EqualsTo(KnownTypes.DescAttribute, compilation))
                {
                    isDesc = true;
                }
            }

            if (isAsc && isDesc)
            {
                return(null);
            }
            else if (isAsc)
            {
                return(SortDirection.Ascending);
            }
            else if (isDesc)
            {
                return(SortDirection.Descending);
            }
            else
            {
                return(SortDirection.Unspecified);
            }
        }
Example #18
0
 private static AttributeData GetCallerInfoAttribute(IParameterSymbol parameter) =>
 parameter.GetAttributes(CallerInfoAttributesToReportOn).FirstOrDefault();
        private static void AnalyzeArgument(
            SyntaxNodeAnalysisContext context,
            ISymbol statelessFuncAttribute,
            ImmutableHashSet <ISymbol> statelessFuncs
            )
        {
            ArgumentSyntax syntax = context.Node as ArgumentSyntax;

            SemanticModel model = context.SemanticModel;

            IParameterSymbol param = syntax.DetermineParameter(model);

            if (param == null)
            {
                return;
            }

            ImmutableArray <AttributeData> paramAttributes = param.GetAttributes();

            if (!paramAttributes.Any(a => a.AttributeClass == statelessFuncAttribute))
            {
                return;
            }

            ExpressionSyntax argument = syntax.Expression;

            /**
             * Even though we haven't specifically accounted for its
             * source if it's a StatelessFunc<T> we're reasonably
             * certain its been analyzed.
             */
            ISymbol type = model.GetTypeInfo(argument).Type;

            if (type != null && IsStatelessFunc(type, statelessFuncs))
            {
                return;
            }

            Diagnostic diag;
            SyntaxKind kind = argument.Kind();

            switch (kind)
            {
            // this is the case when a method reference is used
            // eg Func<string, int> func = int.Parse
            case SyntaxKind.SimpleMemberAccessExpression:
                if (IsStaticMemberAccess(context, argument))
                {
                    return;
                }

                // non-static member access means that state could
                // be used / held.
                // TODO: Look for [Immutable] on the member's type
                // to determine if the non-static member is safe
                diag = Diagnostic.Create(
                    Diagnostics.StatelessFuncIsnt,
                    argument.GetLocation(),
                    $"{ argument.ToString() } is not static"
                    );
                break;

            // this is the case when a "delegate" is used
            // eg delegate( int x, int y ) { return x + y; }
            case SyntaxKind.AnonymousMethodExpression:
            // this is the case when the left hand side of the
            // lambda has parens
            // eg () => 1, (x, y) => x + y
            case SyntaxKind.ParenthesizedLambdaExpression:
            // this is the case when the left hand side of the
            // lambda does not have parens
            // eg x => x + 1
            case SyntaxKind.SimpleLambdaExpression:
                bool hasCaptures = TryGetCaptures(
                    context,
                    argument,
                    out ImmutableArray <ISymbol> captures
                    );
                if (!hasCaptures)
                {
                    return;
                }

                string captured = string.Join(", ", captures.Select(c => c.Name));
                diag = Diagnostic.Create(
                    Diagnostics.StatelessFuncIsnt,
                    argument.GetLocation(),
                    $"Captured variable(s): { captured }"
                    );
                break;

            // this is the case where an expression is invoked,
            // which returns a Func<T>
            // eg ( () => { return () => 1 } )()
            case SyntaxKind.InvocationExpression:
                // we are rejecting this because it is tricky to
                // analyze properly, but also a bit ugly and should
                // never really be necessary
                diag = Diagnostic.Create(
                    Diagnostics.StatelessFuncIsnt,
                    argument.GetLocation(),
                    $"Invocations are not allowed: { argument.ToString() }"
                    );

                break;

            /**
             * This is the case where a variable is passed in
             * eg Foo( f )
             * Where f might be a local variable, a parameter, or field
             *
             * class C<T> {
             *   StatelessFunc<T> m_f;
             *
             *   void P( StatelessFunc<T> f ) { Foo( f ); }
             *   void Q( [StatelessFunc] Func<T> f ) { Foo( f ); }
             *   void R() { StatelessFunc<T> f; Foo( f ); }
             *   void S() { Foo( m_f ); }
             *   void T() : this( StaticMemberMethod ) {}
             * }
             */
            case SyntaxKind.IdentifierName:
                /**
                 * If it's a local parameter marked with [StatelessFunc] we're reasonably
                 * certain it was analyzed on the caller side.
                 */
                if (IsParameterMarkedStateless(
                        model,
                        statelessFuncAttribute,
                        argument as IdentifierNameSyntax,
                        context.CancellationToken
                        ))
                {
                    return;
                }

                if (IsStaticMemberAccess(
                        context,
                        argument as IdentifierNameSyntax
                        ))
                {
                    return;
                }

                /**
                 * If it's any other variable. We're not sure
                 */
                diag = Diagnostic.Create(
                    Diagnostics.StatelessFuncIsnt,
                    argument.GetLocation(),
                    $"Unable to determine if { argument.ToString() } is stateless."
                    );

                break;

            default:
                // we need StatelessFunc<T> to be ultra safe, so we'll
                // reject usages we do not understand yet
                diag = Diagnostic.Create(
                    Diagnostics.StatelessFuncIsnt,
                    argument.GetLocation(),
                    $"Unable to determine safety of { argument.ToString() }. This is an unexpectes usage of StatelessFunc<T>"
                    );

                break;
            }

            context.ReportDiagnostic(diag);
        }
Example #20
0
        private ImmutableArray <SymbolDisplayPart> AppendParameterAttributes(
            ImmutableArray <SymbolDisplayPart> parts,
            ISymbol symbol,
            ImmutableArray <IParameterSymbol> parameters)
        {
            int i = SymbolDeclarationBuilder.FindParameterListStart(symbol, parts);

            if (i == -1)
            {
                return(parts);
            }

            int parameterIndex = 0;

            IParameterSymbol parameter = parameters[parameterIndex];

            ImmutableArray <SymbolDisplayPart> attributeParts = SymbolDeclarationBuilder.GetAttributesParts(
                parameter.GetAttributes(),
                predicate: IsVisibleAttribute,
                splitAttributes: Options.SplitAttributes,
                includeAttributeArguments: Options.IncludeAttributeArguments,
                addNewLine: false);

            if (attributeParts.Any())
            {
                parts = parts.Insert(i + 1, SymbolDisplayPartFactory.Space());
                parts = parts.InsertRange(i + 1, attributeParts);
            }

            int parenthesesDepth   = 0;
            int bracesDepth        = 0;
            int bracketsDepth      = 0;
            int angleBracketsDepth = 0;

            ImmutableArray <SymbolDisplayPart> .Builder builder = null;

            int prevIndex = 0;

            AddParameterAttributes();

            if (builder != null)
            {
                while (prevIndex < parts.Length)
                {
                    builder.Add(parts[prevIndex]);
                    prevIndex++;
                }

                return(builder.ToImmutableArray());
            }

            return(parts);

            void AddParameterAttributes()
            {
                while (i < parts.Length)
                {
                    SymbolDisplayPart part = parts[i];

                    if (part.Kind == SymbolDisplayPartKind.Punctuation)
                    {
                        switch (part.ToString())
                        {
                        case ",":
                        {
                            if (((angleBracketsDepth == 0 && parenthesesDepth == 1 && bracesDepth == 0 && bracketsDepth == 0) ||
                                 (angleBracketsDepth == 0 && parenthesesDepth == 0 && bracesDepth == 0 && bracketsDepth == 1)) &&
                                i < parts.Length - 1)
                            {
                                SymbolDisplayPart nextPart = parts[i + 1];

                                if (nextPart.Kind == SymbolDisplayPartKind.Space)
                                {
                                    parameterIndex++;

                                    attributeParts = SymbolDeclarationBuilder.GetAttributesParts(
                                        parameters[parameterIndex].GetAttributes(),
                                        predicate: IsVisibleAttribute,
                                        splitAttributes: Options.SplitAttributes,
                                        includeAttributeArguments: Options.IncludeAttributeArguments,
                                        addNewLine: false);

                                    if (attributeParts.Any())
                                    {
                                        if (builder == null)
                                        {
                                            builder = ImmutableArray.CreateBuilder <SymbolDisplayPart>();

                                            builder.AddRange(parts, i + 1);
                                        }
                                        else
                                        {
                                            for (int j = prevIndex; j <= i; j++)
                                            {
                                                builder.Add(parts[j]);
                                            }
                                        }

                                        builder.Add(SymbolDisplayPartFactory.Space());
                                        builder.AddRange(attributeParts);

                                        prevIndex = i + 1;
                                    }
                                }
                            }

                            break;
                        }

                        case "(":
                        {
                            parenthesesDepth++;
                            break;
                        }

                        case ")":
                        {
                            Debug.Assert(parenthesesDepth >= 0);
                            parenthesesDepth--;

                            if (parenthesesDepth == 0 &&
                                symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType))
                            {
                                return;
                            }

                            break;
                        }

                        case "[":
                        {
                            bracketsDepth++;
                            break;
                        }

                        case "]":
                        {
                            Debug.Assert(bracketsDepth >= 0);
                            bracketsDepth--;

                            if (bracketsDepth == 0 &&
                                symbol.Kind == SymbolKind.Property)
                            {
                                return;
                            }

                            break;
                        }

                        case "{":
                        {
                            bracesDepth++;
                            break;
                        }

                        case "}":
                        {
                            Debug.Assert(bracesDepth >= 0);
                            bracesDepth--;
                            break;
                        }

                        case "<":
                        {
                            angleBracketsDepth++;
                            break;
                        }

                        case ">":
                        {
                            Debug.Assert(angleBracketsDepth >= 0);
                            angleBracketsDepth--;
                            break;
                        }
                        }
                    }

                    i++;
                }
            }
        }
 static ImmutableArray <string> getParameterAttributes(IParameterSymbol parameter) => parameter.GetAttributes().SelectAsArray(a => a.ToString());
 public static bool IsCallerStaticClassParameter(IParameterSymbol p)
 => p != null && p.Type != null && p.Type.MetadataName == "PhpTypeInfo" &&
 p.GetAttributes().Any(attr => attr.AttributeClass.MetadataName == "ImportCallerStaticClassAttribute");
 public static bool IsCallerClassParameter(IParameterSymbol p)
 => p != null && p.Type != null &&
 (p.Type.MetadataName == "RuntimeTypeHandle" || p.Type.MetadataName == "Type" || p.Type.MetadataName == "PhpTypeInfo" || p.Type.SpecialType == SpecialType.System_String) &&
 p.GetAttributes().Any(attr => attr.AttributeClass.MetadataName == "ImportCallerClassAttribute");
 private static AttributeData GetCallerInfoAttribute(IParameterSymbol parameter)
 {
     return(parameter.GetAttributes()
            .FirstOrDefault(attr => attr.AttributeClass.IsAny(CallerInfoAttributesToReportOn)));
 }
Example #25
0
        private static void AnalyzeSuppressNullableWarningExpression(SyntaxNodeAnalysisContext context)
        {
            var suppressExpression = (PostfixUnaryExpressionSyntax)context.Node;

            SyntaxNode node = suppressExpression.WalkUpParentheses().Parent;

            if (node is ArgumentSyntax argument)
            {
                IParameterSymbol parameterSymbol = context.SemanticModel.DetermineParameter(
                    argument,
                    cancellationToken: context.CancellationToken);

                if (parameterSymbol?.Type.IsErrorType() == false &&
                    parameterSymbol.Type.IsReferenceType &&
                    parameterSymbol.Type.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    foreach (AttributeData attribute in parameterSymbol.GetAttributes())
                    {
                        INamedTypeSymbol attributeClass = attribute.AttributeClass;

                        if (attributeClass.HasMetadataName(System_Diagnostics_CodeAnalysis_MaybeNullWhenAttribute) ||
                            attributeClass.HasMetadataName(System_Diagnostics_CodeAnalysis_NotNullIfNotNullAttribute) ||
                            attributeClass.HasMetadataName(System_Diagnostics_CodeAnalysis_NotNullWhenAttribute))
                        {
                            return;
                        }
                    }

                    context.ReportDiagnostic(DiagnosticRules.UnnecessaryNullForgivingOperator, suppressExpression.OperatorToken);
                }
            }
            else if (node.IsKind(SyntaxKind.EqualsValueClause))
            {
                if (suppressExpression.Operand.WalkDownParentheses().IsKind(
                        SyntaxKind.NullLiteralExpression,
                        SyntaxKind.DefaultLiteralExpression,
                        SyntaxKind.DefaultExpression))
                {
                    SyntaxNode parent = node.Parent;

                    if (parent.IsKind(SyntaxKind.PropertyDeclaration))
                    {
                        var property = (PropertyDeclarationSyntax)node.Parent;

                        if (IsNullableReferenceType(context, property.Type))
                        {
                            context.ReportDiagnostic(DiagnosticRules.UnnecessaryNullForgivingOperator, node);
                        }
                    }
                    else if (parent.IsKind(SyntaxKind.VariableDeclarator))
                    {
                        SyntaxDebug.Assert(
                            parent.IsParentKind(SyntaxKind.VariableDeclaration) &&
                            parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration, SyntaxKind.LocalDeclarationStatement),
                            parent);

                        if (parent.IsParentKind(SyntaxKind.VariableDeclaration) &&
                            parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration, SyntaxKind.LocalDeclarationStatement))
                        {
                            var variableDeclaration = (VariableDeclarationSyntax)parent.Parent;

                            if (IsNullableReferenceType(context, variableDeclaration.Type))
                            {
                                if (parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration))
                                {
                                    context.ReportDiagnostic(DiagnosticRules.UnnecessaryNullForgivingOperator, node);
                                }
                                else
                                {
                                    context.ReportDiagnostic(DiagnosticRules.UnnecessaryNullForgivingOperator, suppressExpression.OperatorToken);
                                }
                            }
                        }
                    }
                }
            }
 private static AttributeData GetCallerInfoAttribute(IParameterSymbol parameter)
 {
     return parameter.GetAttributes()
         .FirstOrDefault(attr => attr.AttributeClass.IsAny(CallerInfoAttributeTypes));
 }
 private static bool HasCallerInformationAttribute(IParameterSymbol parameter, ImmutableHashSet <INamedTypeSymbol> callerAttributes)
 => parameter.GetAttributes().Any(
     attribute => callerAttributes.Any(
         callerAttribute => SymbolEqualityComparer.Default.Equals(callerAttribute, attribute.AttributeClass)));
Example #28
0
 public static bool IsImmutable(this IParameterSymbol symbol)
 {
     return(symbol.GetAttributes().Any(attr => attr.AttributeClass.Name == "ImmutableAttribute"));
 }
 private static bool HasValidatedNotNullAttribute(IParameterSymbol parameter)
 => parameter.GetAttributes().Any(attr => attr.AttributeClass.Name.Equals("ValidatedNotNullAttribute", StringComparison.OrdinalIgnoreCase));
 public static bool IsLocalsParameter(IParameterSymbol p)
 => p != null && p.Type != null && p.Type.MetadataName == "PhpArray" && p.GetAttributes().Any(attr => attr.AttributeClass.MetadataName == "ImportLocalsAttribute");
Example #31
0
        private static SyntaxList<AttributeListSyntax> GenerateAttributes(
            IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options)
        {
            if (isExplicit)
            {
                return default(SyntaxList<AttributeListSyntax>);
            }

            var attributes = parameter.GetAttributes();
            if (attributes.Length == 0)
            {
                return default(SyntaxList<AttributeListSyntax>);
            }

            return AttributeGenerator.GenerateAttributeLists(attributes, options);
        }
 public static bool IsCallerArgsParameter(IParameterSymbol p)
 => p != null && p.Type != null && p.Type.IsSZArray() && p.GetAttributes().Any(attr => attr.AttributeClass.MetadataName == "ImportCallerArgsAttribute");