|
| 1 | +part of 'avoid_redundant_async_rule.dart'; |
| 2 | + |
| 3 | +class _Visitor extends RecursiveAstVisitor<void> { |
| 4 | + final _declarations = <Declaration>[]; |
| 5 | + |
| 6 | + Iterable<Declaration> get declarations => _declarations; |
| 7 | + |
| 8 | + @override |
| 9 | + void visitMethodDeclaration(MethodDeclaration node) { |
| 10 | + super.visitMethodDeclaration(node); |
| 11 | + |
| 12 | + if (_hasRedundantAsync(node.body)) { |
| 13 | + _declarations.add(node); |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + @override |
| 18 | + void visitFunctionDeclaration(FunctionDeclaration node) { |
| 19 | + super.visitFunctionDeclaration(node); |
| 20 | + |
| 21 | + if (_hasRedundantAsync(node.functionExpression.body)) { |
| 22 | + _declarations.add(node); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + bool _hasRedundantAsync(FunctionBody body) { |
| 27 | + final hasAsyncKeyword = body.keyword?.type == Keyword.ASYNC; |
| 28 | + if (!hasAsyncKeyword) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + if (body is ExpressionFunctionBody) { |
| 33 | + final type = body.expression.staticType; |
| 34 | + |
| 35 | + if (type != null && !type.isDartAsyncFuture) { |
| 36 | + return false; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + final asyncVisitor = _AsyncVisitor(); |
| 41 | + body.parent?.visitChildren(asyncVisitor); |
| 42 | + |
| 43 | + return !asyncVisitor.hasValidAsync; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +class _AsyncVisitor extends RecursiveAstVisitor<void> { |
| 48 | + bool hasValidAsync = false; |
| 49 | + |
| 50 | + @override |
| 51 | + void visitReturnStatement(ReturnStatement node) { |
| 52 | + super.visitReturnStatement(node); |
| 53 | + |
| 54 | + final type = node.expression?.staticType; |
| 55 | + |
| 56 | + if (type == null || !type.isDartAsyncFuture) { |
| 57 | + hasValidAsync = true; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + @override |
| 62 | + void visitThrowExpression(ThrowExpression node) { |
| 63 | + super.visitThrowExpression(node); |
| 64 | + |
| 65 | + hasValidAsync = true; |
| 66 | + } |
| 67 | + |
| 68 | + @override |
| 69 | + void visitAwaitExpression(AwaitExpression node) { |
| 70 | + super.visitAwaitExpression(node); |
| 71 | + |
| 72 | + hasValidAsync = true; |
| 73 | + } |
| 74 | +} |
0 commit comments