|
| 1 | +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:analyzer/dart/ast/token.dart'; |
| 6 | +import 'package:analyzer/dart/ast/visitor.dart'; |
| 7 | +import 'package:analyzer/dart/element/element2.dart'; |
| 8 | +import 'package:analyzer/error/listener.dart'; |
| 9 | +import 'package:analyzer/src/dart/ast/ast.dart'; |
| 10 | +import 'package:analyzer/src/error/codes.dart'; |
| 11 | +import 'package:analyzer/src/utilities/extensions/flutter.dart'; |
| 12 | + |
| 13 | +/// Helper for verifying the validity of @Preview(...) applications. |
| 14 | +/// |
| 15 | +/// The Flutter Widget Previewer relies on code generation to import code from |
| 16 | +/// a developer's project into a generated 'widget preview scaffold' that lives |
| 17 | +/// in the project's '.dart_tool' directory. The nature of this implementation |
| 18 | +/// means that any symbols referenced in the declaration of the preview (e.g., |
| 19 | +/// in the invocation of the `Preview(...)` constructor or the name of the |
| 20 | +/// preview function) must be publicly accessible from outside the library in |
| 21 | +/// which they are defined. One of the main uses for this verifier is to flag |
| 22 | +/// usages of private symbols within preview declarations. |
| 23 | +/// |
| 24 | +/// This verifier also ensures that the `@Preview(...)` annotation can only be |
| 25 | +/// applied to a functions or constructors that: |
| 26 | +/// |
| 27 | +/// - Are statically accessible (e.g., no instance methods) |
| 28 | +/// - Have explicit implementations (e.g., not abstract or external) |
| 29 | +class WidgetPreviewVerifier { |
| 30 | + final ErrorReporter _errorReporter; |
| 31 | + |
| 32 | + WidgetPreviewVerifier(this._errorReporter); |
| 33 | + |
| 34 | + /// Check is [node] is a Widget Preview application and verify its |
| 35 | + /// correctness. |
| 36 | + void checkAnnotation(Annotation node) { |
| 37 | + if (node.elementAnnotation?.isWidgetPreview ?? false) { |
| 38 | + _checkWidgetPreview(node); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + void _checkWidgetPreview(Annotation node) { |
| 43 | + if (node.arguments == null) { |
| 44 | + // This is an invalid annotation application since there's no constructor |
| 45 | + // invocation. |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + var parent = node.parent; |
| 50 | + bool isValidApplication = switch (parent) { |
| 51 | + // First, check that the preview application is happening in a supported |
| 52 | + // context. |
| 53 | + _ when !_isSupportedParent(node: parent) => false, |
| 54 | + ConstructorDeclaration() => _isValidConstructorPreviewApplication( |
| 55 | + declaration: parent, |
| 56 | + ), |
| 57 | + FunctionDeclaration() => _isValidFunctionPreviewApplication( |
| 58 | + declaration: parent, |
| 59 | + ), |
| 60 | + MethodDeclaration() => _isValidMethodPreviewApplication( |
| 61 | + declaration: parent, |
| 62 | + ), |
| 63 | + _ => false, |
| 64 | + }; |
| 65 | + |
| 66 | + if (!isValidApplication) { |
| 67 | + _errorReporter.atNode( |
| 68 | + node.name, |
| 69 | + WarningCode.INVALID_WIDGET_PREVIEW_APPLICATION, |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + var visitor = _InvalidWidgetPreviewArgumentDetectorVisitor( |
| 74 | + errorReporter: _errorReporter, |
| 75 | + ); |
| 76 | + node.arguments!.accept(visitor); |
| 77 | + } |
| 78 | + |
| 79 | + bool _hasRequiredParameters(NodeList<FormalParameter> parameters) { |
| 80 | + return parameters.any((e) => e.isRequired); |
| 81 | + } |
| 82 | + |
| 83 | + /// Returns true if `name` is private or `node.parent` is a [ClassDeclaration] |
| 84 | + /// that has a private name. |
| 85 | + bool _isPrivateContext({required Token? name, required AstNode node}) { |
| 86 | + if (Identifier.isPrivateName(name?.lexeme ?? '')) { |
| 87 | + return true; |
| 88 | + } |
| 89 | + var parent = node.parent; |
| 90 | + if (parent == null) return false; |
| 91 | + |
| 92 | + return switch (parent) { |
| 93 | + ClassDeclaration(:var name) => Identifier.isPrivateName(name.lexeme), |
| 94 | + EnumDeclaration(:var name) => Identifier.isPrivateName(name.lexeme), |
| 95 | + ExtensionDeclaration(:var name) => Identifier.isPrivateName( |
| 96 | + name?.lexeme ?? '', |
| 97 | + ), |
| 98 | + ExtensionTypeDeclaration(:var name) => Identifier.isPrivateName( |
| 99 | + name.lexeme, |
| 100 | + ), |
| 101 | + MixinDeclaration(:var name) => Identifier.isPrivateName(name.lexeme), |
| 102 | + _ => false, |
| 103 | + }; |
| 104 | + } |
| 105 | + |
| 106 | + /// Returns true if `node.parent` is a supported context for defining widget |
| 107 | + /// previews. |
| 108 | + /// |
| 109 | + /// Currently, this only includes previews defined within classes and at the |
| 110 | + /// top level of a compilation unit. |
| 111 | + bool _isSupportedParent({required AstNode node}) { |
| 112 | + return switch (node.parent) { |
| 113 | + ClassDeclaration() || CompilationUnit() => true, |
| 114 | + _ => false, |
| 115 | + }; |
| 116 | + } |
| 117 | + |
| 118 | + /// Returns true if `declaration` is a valid constructor target for a widget |
| 119 | + /// preview application. |
| 120 | + /// |
| 121 | + /// Constructor preview applications are valid if: |
| 122 | + /// - The class and constructor names are public |
| 123 | + /// - The class is a subtype of Widget |
| 124 | + /// - The class is not abstract or is a valid factory constructor |
| 125 | + /// - The constructor is not external |
| 126 | + /// - The constructor does not have any required arguments |
| 127 | + bool _isValidConstructorPreviewApplication({ |
| 128 | + required ConstructorDeclaration declaration, |
| 129 | + }) { |
| 130 | + if (declaration case ConstructorDeclaration( |
| 131 | + :var name, |
| 132 | + :var externalKeyword, |
| 133 | + :var factoryKeyword, |
| 134 | + parent: ClassDeclaration(declaredFragment: ClassFragment(:var element)), |
| 135 | + parameters: FormalParameterList(:var parameters), |
| 136 | + )) { |
| 137 | + return !_isPrivateContext(name: name, node: declaration) && |
| 138 | + element.isWidget && |
| 139 | + !(element.isAbstract && factoryKeyword == null) && |
| 140 | + externalKeyword == null && |
| 141 | + !_hasRequiredParameters(parameters); |
| 142 | + } |
| 143 | + return false; |
| 144 | + } |
| 145 | + |
| 146 | + /// Returns true if `declaration` is a valid top-level function target for a |
| 147 | + /// widget preview application. |
| 148 | + /// |
| 149 | + /// Function preview applications are valid if: |
| 150 | + /// - The function name is public |
| 151 | + /// - The function is not a nested function |
| 152 | + /// - The function is not external |
| 153 | + /// - The function returns a subtype of `Widget` or `WidgetBuilder` |
| 154 | + /// - The function does not have any required arguments |
| 155 | + bool _isValidFunctionPreviewApplication({ |
| 156 | + required FunctionDeclaration declaration, |
| 157 | + }) { |
| 158 | + if (declaration case FunctionDeclaration( |
| 159 | + :var name, |
| 160 | + :var externalKeyword, |
| 161 | + :NamedType returnType, |
| 162 | + functionExpression: FunctionExpression( |
| 163 | + parameters: FormalParameterList(:var parameters), |
| 164 | + ), |
| 165 | + )) { |
| 166 | + return !_isPrivateContext(name: name, node: declaration) && |
| 167 | + // Check for nested function. |
| 168 | + declaration.parent is! FunctionDeclarationStatement && |
| 169 | + externalKeyword == null && |
| 170 | + returnType.isValidWidgetPreviewReturnType && |
| 171 | + !_hasRequiredParameters(parameters); |
| 172 | + } |
| 173 | + return false; |
| 174 | + } |
| 175 | + |
| 176 | + /// Returns true if `declaration` is a valid static class member target for a |
| 177 | + /// widget preview application. |
| 178 | + /// |
| 179 | + /// Class member preview applications are valid if: |
| 180 | + /// - The function is static |
| 181 | + /// - The function name is public |
| 182 | + /// - The function is not external |
| 183 | + /// - The function returns a subtype of `Widget` or `WidgetBuilder` |
| 184 | + /// - The function does not have any required arguments |
| 185 | + bool _isValidMethodPreviewApplication({ |
| 186 | + required MethodDeclaration declaration, |
| 187 | + }) { |
| 188 | + if (declaration case MethodDeclaration( |
| 189 | + :var isStatic, |
| 190 | + :var externalKeyword, |
| 191 | + :var name, |
| 192 | + :NamedType returnType, |
| 193 | + parameters: FormalParameterList(:var parameters), |
| 194 | + )) { |
| 195 | + return !_isPrivateContext(name: name, node: declaration) && |
| 196 | + isStatic && |
| 197 | + // Check for nested function. |
| 198 | + declaration.parent is! FunctionDeclarationStatement && |
| 199 | + externalKeyword == null && |
| 200 | + returnType.isValidWidgetPreviewReturnType && |
| 201 | + !_hasRequiredParameters(parameters); |
| 202 | + } |
| 203 | + return false; |
| 204 | + } |
| 205 | +} |
| 206 | + |
| 207 | +class _InvalidWidgetPreviewArgumentDetectorVisitor extends RecursiveAstVisitor { |
| 208 | + final ErrorReporter errorReporter; |
| 209 | + |
| 210 | + NamedExpression? rootArgument; |
| 211 | + _InvalidWidgetPreviewArgumentDetectorVisitor({required this.errorReporter}); |
| 212 | + |
| 213 | + @override |
| 214 | + void visitArgumentList(ArgumentList node) { |
| 215 | + for (var argument in node.arguments) { |
| 216 | + // All arguments to Preview(...) are named. |
| 217 | + if (argument is NamedExpression) { |
| 218 | + rootArgument = argument; |
| 219 | + visitNamedExpression(argument); |
| 220 | + rootArgument = null; |
| 221 | + } |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + @override |
| 226 | + void visitNamedExpression(NamedExpression node) { |
| 227 | + super.visitNamedExpression(node); |
| 228 | + } |
| 229 | + |
| 230 | + @override |
| 231 | + void visitSimpleIdentifier(SimpleIdentifier node) { |
| 232 | + if (Identifier.isPrivateName(node.name)) { |
| 233 | + errorReporter.atNode( |
| 234 | + rootArgument!, |
| 235 | + WarningCode.INVALID_WIDGET_PREVIEW_PRIVATE_ARGUMENT, |
| 236 | + arguments: [node.name, node.name.replaceFirst(RegExp('_*'), '')], |
| 237 | + ); |
| 238 | + } |
| 239 | + super.visitSimpleIdentifier(node); |
| 240 | + } |
| 241 | +} |
0 commit comments