private static SyntaxNode CreateArgument(
     this ISyntaxFactoryService factory,
     IParameterSymbol parameter)
 {
     return factory.CreateArgument(nameOpt: null, refKind: parameter.RefKind,
         expression: factory.CreateIdentifierName(parameter.Name));
 }
 public ParameterConfiguration(IParameterSymbol thisParameter, List<IParameterSymbol> parametersWithoutDefaultValues, List<IParameterSymbol> remainingEditableParameters, IParameterSymbol paramsParameter)
 {
     ThisParameter = thisParameter;
     ParametersWithoutDefaultValues = parametersWithoutDefaultValues;
     RemainingEditableParameters = remainingEditableParameters;
     ParamsParameter = paramsParameter;
 }
        public static bool TryGetParameterSymbol(ArgumentSyntax argument, ArgumentListSyntax argumentList,
            IMethodSymbol method, out IParameterSymbol parameter)
        {
            parameter = null;
            if (!argumentList.Arguments.Contains(argument) ||
                method == null ||
                method.IsVararg)
            {
                return false;
            }

            if (argument.NameColon != null)
            {
                parameter = method.Parameters
                    .FirstOrDefault(symbol => symbol.Name == argument.NameColon.Name.Identifier.ValueText);
                return parameter != null;
            }

            var argumentIndex = argumentList.Arguments.IndexOf(argument);
            var parameterIndex = argumentIndex;

            if (parameterIndex >= method.Parameters.Length)
            {
                var lastParameter = method.Parameters.Last();
                parameter = lastParameter.IsParams ? lastParameter : null;
                return parameter != null;
            }
            parameter = method.Parameters[parameterIndex];
            return true;
        }
        /// <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;
        }
 static ParameterSyntax CreateParameterSyntax(SemanticModel model, SyntaxNode node, IParameterSymbol p)
 {
     return SyntaxFactory.Parameter(
         SyntaxFactory.List<AttributeListSyntax>(),
         SyntaxFactory.TokenList(),
         SyntaxFactory.ParseTypeName(p.Type.ToMinimalDisplayString(model, node.SpanStart)),
         SyntaxFactory.Identifier(p.Name),
         null
     );
 }
 static ParameterSyntax CreateParameterSyntax(SemanticModel model, SyntaxNode node, IParameterSymbol p)
 {
     return SyntaxFactory.Parameter(
         SyntaxFactory.List<AttributeListSyntax>(),
         SyntaxFactory.TokenList(),
         null,
         SyntaxFactory.Identifier(p.Name),
         null
     );
 }
        /// <summary>
        ///     Builds the type as string of the <paramref name="parameterSymbol"/>.
        /// </summary>
        /// <param name="parameterSymbol">
        ///     The parameter type that you want as string.
        /// </param>
        /// <param name="isShort">
        ///     Expects to have a short type.
        /// </param>
        /// <returns>
        ///     The type of the <paramref name="parameterSymbol" /> as <see cref="string"/>.
        /// </returns>
        public string BuildArgumentType(IParameterSymbol parameterSymbol,
                                        bool isShort)
        {
            if (!isShort)
            {
                return parameterSymbol.Type.ToString();
            }

            var shortType = CleanFullType(parameterSymbol);
            return shortType;
        }
        static bool HasNotNullContract(SemanticModel semanticModel, IParameterSymbol parameterSymbol, BlockSyntax bodyStatement)
        {
            foreach (var expressions in bodyStatement.DescendantNodes().OfType<ExpressionStatementSyntax>())
            {
                var identifiers = expressions.DescendantNodes().OfType<IdentifierNameSyntax>();

                if (Enumerable.SequenceEqual(identifiers.Select(i => i.Identifier.Text), new List<string>() { "Contract", "Requires", parameterSymbol.Name }))
                {
                    return true;
                }
            }
            return false;
        }
 protected static SignatureHelpParameter Convert(
     IParameterSymbol parameter,
     SemanticModel semanticModel,
     int position,
     IDocumentationCommentFormattingService formatter,
     CancellationToken cancellationToken)
 {
     return new SignatureHelpParameter(
         parameter.Name,
         parameter.IsOptional,
         parameter.GetDocumentationPartsFactory(semanticModel, position, formatter),
         parameter.ToMinimalDisplayParts(semanticModel, position));
 }
