private static bool CanSimplify( SemanticDocument document, ParenthesizedLambdaExpressionSyntax node, CancellationToken cancellationToken) { if (node == null) { return(false); } var paramNames = node.ParameterList.Parameters.Select(p => p.Identifier).ToList(); var invocation = TryGetInvocationExpression(node.Body); return(CanSimplify(document, node, paramNames, invocation, cancellationToken)); }
public static async Task <Document> RefactorAsync( Document document, ParenthesizedLambdaExpressionSyntax lambda, CancellationToken cancellationToken) { LambdaExpressionSyntax newLambda = SyntaxRewriter.VisitNode(lambda); if (lambda.ParameterList.Parameters.Count == 1) { newLambda = ConvertParenthesizedLambdaToSimpleLambda((ParenthesizedLambdaExpressionSyntax)newLambda); } newLambda = newLambda.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(lambda, newLambda, cancellationToken).ConfigureAwait(false)); }
private ParameterListSyntax GenerateParenthesizedLambdaParameterList( SemanticModel semanticModel, ParenthesizedLambdaExpressionSyntax lambdaExpression, CancellationToken cancellationToken) { return(lambdaExpression.ParameterList.ReplaceNodes( lambdaExpression.ParameterList.Parameters, (parameterNode, _) => { if (parameterNode.Type != null) { return parameterNode; } var parameter = semanticModel.GetDeclaredSymbol(parameterNode, cancellationToken); return parameterNode.WithType(parameter?.Type.GenerateTypeSyntax() ?? s_objectType); })); }
public override bool ContainingScopeHasAsyncKeyword() { var node = GetContainingScope(); return(node switch { AccessorDeclarationSyntax _ => false, MethodDeclarationSyntax method => method.Modifiers.Any(SyntaxKind.AsyncKeyword), ParenthesizedLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, SimpleLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, AnonymousMethodExpressionSyntax anonymous => anonymous.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, _ => false, });
private static void FadeOut(SyntaxNodeAnalysisContext context, ParenthesizedLambdaExpressionSyntax lambda) { DiagnosticDescriptor descriptor = DiagnosticDescriptors.SimplifyLambdaExpressionParameterListFadeOut; SeparatedSyntaxList <ParameterSyntax> parameters = lambda.ParameterList.Parameters; if (parameters.Count == 1) { FadeOutToken(context, lambda.ParameterList.OpenParenToken, descriptor); FadeOutToken(context, lambda.ParameterList.CloseParenToken, descriptor); } for (int i = 0; i < parameters.Count; i++) { FadeOutNode(context, parameters[i].Type, descriptor); } }
public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var ti = this.semanticModel.GetTypeInfo(node); var oldValue = this.IsExpressionOfT; if (ti.Type != null && ti.Type.IsExpressionOfT() || ti.ConvertedType != null && ti.ConvertedType.IsExpressionOfT()) { this.IsExpressionOfT = true; } var newNode = base.VisitParenthesizedLambdaExpression(node); this.IsExpressionOfT = oldValue; return(newNode); }
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (debug) { Console.WriteLine(node.ToFullString()); } Todo("ParenthesizedLambdaExpression"); var nl = OurLine.NewLine(LineKind.Decl, "ParenthesizedLambdaExpression"); nl.Source = node.ToFullString(); nl.ParentKind = node.Parent.RawKind; nl.RawKind = node.RawKind; LogCommand(nl); Todo("ParenthesizedLambdaExpression"); StartBlock("ParenthesizedLambdaExpression"); base.VisitParenthesizedLambdaExpression(node); EndBlock("ParenthesizedLambdaExpression"); }
public static ParametersInfo Create(ParenthesizedLambdaExpressionSyntax parenthesizedLambda, bool allowMissing = false) { ParameterListSyntax parameterList = parenthesizedLambda.ParameterList; if (!CheckParameterList(parameterList, allowMissing)) { return(Default); } CSharpSyntaxNode body = parenthesizedLambda.Body; if (!Check(body, allowMissing)) { return(Default); } return(new ParametersInfo(default(TypeParameterListSyntax), parameterList, body)); }
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { FunctionDepth++; if (node.Body.IsKind(SyntaxKind.IdentifierName)) { var identifier = (IdentifierNameSyntax)node.Body; foreach (var assignmentNode in CacheAnalysisUtil.GetNullAssignmentNodes(identifier, _context)) { PossibleNullValues.Add(assignmentNode); } } base.VisitParenthesizedLambdaExpression(node); FunctionDepth--; }
/// <summary> /// Helper method to get the code Block of a delegate or lambda expression. /// </summary> /// <param name="delegateOrLambdaExpression">The delegate or lambda expression.</param> /// <returns>The code block.</returns> private BlockSyntax GetBlockOfDelegateOrLambdaExpression(SyntaxNode delegateOrLambdaExpression) { AnonymousMethodExpressionSyntax anonymousMethod = delegateOrLambdaExpression as AnonymousMethodExpressionSyntax; if (anonymousMethod != null) { return(anonymousMethod.Block); } ParenthesizedLambdaExpressionSyntax lambdaExpression = delegateOrLambdaExpression as ParenthesizedLambdaExpressionSyntax; if (lambdaExpression != null) { return(lambdaExpression.Body as BlockSyntax); } throw new ArgumentException("Must be of type AnonymousMethodExpressionSyntax or ParenthesizedLambdaExpressionSyntax", nameof(delegateOrLambdaExpression)); }
private static async Task <Document> SimplifyLambdaExpressionParameterListAsync( Document document, ParenthesizedLambdaExpressionSyntax lambda, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); LambdaExpressionSyntax newLambda = SyntaxRewriter.VisitNode(lambda); if (lambda.ParameterList.Parameters.Count == 1) { newLambda = ConvertParenthesizedLambdaToSimpleLambda((ParenthesizedLambdaExpressionSyntax)newLambda); } newLambda = newLambda.WithFormatterAnnotation(); root = root.ReplaceNode(lambda, newLambda); return(document.WithSyntaxRoot(root)); }
public LambdaSharpnode(ParenthesizedLambdaExpressionSyntax syntax) : base(syntax) { // We only allow for a single kind of lambda expressions: those that fit ForAll and Exists. if (syntax.ParameterList.Parameters.Count != 1) { this.errorneousResult = new Error( Diagnostics.SSIL125_LambdasMustHaveSingleParameter, syntax.ParameterList); return; } this.parameter = new ParameterSharpnode(syntax.ParameterList.Parameters[0]); if (syntax.Body is ExpressionSyntax) { this.body = RoslynToSharpnode.MapExpression((ExpressionSyntax)syntax.Body); } else { this.errorneousResult = new Error( Diagnostics.SSIL126_LambdasMustBeExpressions, syntax.Body); } }
private static async Task <Document> SimplifyLambdaExpressionParameterListAsync( Document document, ParenthesizedLambdaExpressionSyntax lambda, CancellationToken cancellationToken) { SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken); LambdaExpressionSyntax newLambda = SimplifyLambdaExpressionParameterListSyntaxRewriter.VisitNode(lambda); if (lambda.ParameterList.Parameters.Count == 1) { newLambda = ConvertParenthesizedLambdaToSimpleLambda((ParenthesizedLambdaExpressionSyntax)newLambda); } newLambda = newLambda.WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode newRoot = oldRoot.ReplaceNode(lambda, newLambda); return(document.WithSyntaxRoot(newRoot)); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); ParenthesizedLambdaExpressionSyntax lambda = root .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf <ParenthesizedLambdaExpressionSyntax>(); if (lambda == null) { return; } CodeAction codeAction = CodeAction.Create( "Simplify lambda expression parameter list", cancellationToken => SimplifyLambdaExpressionParameterListRefactoring.RefactorAsync(context.Document, lambda, cancellationToken), DiagnosticIdentifiers.SimplifyLambdaExpressionParameterList + EquivalenceKeySuffix); context.RegisterCodeFix(codeAction, context.Diagnostics); }
protected override ArgumentSyntax CreateArgumentSyntax() { ParenthesizedLambdaExpressionSyntax expression = null; if (_blockSyntax != null) { expression = ParenthesizedLambdaExpression(_blockSyntax); } else { expression = ParenthesizedLambdaExpression(_expressionSyntax); } if (_parameters.Any()) { expression = expression.WithParameterList(ParameterGenerator.ConvertParameterSyntaxToList(_parameters.Select(p => Parameter(Identifier(p.Name))).ToArray())); } return(Argument(expression)); }
private static Task <Document> RefactorAsync( Document document, ExpressionSyntax expression, SyntaxTokenList modifiers, ParameterListSyntax parameterList, CSharpSyntaxNode bodyOrExpressionBody, CancellationToken cancellationToken) { ParenthesizedLambdaExpressionSyntax lambda = ParenthesizedLambdaExpression( (modifiers.Contains(SyntaxKind.AsyncKeyword)) ? AsyncKeyword() : default(SyntaxToken), parameterList, EqualsGreaterThanToken(), GetLambdaBody(bodyOrExpressionBody)); lambda = lambda .WithTriviaFrom(expression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(expression, lambda, cancellationToken)); }
private Doc PrintParenthesizedLambdaExpressionSyntax( ParenthesizedLambdaExpressionSyntax node) { var parts = new Parts( this.PrintModifiers(node.Modifiers), this.PrintParameterListSyntax(node.ParameterList), SpaceIfNoPreviousComment, this.PrintSyntaxToken(node.ArrowToken, " ") ); if (node.ExpressionBody != null) { parts.Push(this.Print(node.ExpressionBody)); } else if (node.Block != null) { parts.Push(this.PrintBlockSyntax(node.Block)); } return(Concat(parts)); }
public static Doc Print(ParenthesizedLambdaExpressionSyntax node) { var docs = new List <Doc> { Modifiers.Print(node.Modifiers), ParameterList.Print(node.ParameterList), " ", Token.PrintWithSuffix(node.ArrowToken, " ") }; if (node.ExpressionBody != null) { docs.Add(Node.Print(node.ExpressionBody)); } else if (node.Block != null) { docs.Add(Block.Print(node.Block)); } return(Doc.Concat(docs)); }
internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) { Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery()); SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (lambdaExpressionOrQueryNode.Kind()) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = simple.ArrowToken; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = parenthesized.ArrowToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode; body = anon.Block; firstIncluded = body.GetFirstToken(includeZeroWidth: true); break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken(); return(IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken())); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return(IsBetweenTokens(position, firstIncluded, firstExcluded)); }
public static Task <Document> RefactorAsync( Document document, ParenthesizedLambdaExpressionSyntax parenthesizedLambda, MemberDeclarationSyntax memberDeclaration, TypeDeclarationSyntax typeDeclaration, string methodName, SemanticModel semanticModel, CancellationToken cancellationToken) { methodName = NameGenerator.Default.EnsureUniqueLocalName(methodName, semanticModel, parenthesizedLambda.SpanStart, cancellationToken: cancellationToken); MemberDeclarationSyntax newMemberDeclaration = memberDeclaration.ReplaceNode(parenthesizedLambda, IdentifierName(methodName).WithTriviaFrom(parenthesizedLambda)); IMethodSymbol lambdaSymbol = semanticModel.GetMethodSymbol(parenthesizedLambda, cancellationToken); ParameterListSyntax parameterList = parenthesizedLambda.ParameterList; SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; ImmutableArray <IParameterSymbol> parameterSymbols = lambdaSymbol.Parameters; parameters = parameters .ReplaceAt(0, AddTypeIfMissing(parameters[0], parameterSymbols[0])) .ReplaceAt(1, AddTypeIfMissing(parameters[1], parameterSymbols[1])); cancellationToken.ThrowIfCancellationRequested(); MethodDeclarationSyntax newMethodDeclaration = MethodDeclaration( (SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) ? Modifiers.Private_Static() : Modifiers.Private(), VoidType(), Identifier(methodName).WithRenameAnnotation(), parameterList.WithParameters(parameters), CreateMethodBody(parenthesizedLambda.Body)) .WithFormatterAnnotation(); SyntaxList <MemberDeclarationSyntax> newMembers = typeDeclaration.Members.Replace(memberDeclaration, newMemberDeclaration); newMembers = MemberDeclarationInserter.Default.Insert(newMembers, newMethodDeclaration); return(document.ReplaceNodeAsync(typeDeclaration, typeDeclaration.WithMembers(newMembers), cancellationToken));
public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (node.Parent == null) { return(base.VisitParenthesizedLambdaExpression(node)); } var argument = node.Parent as ArgumentSyntax; if (argument == null) { return(base.VisitParenthesizedLambdaExpression(node)); } var argumentList = argument.Parent as ArgumentListSyntax; if (argumentList == null) { return(base.VisitParenthesizedLambdaExpression(node)); } var invocation = argumentList.Parent as InvocationExpressionSyntax; if (invocation == null) { return(base.VisitParenthesizedLambdaExpression(node)); } var identifier = invocation.Expression .DescendantNodes(descendIntoChildren: syntaxNode => true) .LastOrDefault(x => x.IsKind(SyntaxKind.IdentifierName)) as IdentifierNameSyntax; if (identifier == null) { return(base.VisitParenthesizedLambdaExpression(node)); } return(HandleMethod(node, invocation, identifier.Identifier.Text)); }
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { SymbolInfo symInfo = m_Model.GetSymbolInfo(node); var sym = symInfo.Symbol as IMethodSymbol; if (null != sym) { var mi = new MethodInfo(); mi.Init(sym, node); m_MethodInfoStack.Push(mi); CodeBuilder.Append("(function("); int ct = sym.Parameters.Length; if (ct > 0) { for (int i = 0; i < ct; ++i) { var param = sym.Parameters[i]; CodeBuilder.Append(param.Name); if (i < ct - 1) { CodeBuilder.Append(", "); } } } CodeBuilder.AppendLine(")"); ++m_Indent; node.Body.Accept(this); --m_Indent; CodeBuilder.AppendFormat("{0}end)", GetIndentString()); m_MethodInfoStack.Pop(); } else { ReportIllegalSymbol(node, symInfo); } }
internal static bool IsInAnonymousFunctionOrQuery(int position, CSharpSyntaxNode anonymousFunction) { SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (anonymousFunction.Kind) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)anonymousFunction; firstIncluded = simple.Parameter.Identifier; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)anonymousFunction; firstIncluded = parenthesized.ParameterList.OpenParenToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)anonymousFunction; firstIncluded = anon.DelegateKeyword; body = anon.Block; break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = anonymousFunction.GetFirstToken().GetNextToken(); return(IsBetweenTokens(position, firstIncluded, anonymousFunction.GetLastToken().GetNextToken())); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return(IsBetweenTokens(position, firstIncluded, firstExcluded)); }
public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var info = _semanticModel.GetTypeInfo(node); _output.Write(node, "function ({0}) ", this.MakeParametersList(node.ParameterList)); _output.TrivialWriteLine('{'); _output.IncreaseIndent(); if (node.Body.Kind() != SyntaxKind.Block) { if (info.DelegateReturnValue()) { _output.TrivialWrite("return "); } } this.Visit(node.Body); if (node.Body.Kind() != SyntaxKind.Block) { _output.TrivialWriteLine(';'); } _output.DecreaseIndent(); _output.TrivialWrite('}'); return(node); }
public override IEnumerable <IModel> VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var model = Create <LambdaExpression>(node); model.Body = TransformToSingle <ISyntacticModel>(node.Body); TransformInto <ParameterDeclaration>(node.ParameterList, model.Parameters); // if the lambda returns a value an the body is an expression, // we should explicitly include the return statement var expr = model.Body as ExpressionModel; if (expr != null) { var info = GetSymbol(node) as MethodSymbol; if (info != null && info.ReturnType.SpecialType != Roslyn.Compilers.SpecialType.System_Void) { model.Body = new ReturnStatement { Expression = expr }; } } yield return(model); }
public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (queryMethodCtx.HasAny) { if (queryMethodCtx.Current.IsIncludeMethod) //暂Include类特殊处理 { queryMethodCtx.Current.InLambdaExpression = true; var res = base.VisitParenthesizedLambdaExpression(node); queryMethodCtx.Current.InLambdaExpression = false; return(res); } else { for (int i = 0; i < node.ParameterList.Parameters.Count; i++) { queryMethodCtx.Current.LambdaParameters[i] = node.ParameterList.Parameters[i].Identifier.ValueText; } //TODO:考虑预先处理 (t)=> 行差 return(VisitQueryMethodLambdaExpresssion(node)); } } return(base.VisitParenthesizedLambdaExpression(node)); }
/// <summary> /// Finds the async delegate or lambda expression that matches the await by walking up the syntax tree until we encounter an async delegate or lambda expression. /// </summary> /// <param name="awaitExpressionSyntax">The await expression syntax.</param> /// <returns>Node representing the delegate or lambda expression if found. Null if not found.</returns> private SyntaxNode FindAsyncDelegateOrLambdaExpressiomMatchingAwait(AwaitExpressionSyntax awaitExpressionSyntax) { SyntaxNode currentNode = awaitExpressionSyntax; while (currentNode != null && !(currentNode is MethodDeclarationSyntax)) { AnonymousMethodExpressionSyntax anonymousMethod = currentNode as AnonymousMethodExpressionSyntax; if (anonymousMethod != null && anonymousMethod.AsyncKeyword != null) { return(currentNode); } ParenthesizedLambdaExpressionSyntax lambdaExpression = currentNode as ParenthesizedLambdaExpressionSyntax; if (lambdaExpression != null && lambdaExpression.AsyncKeyword != null) { return(currentNode); } // Advance to the next parent currentNode = currentNode.Parent; } return(null); }
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { VisitLambdaExpression(node); }
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { VisitWithNesting(node, base.VisitParenthesizedLambdaExpression); }
private SyntaxNode FixParenthesizedLambda(ParenthesizedLambdaExpressionSyntax lambda) { return(lambda.WithoutLeadingTrivia() .WithAsyncKeyword(s_asyncToken.WithPrependedLeadingTrivia(lambda.GetLeadingTrivia()))); }
public void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); ExpressionStart(node); if (node.Modifiers != Modifiers.None) { _writer.WriteModifiers(node.Modifiers); _writer.WriteSpace(); } node.ParameterList.Accept(this); if (_writer.Configuration.Spaces.Other.AroundLambdaArrow) _writer.WriteSpace(); _writer.WriteSyntax(Syntax.Arrow); if ( _writer.Configuration.Spaces.Other.AroundLambdaArrow && !(node.Body is BlockSyntax) ) _writer.WriteSpace(); _writer.PushBraceFormatting(_writer.Configuration.BracesLayout.Other, false); node.Body.Accept(this); _writer.PopBraceFormatting(); ExpressionEnd(node); }