|
| 1 | +part of 'avoid_redundant_async_on_load_rule.dart'; |
| 2 | + |
| 3 | +class _Visitor extends SimpleAstVisitor<void> { |
| 4 | + final _declarations = <MethodDeclaration>[]; |
| 5 | + |
| 6 | + Iterable<MethodDeclaration> get declarations => _declarations; |
| 7 | + |
| 8 | + @override |
| 9 | + void visitClassDeclaration(ClassDeclaration node) { |
| 10 | + super.visitClassDeclaration(node); |
| 11 | + |
| 12 | + final type = node.extendsClause?.superclass.type; |
| 13 | + if (type == null || !isComponentOrSubclass(type)) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + final onLoadMethod = node.members.firstWhereOrNull((member) => |
| 18 | + member is MethodDeclaration && |
| 19 | + member.name.lexeme == 'onLoad' && |
| 20 | + isOverride(member.metadata)); |
| 21 | + |
| 22 | + if (onLoadMethod is MethodDeclaration) { |
| 23 | + if (_hasFutureType(onLoadMethod.returnType?.type) && |
| 24 | + _hasRedundantAsync(onLoadMethod.body)) { |
| 25 | + _declarations.add(onLoadMethod); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + bool _hasFutureType(DartType? type) => |
| 31 | + type != null && (type.isDartAsyncFuture || type.isDartAsyncFutureOr); |
| 32 | + |
| 33 | + bool _hasRedundantAsync(FunctionBody body) { |
| 34 | + if (body is ExpressionFunctionBody) { |
| 35 | + final type = body.expression.staticType; |
| 36 | + |
| 37 | + if (type != null && |
| 38 | + (type.isDartAsyncFuture || type.isDartAsyncFutureOr)) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + final asyncVisitor = _AsyncVisitor(body); |
| 44 | + body.parent?.visitChildren(asyncVisitor); |
| 45 | + |
| 46 | + return !asyncVisitor.hasValidAsync; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class _AsyncVisitor extends RecursiveAstVisitor<void> { |
| 51 | + final FunctionBody body; |
| 52 | + |
| 53 | + bool hasValidAsync = false; |
| 54 | + |
| 55 | + _AsyncVisitor(this.body); |
| 56 | + |
| 57 | + @override |
| 58 | + void visitReturnStatement(ReturnStatement node) { |
| 59 | + super.visitReturnStatement(node); |
| 60 | + |
| 61 | + hasValidAsync = true; |
| 62 | + } |
| 63 | + |
| 64 | + @override |
| 65 | + void visitAwaitExpression(AwaitExpression node) { |
| 66 | + super.visitAwaitExpression(node); |
| 67 | + |
| 68 | + hasValidAsync = true; |
| 69 | + } |
| 70 | +} |
0 commit comments