Пример #10
0
        internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional)
        {
            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            return SyntaxFactory.Parameter(p.Name.ToIdentifierToken())
                    .WithAttributeLists(GenerateAttributes(p, isExplicit, options))
                    .WithModifiers(GenerateModifiers(p, isFirstParam))
                    .WithType(p.Type.GenerateTypeSyntax())
                    .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional));
        }
        /// <summary>
        ///     Builds models representing methods of the factories.
        /// </summary>
        /// <param name="concreteClassSymbol">
        ///     Represents the concrete class.
        /// </param>
        /// <param name="fields">
        ///     Fields available in the factory.
        /// </param>
        /// <param name="injectedParameters">
        ///     The injected parameters in the factory.
        /// </param>
        /// <param name="factoryMethods">
        ///     The factory methods retrieved with Roslyn.
        /// </param>
        /// <param name="factoryInterfaceName">
        ///     The interface name of the factory.
        /// </param>
        /// <returns>
        ///     Models representing the factory methods.
        /// </returns>
        public IEnumerable<Method> Build(INamedTypeSymbol concreteClassSymbol,
                                         IEnumerable<Field> fields,
                                         IParameterSymbol[] injectedParameters,
                                         IMethodSymbol[] factoryMethods,
                                         string factoryInterfaceName)
        {
            if (!factoryMethods.Any())
            {
                return Enumerable.Empty<Method>();
            }

            fields = fields as Field[] ?? fields.ToArray();
            var methods = new List<Method>();

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var factoryMethod in factoryMethods)
            {
                var constructor = GetConstructorFromFactoryMethod(factoryMethod, concreteClassSymbol);
                var factoryMethodParameters = factoryMethod.Parameters;

                var arguments = this.argumentsBuilderService.BuildMethodArgument(factoryMethodParameters)
                                    .ToArray();
                var constructorArguments = this.BuildConstructorParameters(constructor, arguments, fields, injectedParameters, factoryInterfaceName);
                var genericArguments = this.genericTypeBuilderService.Build(factoryMethod.TypeParameters);

                if (this.writeXmlDoc)
                {
                    var xmlComments = BuildXmlDoc(factoryMethod);
                    methods.Add(new Method("Create", factoryMethod.ReturnType.ToString(), concreteClassSymbol.ToString(), arguments, constructorArguments, genericArguments, xmlComments));
                }
                else
                {
                    methods.Add(new Method("Create", factoryMethod.ReturnType.ToString(), concreteClassSymbol.ToString(), arguments, constructorArguments, genericArguments, string.Empty));
                }
            }

            return methods;
        }
 public CodeGenerationConversionSymbol(
     INamedTypeSymbol containingType,
     IList<AttributeData> attributes,
     Accessibility declaredAccessibility,
     DeclarationModifiers modifiers,
     ITypeSymbol toType,
     IParameterSymbol fromType,
     bool isImplicit,
     IList<AttributeData> toTypeAttributes) :
     base(containingType,
         attributes,
         declaredAccessibility,
         modifiers,
         returnType: toType,
         explicitInterfaceSymbolOpt: null,
         name: isImplicit ?
             WellKnownMemberNames.ImplicitConversionName :
             WellKnownMemberNames.ExplicitConversionName,
         typeParameters: SpecializedCollections.EmptyList<ITypeParameterSymbol>(),
         parameters: new List<IParameterSymbol>(SpecializedCollections.SingletonEnumerable(fromType)),
         returnTypeAttributes: toTypeAttributes)
 {
 }
