public WithConstructorInitializerLocalsBinder(Binder enclosing, ConstructorDeclarationSyntax declaration) : base(enclosing, enclosing.Flags) { Debug.Assert(declaration.Initializer != null); this.scope = declaration; this.initializerArgumentList = declaration.Initializer.ArgumentList; }
public static InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax sourceExpression, SimpleNameSyntax methodName, ArgumentListSyntax argumentList) => SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, sourceExpression, methodName), argumentList);
public static IParameterSymbol GetParameterSymbol(ArgumentSyntax argument, ArgumentListSyntax argumentList, IMethodSymbol method) { if (!argumentList.Arguments.Contains(argument) || method == null) { return null; } if (argument.NameColon != null) { return method.Parameters .FirstOrDefault(symbol => symbol.Name == argument.NameColon.Name.Identifier.ValueText); } var argumentIndex = argumentList.Arguments.IndexOf(argument); var parameterIndex = argumentIndex; if (parameterIndex >= method.Parameters.Length) { var p = method.Parameters.Last(); return p.IsParams ? p : null; } var parameter = method.Parameters[parameterIndex]; return parameter; }
public override FlatOperand Resolve(ExpressionSyntax expression, ArgumentListSyntax argumentList, TypeInfo result_type, SymbolInfo si, FlatOperand into_lvalue, Function function, List<FlatStatement> instructions) { FlatOperand fop_subject; if (expression is IdentifierNameSyntax) { // typeof this fop_subject = FlatOperand.ThisRef(FlatValue.FromType(result_type.ConvertedType)); } else if (expression is MemberAccessExpressionSyntax) { MemberAccessExpressionSyntax meas = (MemberAccessExpressionSyntax)expression; fop_subject = function.ResolveExpression(meas.Expression, null, instructions); } else { throw new NotImplementedException("GetMetaTable on expression type " + expression.GetType().ToString()); } if (into_lvalue == null) { FlatOperand fop_register = function.AllocateRegister(""); into_lvalue = fop_register.GetLValue(function, instructions); } instructions.Add(FlatStatement.GETMETATABLE(into_lvalue, fop_subject)); return into_lvalue.AsRValue(FlatValue.Table()); }
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; }
public WithConstructorInitializerLocalsBinder(Binder enclosing, ArgumentListSyntax initializerArgumentList) : base(enclosing, enclosing.Flags) { Debug.Assert(initializerArgumentList != null); this.scope = initializerArgumentList; this.initializerArgumentList = initializerArgumentList; }
private static bool AnyArgumentIsValueType(ArgumentListSyntax argumentList, SemanticModel semanticModel) { return argumentList.Arguments.Any(argument => { var type = semanticModel.GetTypeInfo(argument.Expression).Type; return type != null && type.IsValueType; }); }
public static bool HasFalseArgument(ArgumentListSyntax argumentList) { if (argumentList.Arguments.Count != 1) return false; if (!argumentList.Arguments[0].Expression.IsKind(SyntaxKind.FalseLiteralExpression)) return false; return true; }
public FixConstructor(IMethodSymbol constructor, ArgumentListSyntax node, string sourcename, SemanticModel semanticModel, Document document) { this.constructor = constructor; this.node = node; this.sourcename = sourcename; this.semanticModel = semanticModel; this.document = document; Title = $"Fill constructor from {sourcename}"; }
private async Task<Document> CollapseParameters(Document document, ArgumentListSyntax argumentListNode, CancellationToken cancellationToken) { ArgumentListSyntax updatedParameterList = SyntaxFactory.ArgumentList(argumentListNode.OpenParenToken, SyntaxFactory.SeparatedList(argumentListNode.Arguments .Select(argument => argument.WithoutLeadingTrivia().WithoutTrailingTrivia()).ToList()), argumentListNode.CloseParenToken); SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = root.ReplaceNode(argumentListNode, updatedParameterList); return await Formatter.FormatAsync(document.WithSyntaxRoot(newRoot), updatedParameterList.FullSpan); }
private static void ReportForUnimplemented(CodeRefactoringContext context, IMethodSymbol constructor, SemanticModel semanticModel, ArgumentListSyntax node, TypeInfo typeSymbol) { var unimplemntedParameters = constructor.Parameters.Skip(node.Arguments.Count); var typesymbols = semanticModel.GetTypeSymbols(node, typeSymbol); var symbols = typesymbols.Where(x => ImplementsSomethingFor(x.TypeSymbol, unimplemntedParameters)) .Distinct(); foreach(var symbol in symbols) context.RegisterRefactoring( new FixConstructor(constructor, node, symbol.Name, semanticModel, context.Document)); }
private static void CheckCall(SyntaxNode node, ArgumentListSyntax argumentList, SyntaxNodeAnalysisContext context) { var invokedMethodSymbol = context.SemanticModel.GetSymbolInfo(node).Symbol as IMethodSymbol; if (invokedMethodSymbol == null || !invokedMethodSymbol.Parameters.Any() || !invokedMethodSymbol.Parameters.Last().IsParams || argumentList == null) { return; } if (IsInvocationWithExplicitArray(argumentList, invokedMethodSymbol, context.SemanticModel)) { return; } var argumentTypes = argumentList.Arguments .Select(arg => context.SemanticModel.GetTypeInfo(arg.Expression).Type) .ToList(); if (argumentTypes.Any(type => type is IErrorTypeSymbol)) { return; } var possibleOtherMethods = invokedMethodSymbol.ContainingType.GetMembers(invokedMethodSymbol.Name) .OfType<IMethodSymbol>() .Where(m => !m.IsVararg) .Where(m => m.MethodKind == invokedMethodSymbol.MethodKind) .Where(m => !invokedMethodSymbol.Equals(m)) .Where(m => m.Parameters.Any() && !m.Parameters.Last().IsParams); var otherMethod = possibleOtherMethods.FirstOrDefault(possibleOtherMethod => ArgumentsMatchParameters( argumentList, argumentTypes.Select(t => t as INamedTypeSymbol).ToList(), possibleOtherMethod, context.SemanticModel)); if (otherMethod != null) { context.ReportDiagnostic(Diagnostic.Create( Rule, node.GetLocation(), otherMethod.ToMinimalDisplayString(context.SemanticModel, node.SpanStart))); } }
private void Execute(MethodInformation methodInformation, List<object> arguments, ArgumentListSyntax argumentList) { if (!argumentList.Arguments.Any()) { return; } try { methodInformation.MethodAction.Invoke(arguments); } catch (Exception ex) { while (ex.InnerException != null) { ex = ex.InnerException; } var diag = Diagnostic.Create(diagnosticDescriptor, argumentList.Arguments[methodInformation.ArgumentIndex].GetLocation(), ex.Message); context.ReportDiagnostic(diag); } }
/// <summary> /// Returns the candidate parameter types from the /// specified argument list. /// </summary> /// <param name="argumentList">ArgumentListSyntax</param> /// <param name="node">IDataFlowNode</param> /// <returns>ITypeSymbols</returns> private static IDictionary<int, ISet<ITypeSymbol>> GetCandidateParameterTypes( ArgumentListSyntax argumentList, IDataFlowNode node) { var candidateTypes = new Dictionary<int, ISet<ITypeSymbol>>(); if (argumentList == null) { return candidateTypes; } for (int idx = 0; idx < argumentList.Arguments.Count; idx++) { var argSymbol = node.Summary.SemanticModel.GetSymbolInfo( argumentList.Arguments[idx].Expression).Symbol; if (argSymbol != null) { candidateTypes.Add(idx, node.DataFlowInfo.GetCandidateTypesOfSymbol(argSymbol)); } } return candidateTypes; }
private async Task<Document> BreakParametersApart(Document document, ArgumentListSyntax argumentListNode, CancellationToken cancellationToken) { if (argumentListNode.Arguments.Count < 2) return document; ArgumentSyntax firstParameter = argumentListNode.Arguments.First(); List<ArgumentSyntax> updatedParameters = new List<ArgumentSyntax>(); updatedParameters.Add(firstParameter.WithoutLeadingTrivia().WithoutTrailingTrivia()); foreach (ArgumentSyntax parameter in argumentListNode.Arguments.Skip(1).ToList()) updatedParameters.Add(parameter .WithoutTrailingTrivia() .WithLeadingTrivia(SyntaxFactory.EndOfLine("\r\n"), GetIndentTrivia(argumentListNode))); ArgumentListSyntax updatedParameterList = SyntaxFactory.ArgumentList(argumentListNode.OpenParenToken, SyntaxFactory.SeparatedList(updatedParameters), argumentListNode.CloseParenToken); SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = root.ReplaceNode(argumentListNode, updatedParameterList); return document.WithSyntaxRoot(newRoot); }
public static InvocationExpressionSyntax MethodInvocationExpressionSyntax(IdentifierNameSyntax methodName, ArgumentListSyntax arguments, IdentifierNameSyntax instance = null) { InvocationExpressionSyntax invocation = null; if (instance == null) { invocation = SyntaxFactory.InvocationExpression(methodName); } else { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, instance, methodName ) ); } return invocation.WithArgumentList(arguments); }
public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, string name, ArgumentListSyntax argumentList) { return(SimpleMemberInvocationExpression(expression, IdentifierName(name), argumentList)); }
private List<object> GetArguments(ArgumentListSyntax argumentList) { return argumentList.Arguments .Select(a => a.Expression) .Select(l => l == null ? null : context.SemanticModel.GetConstantValue(l).Value) .ToList(); }
public virtual void VisitArgumentList(ArgumentListSyntax node) { DefaultVisit(node); }
public override void VisitArgumentList(ArgumentListSyntax node) { var oper = m_Model.GetOperationEx(node.Parent); OutputArgumentList(node.Arguments, ", ", oper); }
public static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) { if (context.Node.SpanContainsDirectives()) { return; } var lambda = (SimpleLambdaExpressionSyntax)context.Node; InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); if (invocationExpression == null) { return; } ExpressionSyntax expression = invocationExpression.Expression; if (!IsSimpleInvocation(expression)) { return; } SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; if (!(semanticModel.GetSymbol(invocationExpression, cancellationToken) is IMethodSymbol methodSymbol)) { return; } if (!methodSymbol.IsStatic && expression.Kind() != SyntaxKind.IdentifierName && !ExpressionIsParameter(expression, lambda.Parameter)) { return; } bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; ImmutableArray <IParameterSymbol> parameterSymbols = (isReduced) ? methodSymbol.ReducedFrom.Parameters : methodSymbol.Parameters; if (parameterSymbols.Length != 1) { return; } ArgumentListSyntax argumentList = invocationExpression.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count != ((isReduced) ? 0 : 1)) { return; } ParameterSyntax parameter = lambda.Parameter; MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; if (!CheckParameter( parameter, (isReduced) ? memberAccessExpression.Expression : arguments[0].Expression, parameterSymbols[0])) { return; } methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) { return; } if (!CheckSpeculativeSymbol( lambda, (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, methodSymbol, semanticModel)) { return; } context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, lambda); FadeOut(context, parameter, null, lambda.Body as BlockSyntax, argumentList, lambda.ArrowToken, memberAccessExpression); }
private ArgumentSyntax GetArgumentForParameter(IParameterSymbol parameterSymbol, int index, ArgumentListSyntax node) { if (node.Arguments.TakeWhile(a => a.NameColon is null).Count() > index) { return(node.Arguments[index]); }
public ArgumentListTranslation(ArgumentListSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Arguments = syntax.Arguments.Get <ArgumentSyntax, ArgumentTranslation>(this); }
public InvocationContext(SemanticModel semModel, int position, SyntaxNode receiver, ArgumentListSyntax argList, bool isStatic) { SemanticModel = semModel; Position = position; Receiver = receiver; ArgumentTypes = argList.Arguments.Select(argument => semModel.GetTypeInfo(argument.Expression)); Separators = argList.Arguments.GetSeparators(); IsInStaticContext = isStatic; }
public void VisitInvocationAndCreation(ExpressionSyntax node, ArgumentListSyntax argList, ExecutionState state) { }
public ArgumentListPair(ArgumentListSyntax argumentList1, ArgumentListSyntax argumentList2) { ArgumentList1 = argumentList1; ArgumentList2 = argumentList2; }
private static ArgumentListPair RewriteArgumentLists( ArgumentListSyntax argumentList, SemanticModel semanticModel, CancellationToken cancellationToken) { ArgumentSyntax pattern = null; ArgumentSyntax regexOptions = null; ArgumentSyntax matchTimeout = null; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; SeparatedSyntaxList <ArgumentSyntax> newArguments = arguments; for (int i = arguments.Count - 1; i >= 0; i--) { IParameterSymbol parameterSymbol = semanticModel.DetermineParameter(arguments[i], cancellationToken: cancellationToken); Debug.Assert(parameterSymbol != null, ""); if (parameterSymbol != null) { if (pattern == null && parameterSymbol.Type.IsString() && parameterSymbol.Name == "pattern") { pattern = arguments[i]; newArguments = newArguments.RemoveAt(i); } if (regexOptions == null && parameterSymbol.Type.Equals(semanticModel.GetTypeByMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions))) { regexOptions = arguments[i]; newArguments = newArguments.RemoveAt(i); } if (matchTimeout == null && parameterSymbol.Type.Equals(semanticModel.GetTypeByMetadataName(MetadataNames.System_TimeSpan))) { matchTimeout = arguments[i]; newArguments = newArguments.RemoveAt(i); } } } argumentList = argumentList.WithArguments(newArguments); var arguments2 = new List <ArgumentSyntax>(); if (pattern != null) { arguments2.Add(pattern); } if (regexOptions != null) { arguments2.Add(regexOptions); } if (matchTimeout != null) { arguments2.Add(matchTimeout); } return(new ArgumentListPair(argumentList, ArgumentList(arguments2.ToArray()))); }
public MethodParameterLookup(ArgumentListSyntax argumentList, SemanticModel semanticModel) { this.argumentList = argumentList; MethodSymbol = semanticModel.GetSymbolInfo(argumentList.Parent).Symbol as IMethodSymbol; }
/// <summary> /// Get the arguments which are unnamed and not "params" /// </summary> private static IEnumerable <ArgParamBinding> GetUnnamedArgs( SemanticModel model, ArgumentListSyntax args ) { for (var idx = 0; idx < args.Arguments.Count; idx++) { var arg = args.Arguments[idx]; // Ignore args that already have names if (arg.NameColon != null) { continue; } var param = arg.DetermineParameter( model, // Don't map params arguments. It's okay that they are // unnamed. Some things like ImmutableArray.Create() could // take a large number of args and we don't want anything to // be named. Named params really suck so we may still // encourage it but APIs that take params and many other // args would suck anyway. allowParams: false ); // Not sure if this can happen but it'd be hard to name this // param so ignore it. if (param == null) { continue; } // IParameterSymbol.Name is documented to be possibly empty in // which case it is "unnamed", so ignore it. if (param.Name == "") { continue; } string psuedoName = GetPsuedoName(arg); if (psuedoName != null) { bool matchesParamName = string.Equals( psuedoName, param.Name, StringComparison.OrdinalIgnoreCase ); if (matchesParamName) { continue; } } yield return(new ArgParamBinding( position: idx, paramName: param.Name, syntax: arg )); } }
private static bool ArgumentsMatchParameters(ArgumentListSyntax argumentList, List<INamedTypeSymbol> argumentTypes, IMethodSymbol possibleOtherMethod, SemanticModel semanticModel) { var matchedParameters = new List<IParameterSymbol>(); for (int i = 0; i < argumentList.Arguments.Count; i++) { var argument = argumentList.Arguments[i]; var argumentType = argumentTypes[i]; IParameterSymbol parameter; if (!MethodParameterLookup.TryGetParameterSymbol(argument, argumentList, possibleOtherMethod, out parameter)) { return false; } if (argumentType == null) { if (!parameter.Type.IsReferenceType) { return false; } } else { var conversion = semanticModel.ClassifyConversion(argument.Expression, parameter.Type); if (!conversion.IsImplicit) { return false; } } matchedParameters.Add(parameter); } var nonMatchedParameters = possibleOtherMethod.Parameters.Except(matchedParameters); return nonMatchedParameters.All(p => p.HasExplicitDefaultValue); }
public static ConstructorInitializerSyntax ThisConstructorInitializer(ArgumentListSyntax argumentList = null) { return(ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, argumentList)); }
/// <summary> /// Creates a SemanticModel for a constructor initializer (": base-class(...)"). /// </summary> internal static InitializerSemanticModel Create(CSharpCompilation compilation, ArgumentListSyntax syntax, MethodSymbol methodSymbol, Binder rootBinder) { return(new InitializerSemanticModel(compilation, syntax, methodSymbol, rootBinder)); }
public static void AnalyzeAnonyousMethodExpression(SyntaxNodeAnalysisContext context) { if (context.Node.SpanContainsDirectives()) { return; } var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; InvocationExpressionSyntax invocationExpression = GetInvocationExpression(anonymousMethod.Body); if (invocationExpression == null) { return; } ExpressionSyntax expression = invocationExpression.Expression; if (!IsSimpleInvocation(expression)) { return; } SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; if (!(semanticModel.GetSymbol(invocationExpression, cancellationToken) is IMethodSymbol methodSymbol)) { return; } if (!methodSymbol.IsStatic && expression.Kind() != SyntaxKind.IdentifierName && !ExpressionIsParameter(expression, anonymousMethod.ParameterList)) { return; } ImmutableArray <IParameterSymbol> parameterSymbols = methodSymbol.Parameters; ArgumentListSyntax argumentList = invocationExpression.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count != parameterSymbols.Length) { return; } ParameterListSyntax parameterList = anonymousMethod.ParameterList; if (parameterList == null) { return; } SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) { return; } MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; if (isReduced) { if (!CheckParameter( parameters[0], ((MemberAccessExpressionSyntax)expression).Expression, methodSymbol.ReducedFrom.Parameters[0])) { return; } parameters = parameters.RemoveAt(0); } if (!CheckParameters(parameters, arguments, parameterSymbols)) { return; } methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; if (!CheckInvokeMethod(anonymousMethod, methodSymbol, semanticModel, context.CancellationToken)) { return; } if (!CheckSpeculativeSymbol( anonymousMethod, (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, methodSymbol, semanticModel)) { return; } context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, anonymousMethod); FadeOut(context, null, parameterList, anonymousMethod.Block, argumentList, anonymousMethod.DelegateKeyword, memberAccessExpression); }
private static async Task <Document> RemoveArgumentsAndAddNecessaryNamesAsync(Document document, ArgumentListSyntax argumentList, List <CSharpMethodParameterLookup.ArgumentParameterMapping> argumentMappings, List <ArgumentSyntax> argumentsToRemove, SemanticModel semanticModel, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newArgumentList = SyntaxFactory.ArgumentList(); var alreadyRemovedOne = false; foreach (var argumentMapping in argumentMappings .Where(argumentMapping => !argumentMapping.Parameter.IsParams)) { var argument = argumentMapping.Argument; if (argumentsToRemove.Contains(argument)) { alreadyRemovedOne = true; continue; } newArgumentList = AddArgument(newArgumentList, argumentMapping.Parameter.Name, argument, alreadyRemovedOne); } var paramsArguments = argumentMappings .Where(mapping => mapping.Parameter.IsParams) .ToList(); if (paramsArguments.Any()) { newArgumentList = AddParamsArguments(semanticModel, paramsArguments, newArgumentList); } var newRoot = root.ReplaceNode(argumentList, newArgumentList); return(document.WithSyntaxRoot(newRoot)); }
/// <summary> /// Tests it the provided <paramref name="argumentList"/> contains initialization of the <see cref="TrackedPropertyName"/> /// with an allowed value. Override this method when a constructor can initialize the property value with a allowed value. /// </summary> /// <returns>True when the <paramref name="argumentList"/> contains initialization of <see cref="TrackedPropertyName"/> /// with allowed value or when this constructor sets <see cref="TrackedPropertyName"/> with the /// allowed value by default, otherwise false.</returns> protected virtual bool CtorInitializesTrackedPropertyWithAllowedValue(ArgumentListSyntax argumentList, SemanticModel semanticModel) => false;
private static ArgumentListSyntax AddParamsArguments(SemanticModel semanticModel, ICollection <CSharpMethodParameterLookup.ArgumentParameterMapping> paramsArguments, ArgumentListSyntax argumentList) { var firstParamsMapping = paramsArguments.First(); var firstParamsArgument = firstParamsMapping.Argument; var paramsParameter = firstParamsMapping.Parameter; if (firstParamsArgument.NameColon != null) { return(argumentList.AddArguments(firstParamsArgument)); } if (paramsArguments.Count == 1 && paramsParameter.Type.Equals( semanticModel.GetTypeInfo(firstParamsArgument.Expression).Type)) { return(argumentList.AddArguments( SyntaxFactory.Argument( SyntaxFactory.NameColon( SyntaxFactory.IdentifierName(paramsParameter.Name)), firstParamsArgument.RefOrOutKeyword, firstParamsArgument.Expression))); } return(argumentList.AddArguments( SyntaxFactory.Argument( SyntaxFactory.NameColon( SyntaxFactory.IdentifierName(paramsParameter.Name)), SyntaxFactory.Token(SyntaxKind.None), SyntaxFactory.ImplicitArrayCreationExpression( SyntaxFactory.InitializerExpression( SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList( paramsArguments.Select(arg => arg.Argument.Expression)) ))))); }
private static SyntaxNode createInvocation(string call, ArgumentListSyntax args) { //td: use cases //switch (call) //{ // case "c": // call = "RR.c"; // break; //} return CSharp.InvocationExpression(CSharp.ParseExpression("RR." + call), args); }
private static bool TryGetAlgorithmName(ArgumentListSyntax argumentList, out string algorithmName) { if (argumentList == null || argumentList.Arguments.Count == 0 || !argumentList.Arguments.First().Expression.IsKind(SyntaxKind.StringLiteralExpression)) { algorithmName = null; return false; } var algorithmNameCandidate = ((LiteralExpressionSyntax)argumentList.Arguments.First().Expression).Token.ValueText; algorithmName = InsecureHashAlgorithmTypeNames.Values .FirstOrDefault(alg => algorithmNameCandidate.StartsWith(alg, System.StringComparison.InvariantCulture)); return algorithmName != null; }
private void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context) { var invocation = (InvocationExpressionSyntax)context.Node; ExpressionSyntax expression = invocation.Expression; if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true) { var memberAccess = (MemberAccessExpressionSyntax)expression; ArgumentListSyntax argumentList = invocation.ArgumentList; if (argumentList?.IsMissing == false) { int argumentCount = argumentList.Arguments.Count; string methodName = memberAccess.Name?.Identifier.ValueText; if (argumentCount == 0) { switch (methodName) { case "Any": { SimplifyLinqMethodChainRefactoring.Analyze(context, invocation, memberAccess, methodName); ReplaceAnyMethodWithCountOrLengthPropertyRefactoring.Analyze(context, invocation, memberAccess); break; } case "Cast": { ReplaceWhereAndCastWithOfTypeRefactoring.Analyze(context, invocation); break; } case "Count": { SimplifyLinqMethodChainRefactoring.Analyze(context, invocation, memberAccess, methodName); ReplaceCountMethodRefactoring.Analyze(context, invocation, memberAccess); break; } case "First": case "FirstOrDefault": case "Last": case "LastOrDefault": case "LongCount": case "Single": case "SingleOrDefault": { SimplifyLinqMethodChainRefactoring.Analyze(context, invocation, memberAccess, methodName); break; } } } else if (argumentCount == 1) { switch (methodName) { case "Select": { ReplaceSelectWithCastRefactoring.Analyze(context, invocation, memberAccess); break; } case "Where": { CombineEnumerableWhereMethodChainRefactoring.Analyze(context, invocation, memberAccess); break; } } } } } if (ReplaceHasFlagWithBitwiseOperationRefactoring.CanRefactor(invocation, context.SemanticModel, context.CancellationToken)) { context.ReportDiagnostic(DiagnosticDescriptors.UseBitwiseOperationInsteadOfHasFlagMethod, invocation.GetLocation()); } RemoveRedundantToStringCallRefactoring.Analyze(context, invocation); RemoveRedundantStringToCharArrayCallRefactoring.Analyze(context, invocation); }
public static ObjectCreationExpressionSyntax ObjectCreationExpression(TypeSyntax type, ArgumentListSyntax argumentList) { return(SyntaxFactory.ObjectCreationExpression(type, argumentList, default(InitializerExpressionSyntax))); }
public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name, ArgumentListSyntax argumentList) { return(SyntaxFactory.InvocationExpression(SimpleMemberAccessExpression(expression, name), argumentList)); }
/// <summary> /// Creates a SemanticModel for a constructor initializer (": base-class(...)"). /// </summary> internal static InitializerSemanticModel Create(CSharpCompilation compilation, ArgumentListSyntax syntax, MethodSymbol methodSymbol, Binder rootBinder) { return new InitializerSemanticModel(compilation, syntax, methodSymbol, rootBinder); }
private static void AnalyzeArgumentList(SyntaxNodeAnalysisContext context, ArgumentListSyntax argumentListSyntax) { var openParenToken = argumentListSyntax.OpenParenToken; if (openParenToken.IsMissing || argumentListSyntax.IsMissing || !argumentListSyntax.Arguments.Any()) { return; } var firstArgument = argumentListSyntax.Arguments[0]; if (firstArgument.GetLeadingTrivia().Any(SyntaxKind.PragmaWarningDirectiveTrivia)) { return; } var firstArgumentLineSpan = firstArgument.GetLineSpan(); if (!firstArgumentLineSpan.IsValid) { return; } var openParenLineSpan = openParenToken.GetLineSpan(); if (!openParenLineSpan.IsValid) { return; } if (openParenLineSpan.EndLinePosition.Line != firstArgumentLineSpan.StartLinePosition.Line && openParenLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1)) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation())); } }
private static bool IsBaseEncryptionCreateCalled(string methodName, ArgumentListSyntax argumentList) { if (methodName != BaseEncryptionAlgorithmCreate) { return false; } if (argumentList.Arguments.Count == 0 || !argumentList.Arguments.First().Expression.IsKind(SyntaxKind.StringLiteralExpression)) { return false; } var algorithmNameCandidate = ((LiteralExpressionSyntax)argumentList.Arguments.First().Expression).Token.ValueText; var algorithmName = AlgorithmNames .FirstOrDefault(alg => algorithmNameCandidate.StartsWith(alg, System.StringComparison.InvariantCulture)); return algorithmName != null; }
private static bool IsInvocationWithExplicitArray(ArgumentListSyntax argumentList, IMethodSymbol invokedMethodSymbol, SemanticModel semanticModel) { var allParameterMatches = new List<IParameterSymbol>(); foreach (var argument in argumentList.Arguments) { IParameterSymbol parameter; if (!MethodParameterLookup.TryGetParameterSymbol(argument, argumentList, invokedMethodSymbol, out parameter)) { return false; } allParameterMatches.Add(parameter); if (!parameter.IsParams) { continue; } var argType = semanticModel.GetTypeInfo(argument.Expression).Type; if (!(argType is IArrayTypeSymbol)) { return false; } } return allParameterMatches.Count(p => p.IsParams) == 1; }
internal static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context) { var invocation = (InvocationExpressionSyntax)context.Node; ExpressionSyntax expression = invocation.Expression; if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true) { var memberAccess = (MemberAccessExpressionSyntax)expression; ArgumentListSyntax argumentList = invocation.ArgumentList; if (argumentList?.IsMissing == false) { SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count == 0) { SimpleNameSyntax name = memberAccess.Name; if (name != null) { string methodName = name.Identifier.ValueText; if (methodName == "Cast") { SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; ISymbol symbol = semanticModel.GetSymbol(invocation, cancellationToken); if (symbol?.IsMethod() == true) { ExtensionMethodInfo extensionMethodInfo; if (ExtensionMethodInfo.TryCreate((IMethodSymbol)symbol, semanticModel, out extensionMethodInfo, ExtensionMethodKind.Reduced) && extensionMethodInfo.MethodInfo.IsLinqCast()) { ImmutableArray <ITypeSymbol> typeArguments = extensionMethodInfo.ReducedSymbol.TypeArguments; if (typeArguments.Length == 1) { ExpressionSyntax memberAccessExpression = memberAccess.Expression; if (memberAccessExpression != null) { var memberAccessExpressionType = semanticModel.GetTypeSymbol(memberAccessExpression, cancellationToken) as INamedTypeSymbol; if (memberAccessExpressionType?.IsConstructedFromIEnumerableOfT() == true && typeArguments[0].Equals(memberAccessExpressionType.TypeArguments[0]) && !invocation.ContainsDirectives(TextSpan.FromBounds(memberAccessExpression.Span.End, invocation.Span.End))) { context.ReportDiagnostic( DiagnosticDescriptors.RemoveRedundantCast, Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(name.SpanStart, argumentList.Span.End))); } } } } } } } } } } }
public static InvocationExpressionSyntax InvocationExpression(string name, ArgumentListSyntax argumentList) { return(SyntaxFactory.InvocationExpression(IdentifierName(name), argumentList)); }
private void ExtractInvocationInfo(IMethodSymbol sym, ArgumentListSyntax argList, out List <ExpressionSyntax> args, out List <ArgDefaultValueInfo> defArgs, out List <IConversionExpression> argConversions) { args = new List <ExpressionSyntax>(); defArgs = new List <ArgDefaultValueInfo>(); argConversions = new List <IConversionExpression>(); var moper = m_Model.GetOperation(argList) as IInvocationExpression; var argExps = argList.Arguments; Dictionary <string, ExpressionSyntax> namedArgs = new Dictionary <string, ExpressionSyntax>(); int ct = 0; for (int i = 0; i < argExps.Count; ++i) { var arg = argExps[i]; var argOper = m_Model.GetOperation(arg.Expression); if (null != arg.NameColon) { namedArgs.Add(arg.NameColon.Name.Identifier.Text, arg.Expression); continue; } IConversionExpression lastConv = null; if (ct < sym.Parameters.Length) { var param = sym.Parameters[ct]; if (null != moper) { var iarg = moper.GetArgumentMatchingParameter(param); if (null != iarg) { lastConv = iarg.Value as IConversionExpression; } } if (param.RefKind == RefKind.Ref) { args.Add(arg.Expression); } else if (param.RefKind == RefKind.Out) { //方法的out参数,为与脚本引擎的机制一致,在调用时传入__cs2dsl_out,这里用null标记一下,在实际输出参数时再变为__cs2dsl_out args.Add(null); } else if (param.IsParams) { args.Add(arg.Expression); } else { args.Add(arg.Expression); } ++ct; } else { args.Add(arg.Expression); } argConversions.Add(lastConv); } for (int i = ct; i < sym.Parameters.Length; ++i) { var param = sym.Parameters[i]; if (param.HasExplicitDefaultValue) { IConversionExpression lastConv = null; if (null != moper) { var iarg = moper.GetArgumentMatchingParameter(param); if (null != iarg) { lastConv = iarg.Value as IConversionExpression; } } argConversions.Add(lastConv); ExpressionSyntax expval; if (namedArgs.TryGetValue(param.Name, out expval)) { var argOper = m_Model.GetOperation(expval); defArgs.Add(new ArgDefaultValueInfo { Expression = expval }); } else { var decl = param.DeclaringSyntaxReferences; bool handled = false; if (decl.Length >= 1) { var node = param.DeclaringSyntaxReferences[0].GetSyntax() as ParameterSyntax; if (null != node) { var exp = node.Default.Value; var tree = node.SyntaxTree; var newModel = SymbolTable.Instance.Compilation.GetSemanticModel(tree, true); if (null != newModel) { var oper = newModel.GetOperation(exp); defArgs.Add(new ArgDefaultValueInfo { Value = param.ExplicitDefaultValue, OperOrSym = oper }); handled = true; } } } if (!handled) { defArgs.Add(new ArgDefaultValueInfo { Value = param.ExplicitDefaultValue, OperOrSym = null }); } } } } }
private static bool MatchArguments(ParameterListSyntax parameters, ArgumentListSyntax arguments) { if (arguments.Arguments.Count != parameters.Parameters.Count) return false; var paramNameList = parameters.Parameters.Select(p => p.Identifier.Text); var argNameList = arguments.Arguments .Where(a => a.Expression is IdentifierNameSyntax) .Select(a => (a.Expression as IdentifierNameSyntax).Identifier.Text); return paramNameList.SequenceEqual(argNameList); }
private static ValidationFailure TryParseAndValidate(string formatStringText, ArgumentListSyntax argumentList, int formatArgumentIndex, SemanticModel semanticModel) { if (formatStringText == null) { return(ValidationFailure.NullFormatString); } return(ExtractFormatItems(formatStringText, out var formatStringItems) ?? TryValidateFormatString(formatStringItems, argumentList, formatArgumentIndex, semanticModel)); }
protected override ArgumentSyntax?GetLambda(ArgumentListSyntax argumentList) => argumentList.GetArgument("expression", 0);
private static async Task <Document> ApplyObservableBeforeCriteriaFixAsync(CodeFixContext context, ArgumentListSyntax argumentList, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken) .ConfigureAwait(false); editor.ReplaceNode( argumentList.Arguments[0].Expression, argumentList.Arguments[1].Expression .WithLeadingTrivia(argumentList.Arguments[0].Expression.GetLeadingTrivia())); editor.ReplaceNode( argumentList.Arguments[1].Expression, argumentList.Arguments[0].Expression .WithLeadingTrivia(argumentList.Arguments[1].Expression.GetLeadingTrivia())); return(editor.GetChangedDocument()); }
private IEnumerable<ITypeSymbol> InferTypeInArgumentList(ArgumentListSyntax argumentList, SyntaxToken previousToken) { // Has to follow the ( or a , if (previousToken != argumentList.OpenParenToken && previousToken.CSharpKind() != SyntaxKind.CommaToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var invocation = argumentList.Parent as InvocationExpressionSyntax; if (invocation != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInInvocationExpression(invocation, index); } var objectCreation = argumentList.Parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInObjectCreationExpression(objectCreation, index); } var constructorInitializer = argumentList.Parent as ConstructorInitializerSyntax; if (constructorInitializer != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInConstructorInitializer(constructorInitializer, index); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); }
protected override ArgumentSyntax?GetUidPart2(ArgumentListSyntax argumentList) => argumentList.GetArgument("uidPart2", 2);
public override void VisitArgumentList(ArgumentListSyntax node) { if (_root == node) { // We are supposed to get here only for constructor initializers Debug.Assert(node.Parent is ConstructorInitializerSyntax); var argBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, argBinder); foreach (var arg in node.Arguments) { Visit(arg.Expression, argBinder); } } else { base.VisitArgumentList(node); } }
private static void HandleArgumentListSyntax(SyntaxNodeAnalysisContext context, ArgumentListSyntax argumentList) { if (argumentList == null) { return; } SeparatedSyntaxList <ArgumentSyntax> parameters = argumentList.Arguments; if (parameters.Count > 1) { Analyze(context, argumentList.OpenParenToken, parameters[0], parameters[1]); } }
private async Task<Document> CorrectKindAsync(Document document, ArgumentListSyntax declaration, CancellationToken c) { SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document); ArgumentSyntax argument = CodeFixNodeCreator.CreateSyntaxKindIfStatement(generator); SeparatedSyntaxList<ArgumentSyntax> arguments = declaration.Arguments; if (arguments.Count < 2) { arguments = arguments.Add(argument); } else { arguments = arguments.Replace(arguments[1], argument); } var argList = SyntaxFactory.ArgumentList(arguments); SyntaxNode newRegister = generator.IdentifierName("RegisterSyntaxNodeAction"); SyntaxNode newMemberExpr = generator.MemberAccessExpression(((declaration.Parent as InvocationExpressionSyntax).Expression as MemberAccessExpressionSyntax).Expression, newRegister); SyntaxNode newInvocationExpr = generator.InvocationExpression(newMemberExpr, argList.Arguments); SyntaxNode newExpression = generator.ExpressionStatement(newInvocationExpr); return await ReplaceNode(declaration.Ancestors().OfType<ExpressionStatementSyntax>().First(), newExpression.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" "), SyntaxFactory.ParseLeadingTrivia("// Calls the method (first argument) to perform analysis whenever this is a change to a SyntaxNode of kind IfStatement").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"), SyntaxFactory.Whitespace(" "))), document); }
public static ExpressionSyntax Get(this ArgumentListSyntax argumentList, int index) => argumentList != null && argumentList.Arguments.Count > index ? argumentList.Arguments[index].Expression.RemoveParentheses() : null;
public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, ArgumentListSyntax argumentList) { return semanticModel.GenerateParameterNames(argumentList.Arguments); }
internal static ExpressionSyntax ToInvocationExpression(string identifier, ArgumentListSyntax argumentList = null) { return(ToInvocationExpression(SyntaxFactory.IdentifierName(identifier), argumentList)); }