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)); }
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) { }
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); }
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"); }
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)); }
protected abstract bool HasNonNullArgumentForParameter(SyntaxNode invocation, IParameterSymbol parameter, int indexOfParameter, SemanticModel semanticModel, CancellationToken cancellationToken);
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); }
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));
private DelegateTypeParameter(Context cx, IParameterSymbol init, IEntity parent, Parameter original) : base(cx, init, parent, original) { }
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); }
protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList <SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
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)); }
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)); }
private static EqualsValueClauseSyntax GetDefaultValueClause(IParameterSymbol symbol) { if (symbol.HasExplicitDefaultValue) { return GetDefaultValueClauseCore(symbol.ExplicitDefaultValue, symbol.Type); } return null; }
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"); }
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); }
public ArgumentParameterMapping(ArgumentSyntax argument, IParameterSymbol parameter) { Argument = argument; Parameter = parameter; }
public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter) { _semanticModel = semanticModel; _parameter = parameter; }
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); }
public ParameterInfoWrapper(IParameterSymbol parameter, MetadataLoadContext metadataLoadContext) { _parameter = parameter; _metadataLoadContext = metadataLoadContext; }
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)); }
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); } }
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)); }
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); } } } } } } } } }
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)); }
public static Named <BaseType> NamedBaseTypeSpecifierFromSymbol(IParameterSymbol paramSymbol) { return(new Named <BaseType>(paramSymbol.Name, BaseTypeSpecifierFromSymbol(paramSymbol.Type))); }
private RoslynParameterMetadata(IParameterSymbol symbol) { this.symbol = symbol; }
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)) }); } }
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)); }
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; }
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))); }
public override void VisitParameter(IParameterSymbol symbol) { UsedTypeSymbols.Add(symbol.Type); base.VisitParameter(symbol); }
private static AttributeData GetCallerInfoAttribute(IParameterSymbol parameter) => parameter.GetAttributes(CallerInfoAttributesToReportOn).FirstOrDefault();
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))); } } }
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 override void VisitParameter(IParameterSymbol symbol) { base.VisitParameter(symbol); }
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)); }
bool IsNUnitThrowsArgument(IParameterSymbol parameterSymbol) { return(IsThrowsArgument(parameterSymbol, "code", s_nUnitMethodNames, nunitAssertType)); }