Пример #13
0
		string GetParameterVariableMarkup (IParameterSymbol parameter)
		{
			if (parameter == null)
				throw new ArgumentNullException ("parameter");

			var result = new StringBuilder ();
			AppendParameter (result, parameter);

			if (parameter.HasExplicitDefaultValue) {
				if (options.GetOption (CSharpFormattingOptions.SpacingAroundBinaryOperator) == BinaryOperatorSpacingOptions.Single) {
					result.Append (" = ");
				} else {
					result.Append ("=");
				}
				AppendConstant (result, parameter.Type, parameter.ExplicitDefaultValue);
			}

			return result.ToString ();
		}
 private static Diagnostic GetRemoveSetterDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
 {
     // Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
     return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary<string, string> { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
 }
Пример #15
0
 internal static bool TryGetMatchingArgument(this InvocationExpressionSyntax invocation, IParameterSymbol parameter, out ArgumentSyntax argument)
 {
     return(TryGetMatchingArgument(invocation?.ArgumentList, parameter, out argument));
 }
 private static bool IsParameterName(IParameterSymbol parameter)
 {
     return(parameter.Name == "paramName" || parameter.Name == "parameterName");
 }
Пример #17
0
 bool IsXunitThrowsArgument(IParameterSymbol parameterSymbol)
 {
     return(IsThrowsArgument(parameterSymbol, "testCode", s_xUnitMethodNames, xunitAssertType));
 }
 private static SyntaxNode CreateArgument(
     this SyntaxGenerator factory,
     IParameterSymbol parameter)
 {
     return factory.Argument(parameter.RefKind, factory.IdentifierName(parameter.Name));
 }
Пример #19
0
 protected abstract bool HasNonNullArgumentForParameter(SyntaxNode invocation, IParameterSymbol parameter, int indexOfParameter, SemanticModel semanticModel, CancellationToken cancellationToken);
Пример #20
0
        private static Expression PreprocessParameter(Expression expression, IParameterSymbol parameter)
        {
            if (parameter == null)
            {
                return(expression);
            }

            var parameterType = parameter.Type;

            if (parameterType == null)
            {
                return(expression);
            }

            var effectiveExpression = expression;

            var typeDestination = parameterType;

            if (typeDestination.IsReferenceType)
            {
                var literal = expression as Literal;
                if (literal != null && literal.Value.IsNull)
                {
                    effectiveExpression = new Conversion
                    {
                        Type    = typeDestination,
                        Operand = effectiveExpression
                    };
                }
            }

            if (typeDestination.IsValueType && expression is ThisReference)
            {
                effectiveExpression = new PointerIndirectionOperator {
                    Operand = expression
                };
            }

            if (expression.IsStaticWrapperCall())
            {
                effectiveExpression = new Cast
                {
                    Type                  = typeDestination,
                    Operand               = effectiveExpression,
                    Reference             = parameter.RefKind.HasFlag(RefKind.Ref) || parameter.RefKind.HasFlag(RefKind.Out),
                    CCast                 = true,
                    UseEnumUnderlyingType = true,
                };
            }

            if (effectiveExpression.IsReference && (effectiveExpression.Type.TypeKind == TypeKind.Interface) && parameter.Type.SpecialType == SpecialType.System_Object)
            {
                effectiveExpression = new Conversion
                {
                    ConversionKind = ConversionKind.ImplicitReference,
                    IsReference    = true,
                    Operand        = expression,
                    TypeSource     = effectiveExpression.Type,
                    Type           = parameter.Type
                };
            }

            return(effectiveExpression);
        }
Пример #21
0
 public static new DelegateTypeParameter Create(Context cx, IParameterSymbol param, IEntity parent, Parameter original = null) =>
 // We need to use a different cache key than `param` to avoid mixing up
 // `DelegateTypeParameter`s and `Parameter`s
 DelegateTypeParameterFactory.Instance.CreateEntity(cx, (typeof(DelegateTypeParameter), new SymbolEqualityWrapper(param)), (param, parent, original));
Пример #22
0
 private DelegateTypeParameter(Context cx, IParameterSymbol init, IEntity parent, Parameter original)
     : base(cx, init, parent, original)
 {
 }
Пример #23
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AssignDefaultValueToOutParameter))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(
                    root,
                    context.Span,
                    out SyntaxNode node,
                    predicate: f => f.IsKind(SyntaxKind.MethodDeclaration) || f is StatementSyntax))
            {
                return;
            }

            Diagnostic diagnostic = context.Diagnostics[0];

            StatementSyntax statement = null;

            if (!node.IsKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement))
            {
                statement = (StatementSyntax)node;

                node = node.FirstAncestor(f => f.IsKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement));

                Debug.Assert(node != null, "Containing method or local function not found.");

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

            SyntaxNode bodyOrExpressionBody = GetBodyOrExpressionBody(node);

            if (bodyOrExpressionBody == null)
            {
                return;
            }

            if (ContainsYieldWalker.ContainsYield(bodyOrExpressionBody))
            {
                return;
            }

            SemanticModel semanticModel = await context.Document.GetSemanticModelAsync().ConfigureAwait(false);

            DataFlowAnalysis dataFlowAnalysis = AnalyzeDataFlow(bodyOrExpressionBody, semanticModel);

            // Flow analysis APIs do not work with local functions: https://github.com/dotnet/roslyn/issues/14214
            if (!dataFlowAnalysis.Succeeded)
            {
                return;
            }

            var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(node);

            ImmutableArray <IParameterSymbol> parameters = methodSymbol.Parameters;

            ImmutableArray <ISymbol> alwaysAssigned = dataFlowAnalysis.AlwaysAssigned;

            IParameterSymbol singleParameter = null;
            bool             isAny           = false;

            foreach (IParameterSymbol parameter in parameters)
            {
                if (parameter.RefKind == RefKind.Out &&
                    !alwaysAssigned.Contains(parameter))
                {
                    if (singleParameter == null)
                    {
                        singleParameter = parameter;
                        isAny           = true;
                    }
                    else
                    {
                        singleParameter = null;
                        break;
                    }
                }
            }

            Debug.Assert(isAny, "No unassigned 'out' parameter found.");

            if (!isAny)
            {
                return;
            }

            CodeAction codeAction = CodeAction.Create(
                (singleParameter != null)
                    ? $"Assign default value to parameter '{singleParameter.Name}'"
                    : "Assign default value to parameters",
                cancellationToken => RefactorAsync(context.Document, node, statement, bodyOrExpressionBody, parameters, alwaysAssigned, semanticModel, cancellationToken),
                base.GetEquivalenceKey(diagnostic));

            context.RegisterCodeFix(codeAction, diagnostic);
        }
Пример #24
0
 protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList <SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
Пример #25
0
 private static bool AreParameterTypesEqual(IParameterSymbol p1, IParameterSymbol p2)
 {
     return(Equals(p1.Type, p2.Type) ||
            p1.Type.Is(TypeKind.TypeParameter) && p2.Type.Is(TypeKind.TypeParameter) ||
            Equals(p1.Type.OriginalDefinition, p2.Type.OriginalDefinition));
 }
Пример #26
0
 private static ParameterSyntax GetParameter(IParameterSymbol p, IFilterVisitor filterVisitor, bool isThisParameter = false)
 {
     return SyntaxFactory.Parameter(
         GetAttributes(p, filterVisitor, true),
         SyntaxFactory.TokenList(GetParameterModifiers(p, isThisParameter)),
         GetTypeSyntax(p.Type),
         SyntaxFactory.Identifier(p.Name),
         GetDefaultValueClause(p));
 }
Пример #27
0
 private static EqualsValueClauseSyntax GetDefaultValueClause(IParameterSymbol symbol)
 {
     if (symbol.HasExplicitDefaultValue)
     {
         return GetDefaultValueClauseCore(symbol.ExplicitDefaultValue, symbol.Type);
     }
     return null;
 }
Пример #28
0
 public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) :
     base(compilation, type)
 {
     Contract.ThrowIfNull(parameterSymbol);
     _parameterSymbol = parameterSymbol;
 }
 private static bool IsMessage(IParameterSymbol parameter)
 {
     return(parameter.Name == "message");
 }
Пример #30
0
            private async Task <IEnumerable <SymbolDisplayPart> > GetInitializerSourcePartsAsync(IParameterSymbol symbol)
            {
                var syntax = await this.GetFirstDeclaration <ParameterSyntax>(symbol).ConfigureAwait(false);

                if (syntax != null)
                {
                    return(await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(false));
                }

                return(null);
            }
Пример #31
0
 public ArgumentParameterMapping(ArgumentSyntax argument, IParameterSymbol parameter)
 {
     Argument  = argument;
     Parameter = parameter;
 }
Пример #32
0
 public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter)
 {
     _semanticModel = semanticModel;
     _parameter     = parameter;
 }
Пример #33
0
 public bool TryGetParameterSymbol(ArgumentSyntax argument, out IParameterSymbol parameter)
 {
     return(TryGetParameterSymbol(argument, invocation.ArgumentList, MethodSymbol, out parameter));
 }
 private static Diagnostic GetDefaultDiagnostic(IParameterSymbol parameter, INamedTypeSymbol attributeType)
 {
     // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
     return parameter.Locations.CreateDiagnostic(DefaultRule, new Dictionary<string, string> { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name);
 }
Пример #35
0
 public ParameterInfoWrapper(IParameterSymbol parameter, MetadataLoadContext metadataLoadContext)
 {
     _parameter           = parameter;
     _metadataLoadContext = metadataLoadContext;
 }
Пример #36
0
        internal static bool TryGetMatchingArgument(this ArgumentListSyntax argumentList, IParameterSymbol parameter, out ArgumentSyntax argument)
        {
            argument = null;
            if (argumentList == null ||
                argumentList.Arguments.Count == 0 ||
                parameter == null ||
                parameter.IsParams)
            {
                return(false);
            }

            if (argumentList.Arguments.TrySingle(x => x.NameColon?.Name.Identifier.ValueText == parameter.Name, out argument))
            {
                return(true);
            }

            return(argumentList.Arguments.TryElementAt(parameter.Ordinal, out argument));
        }
Пример #37
0
 protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol);
        private static void AnalyzeClassDeclaration(SyntaxNodeAnalysisContext context)
        {
            var classDeclaration = (ClassDeclarationSyntax)context.Node;

            if (!classDeclaration.Identifier.ValueText.EndsWith("Extensions", StringComparison.Ordinal))
            {
                return;
            }

            if (!classDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword))
            {
                return;
            }

            if (!classDeclaration.IsParentKind(SyntaxKind.NamespaceDeclaration, SyntaxKind.CompilationUnit))
            {
                return;
            }

            if (!SyntaxAccessibility <ClassDeclarationSyntax> .Instance.GetAccessibility(classDeclaration).Is(Accessibility.Public, Accessibility.Internal))
            {
                return;
            }

            foreach (MemberDeclarationSyntax member in classDeclaration.Members)
            {
                if (!(member is MethodDeclarationSyntax methodDeclaration))
                {
                    continue;
                }

                if (!methodDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword))
                {
                    continue;
                }

                if (!SyntaxAccessibility <MethodDeclarationSyntax> .Instance.GetAccessibility(methodDeclaration).Is(Accessibility.Public, Accessibility.Internal))
                {
                    continue;
                }

                ParameterSyntax parameter = methodDeclaration.ParameterList?.Parameters.FirstOrDefault();

                if (parameter == null)
                {
                    continue;
                }

                if (parameter.Default != null)
                {
                    continue;
                }

                if (parameter.Type.IsKind(SyntaxKind.PointerType))
                {
                    continue;
                }

                if (parameter.Modifiers.Contains(SyntaxKind.ParamsKeyword))
                {
                    continue;
                }

                bool isThis = false;
                bool isIn   = false;
                bool isRef  = false;

                foreach (SyntaxToken modifier in parameter.Modifiers)
                {
                    SyntaxKind kind = modifier.Kind();

                    if (kind == SyntaxKind.ThisKeyword)
                    {
                        isThis = true;
                        break;
                    }
                    else if (kind == SyntaxKind.InKeyword)
                    {
                        isIn = true;
                    }
                    else if (kind == SyntaxKind.RefKeyword)
                    {
                        isRef = true;
                    }

                    if (isThis)
                    {
                        break;
                    }
                }

                if (isThis)
                {
                    continue;
                }

                if (isIn)
                {
                    IParameterSymbol parameterSymbol = context.SemanticModel.GetDeclaredSymbol(parameter, context.CancellationToken);

                    ITypeSymbol typeSymbol = parameterSymbol.Type;

                    if (!typeSymbol.IsValueType)
                    {
                        continue;
                    }

                    if (typeSymbol.Kind == SymbolKind.TypeParameter)
                    {
                        continue;
                    }
                }
                else if (isRef)
                {
                    IParameterSymbol parameterSymbol = context.SemanticModel.GetDeclaredSymbol(parameter, context.CancellationToken);

                    if (!parameterSymbol.Type.IsValueType)
                    {
                        continue;
                    }
                }

                DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.MakeMethodExtensionMethod, methodDeclaration.Identifier);
            }
        }
Пример #39
0
        private static TNode ReplaceReferencesToParameterWithValue <TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node)
            where TNode : SyntaxNode
        {
            var rewriter = new Rewriter(semanticModel, parameter);

            return((TNode)rewriter.Visit(node));
        }
Пример #40
0
 private static bool IsGenericTypeParameter(IParameterSymbol parameterSymbol)
 {
     return(parameterSymbol.ContainingType.ConstructedFrom.TypeParameters.Any(parameterSymbol.Type.Equals));
 }
 private static Diagnostic GetIncreaseVisibilityDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
 {
     // If '{0}' is the property accessor for positional argument '{1}', make it public.
     return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary<string, string> { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
 }
        public static void Analyze(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation)
        {
            ExpressionSyntax expression = invocation.Expression;

            if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true)
            {
                var memberAccess = (MemberAccessExpressionSyntax)expression;

                ArgumentListSyntax argumentList = invocation.ArgumentList;

                if (argumentList != null)
                {
                    SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

                    if (arguments.Any())
                    {
                        SimpleNameSyntax name = memberAccess.Name;

                        if (name?.Identifier.ValueText == "Join")
                        {
                            SemanticModel     semanticModel     = context.SemanticModel;
                            CancellationToken cancellationToken = context.CancellationToken;

                            MethodInfo info = semanticModel.GetMethodInfo(invocation, cancellationToken);

                            if (info.IsValid &&
                                info.HasName("Join") &&
                                info.IsContainingType(SpecialType.System_String) &&
                                info.IsPublic &&
                                info.IsStatic &&
                                info.IsReturnType(SpecialType.System_String) &&
                                !info.IsGenericMethod &&
                                !info.IsExtensionMethod)
                            {
                                ImmutableArray <IParameterSymbol> parameters = info.Parameters;

                                if (parameters.Length == 2 &&
                                    parameters[0].Type.IsString())
                                {
                                    IParameterSymbol parameter = parameters[1];

                                    if (parameter.IsParamsOf(SpecialType.System_String) ||
                                        parameter.IsParamsOf(SpecialType.System_Object) ||
                                        parameter.Type.IsConstructedFromIEnumerableOfT())
                                    {
                                        ArgumentSyntax   firstArgument      = arguments.First();
                                        ExpressionSyntax argumentExpression = firstArgument.Expression;

                                        if (argumentExpression != null &&
                                            CSharpAnalysis.IsEmptyString(argumentExpression, semanticModel, cancellationToken) &&
                                            !invocation.ContainsDirectives(TextSpan.FromBounds(invocation.SpanStart, firstArgument.Span.End)))
                                        {
                                            context.ReportDiagnostic(
                                                DiagnosticDescriptors.CallStringConcatInsteadOfStringJoin,
                                                name);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #43
0
		void AppendParameter (StringBuilder result, IParameterSymbol parameter)
		{
			if (parameter == null)
				return;
			if (parameter.RefKind == RefKind.Out) {
				result.Append (Highlight ("out ", colorStyle.KeywordParameter));
			} else if (parameter.RefKind == RefKind.Ref) {
				result.Append (Highlight ("ref ", colorStyle.KeywordParameter));
			} else if (parameter.IsParams) {
				result.Append (Highlight ("params ", colorStyle.KeywordParameter));
			}
			result.Append (GetTypeReferenceString (parameter.Type));
			result.Append (" ");
			result.Append (FilterEntityName (parameter.Name));
		}
Пример #44
0
 public static Named <BaseType> NamedBaseTypeSpecifierFromSymbol(IParameterSymbol paramSymbol)
 {
     return(new Named <BaseType>(paramSymbol.Name, BaseTypeSpecifierFromSymbol(paramSymbol.Type)));
 }
 private RoslynParameterMetadata(IParameterSymbol symbol)
 {
     this.symbol = symbol;
 }
Пример #46
0
 public override void VisitParameter(IParameterSymbol symbol)
 {
     if (_finished || _symbolPredicate == null || _symbolPredicate(symbol))
     {
         AddDocumentForMember(symbol, false, new MetadataItems
         {
             new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString()),
             new MetadataItem(CodeAnalysisKeys.Type, DocumentFor(symbol.Type))
         });
     }
 }
Пример #47
0
 private static IEnumerable<SyntaxToken> GetParameterModifiers(IParameterSymbol parameter, bool isThisParameter)
 {
     if (isThisParameter)
     {
         yield return SyntaxFactory.Token(SyntaxKind.ThisKeyword);
     }
     switch (parameter.RefKind)
     {
         case RefKind.None:
             break;
         case RefKind.Ref:
             yield return SyntaxFactory.Token(SyntaxKind.RefKeyword);
             break;
         case RefKind.Out:
             yield return SyntaxFactory.Token(SyntaxKind.OutKeyword);
             break;
         default:
             break;
     }
     if (parameter.IsParams)
     {
         yield return SyntaxFactory.Token(SyntaxKind.ParamsKeyword);
     }
 }
            private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
            {
                if (symbol.IsOptional)
                {
                    var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
                    if (!initializerParts.IsDefaultOrEmpty)
                    {
                        var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
                        parts.AddRange(Space());
                        parts.AddRange(Punctuation("="));
                        parts.AddRange(Space());
                        parts.AddRange(initializerParts);

                        AddToGroup(SymbolDescriptionGroups.MainDescription,
                            Description(FeaturesResources.parameter), parts);

                        return;
                    }
                }

                AddToGroup(SymbolDescriptionGroups.MainDescription,
                    Description(FeaturesResources.parameter),
                    ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
            }
Пример #49
0
        private static bool IsSameParameter(IParameterSymbol parameterSymbol, IEnumerable<ParameterSyntax> parameters)
        {
            var parametersFromSymbol = parameterSymbol.Locations.Select(l => l.FindToken().AncestorAndSelf<ParameterSyntax>());
            if (parameters.Any(p => parametersFromSymbol.Any(p2 => p == p2)))
            {
                return true;
            }

            return false;
        }
Пример #50
0
 private static ExpressionSyntax GenerateEqualsValueClauseWorker(
     IParameterSymbol parameter,
     object value)
 {
     return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true);
 }
 private static ParameterSyntax GetParameterSyntaxFromParameterSymbol(IParameterSymbol symbolParameter)
 {
     return(SyntaxFactory.Parameter(SyntaxFactory.Identifier(symbolParameter.Name))
            .WithType(SyntaxFactory.ParseTypeName(symbolParameter.Type.Name)));
 }
Пример #52
0
 public override void VisitParameter(IParameterSymbol symbol)
 {
     UsedTypeSymbols.Add(symbol.Type);
     base.VisitParameter(symbol);
 }
Пример #53
0
 public ArgumentParameterMapping(ArgumentSyntax argument, IParameterSymbol parameter)
 {
     Argument = argument;
     Parameter = parameter;
 }
 private static AttributeData GetCallerInfoAttribute(IParameterSymbol parameter) =>
 parameter.GetAttributes(CallerInfoAttributesToReportOn).FirstOrDefault();
Пример #55
0
        private static EqualsValueClauseSyntax GenerateEqualsValueClause(
            IParameterSymbol parameter,
            bool isExplicit,
            bool seenOptional)
        {
            if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut())
            {
                if (parameter.HasExplicitDefaultValue || seenOptional)
                {
                    var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null;
                    if (defaultValue is DateTime)
                    {
                        return null;
                    }

                    return SyntaxFactory.EqualsValueClause(GenerateEqualsValueClauseWorker(parameter, defaultValue));
                }
            }

            return null;
        }
        private static void AnalyzeMethodSymbol(SymbolAnalysisContext analysisContext)
        {
            var methodSymbol = (IMethodSymbol)analysisContext.Symbol;

            if (!methodSymbol.MatchesConfiguredVisibility(analysisContext.Options, Rule, analysisContext.CancellationToken) ||
                !(methodSymbol.CanBeReferencedByName || methodSymbol.IsImplementationOfAnyExplicitInterfaceMember()) ||
                !methodSymbol.Locations.Any(x => x.IsInSource) ||
                string.IsNullOrWhiteSpace(methodSymbol.Name))
            {
                return;
            }

            if (!methodSymbol.IsOverride && !methodSymbol.IsImplementationOfAnyImplicitInterfaceMember())
            {
                return;
            }

            ImmutableArray <IMethodSymbol> originalDefinitions = GetOriginalDefinitions(methodSymbol);

            if (originalDefinitions.Length == 0)
            {
                // We did not find any original definitions so we don't have to do anything.
                // This can happen when the method has an override modifier,
                // but does not have any valid method it is overriding.
                return;
            }

            IMethodSymbol?bestMatch      = null;
            int           bestMatchScore = -1;

            foreach (var originalDefinition in originalDefinitions)
            {
                // always prefer the method override, if it is available
                // (the overridden method will always be the first item in the list.)
                if (originalDefinition.ContainingType.TypeKind != TypeKind.Interface)
                {
                    bestMatch = originalDefinition;
                    break;
                }

                int currentMatchScore = 0;
                for (int i = 0; i < methodSymbol.Parameters.Length; i++)
                {
                    IParameterSymbol currentParameter  = methodSymbol.Parameters[i];
                    IParameterSymbol originalParameter = originalDefinition.Parameters[i];

                    if (currentParameter.Name == originalParameter.Name)
                    {
                        currentMatchScore++;
                    }
                }

                if (currentMatchScore > bestMatchScore)
                {
                    bestMatch      = originalDefinition;
                    bestMatchScore = currentMatchScore;

                    if (bestMatchScore == methodSymbol.Parameters.Length)
                    {
                        break;
                    }
                }
            }

            if (bestMatch == null)
            {
                return;
            }

            for (int i = 0; i < methodSymbol.Parameters.Length; i++)
            {
                IParameterSymbol currentParameter   = methodSymbol.Parameters[i];
                IParameterSymbol bestMatchParameter = bestMatch.Parameters[i];

                if (currentParameter.Name != bestMatchParameter.Name)
                {
                    var properties = ImmutableDictionary <string, string> .Empty.SetItem(NewNamePropertyName, bestMatchParameter.Name);

                    analysisContext.ReportDiagnostic(Diagnostic.Create(Rule, currentParameter.Locations.First(), properties, methodSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), currentParameter.Name, bestMatchParameter.Name, bestMatch.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)));
                }
            }
        }
Пример #57
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);
        }
Пример #58
0
 public override void VisitParameter(IParameterSymbol symbol)
 {
     base.VisitParameter(symbol);
 }
Пример #59
0
        private static SyntaxTokenList GenerateModifiers(
            IParameterSymbol parameter, bool isFirstParam)
        {
            if (isFirstParam &&
                parameter.ContainingSymbol is IMethodSymbol &&
                ((IMethodSymbol)parameter.ContainingSymbol).IsExtensionMethod)
            {
                return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ThisKeyword));
            }

            if (parameter.IsParams)
            {
                return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamsKeyword));
            }

            return parameter.RefKind == RefKind.None
                ? new SyntaxTokenList()
                : parameter.RefKind == RefKind.Out
                    ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.OutKeyword))
                    : SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword));
        }
Пример #60
0
 bool IsNUnitThrowsArgument(IParameterSymbol parameterSymbol)
 {
     return(IsThrowsArgument(parameterSymbol, "code", s_nUnitMethodNames, nunitAssertType));
 }