OLD | NEW |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 /// Encapsulates how to invoke the analyzer resolver and overrides how it | 5 /// Encapsulates how to invoke the analyzer resolver and overrides how it |
6 /// computes types on expressions to use our restricted set of types. | 6 /// computes types on expressions to use our restricted set of types. |
7 library dev_compiler.src.checker.resolver; | 7 library dev_compiler.src.checker.resolver; |
8 | 8 |
9 import 'package:analyzer/analyzer.dart'; | 9 import 'package:analyzer/analyzer.dart'; |
10 import 'package:analyzer/src/generated/ast.dart'; | 10 import 'package:analyzer/src/generated/ast.dart'; |
11 import 'package:analyzer/src/generated/element.dart'; | 11 import 'package:analyzer/src/generated/element.dart'; |
12 import 'package:analyzer/src/generated/engine.dart'; | 12 import 'package:analyzer/src/generated/engine.dart'; |
13 import 'package:analyzer/src/generated/error.dart' as analyzer; | 13 import 'package:analyzer/src/generated/error.dart' as analyzer; |
14 import 'package:analyzer/src/generated/java_io.dart' show JavaFile; | 14 import 'package:analyzer/src/generated/java_io.dart' show JavaFile; |
15 import 'package:analyzer/src/generated/resolver.dart'; | 15 import 'package:analyzer/src/generated/resolver.dart'; |
16 import 'package:analyzer/src/generated/static_type_analyzer.dart'; | |
17 import 'package:analyzer/src/generated/sdk_io.dart' show DirectoryBasedDartSdk; | 16 import 'package:analyzer/src/generated/sdk_io.dart' show DirectoryBasedDartSdk; |
18 import 'package:analyzer/src/generated/source.dart' show DartUriResolver; | 17 import 'package:analyzer/src/generated/source.dart' show DartUriResolver; |
19 import 'package:analyzer/src/generated/source.dart' show Source; | 18 import 'package:analyzer/src/generated/source.dart' show Source; |
20 import 'package:analyzer/src/generated/source_io.dart'; | 19 import 'package:analyzer/src/generated/source_io.dart'; |
| 20 import 'package:analyzer/src/generated/static_type_analyzer.dart'; |
21 import 'package:logging/logging.dart' as logger; | 21 import 'package:logging/logging.dart' as logger; |
22 | 22 |
23 import 'package:dev_compiler/src/options.dart'; | 23 import 'package:dev_compiler/src/options.dart'; |
24 import 'package:dev_compiler/src/report.dart'; | 24 import 'package:dev_compiler/src/report.dart'; |
25 import 'package:dev_compiler/src/utils.dart'; | 25 import 'package:dev_compiler/src/utils.dart'; |
26 import 'dart_sdk.dart'; | 26 import 'dart_sdk.dart'; |
27 import 'multi_package_resolver.dart'; | 27 import 'multi_package_resolver.dart'; |
28 | 28 |
29 final _log = new logger.Logger('dev_compiler.src.resolver'); | 29 final _log = new logger.Logger('dev_compiler.src.resolver'); |
30 | 30 |
(...skipping 68 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
99 | 99 |
100 const AnalyzerError(String message, logger.Level level, int begin, int end) | 100 const AnalyzerError(String message, logger.Level level, int begin, int end) |
101 : super('[from analyzer]: $message', level, begin, end); | 101 : super('[from analyzer]: $message', level, begin, end); |
102 } | 102 } |
103 | 103 |
104 /// Creates an analysis context that contains our restricted typing rules. | 104 /// Creates an analysis context that contains our restricted typing rules. |
105 InternalAnalysisContext _initContext(ResolverOptions options) { | 105 InternalAnalysisContext _initContext(ResolverOptions options) { |
106 var analysisOptions = new AnalysisOptionsImpl()..cacheSize = 512; | 106 var analysisOptions = new AnalysisOptionsImpl()..cacheSize = 512; |
107 AnalysisContextImpl res = AnalysisEngine.instance.createAnalysisContext(); | 107 AnalysisContextImpl res = AnalysisEngine.instance.createAnalysisContext(); |
108 res.analysisOptions = analysisOptions; | 108 res.analysisOptions = analysisOptions; |
109 res.resolverVisitorFactory = RestrictedResolverVisitor.constructor(options); | 109 res.libraryResolverFactory = |
110 if (options.inferFromOverrides) { | 110 (context) => new LibraryResolverWithInference(context, options); |
111 res.typeResolverVisitorFactory = RestrictedTypeResolverVisitor.constructor; | |
112 } | |
113 return res; | 111 return res; |
114 } | 112 } |
115 | 113 |
116 /// Overrides the default [ResolverVisitor] to comply with DDC's restricted | 114 /// A [LibraryResolver] that performs inference on top-levels and fields based |
117 /// type rules. This changes how types are promoted in conditional expressions | 115 /// on the value of the initializer, and on fields and methods based on |
118 /// and statements, and how types are computed on expressions. | 116 /// overridden members in super classes. |
| 117 class LibraryResolverWithInference extends LibraryResolver { |
| 118 final ResolverOptions _options; |
| 119 |
| 120 LibraryResolverWithInference(context, this._options) : super(context); |
| 121 |
| 122 @override |
| 123 void resolveReferencesAndTypes() { |
| 124 _resolveVariableReferences(); |
| 125 |
| 126 // Skip inference in the core libraries (note: resolvedLibraries are the |
| 127 // libraries in the current strongly connected component). |
| 128 if (resolvedLibraries.any((l) => l.librarySource.isInSystemLibrary)) { |
| 129 _resolveReferencesAndTypes(false); |
| 130 return; |
| 131 } |
| 132 |
| 133 // Run resolution in two stages, skipping method bodies first, so we can run |
| 134 // type-inference before we fully analyze methods. |
| 135 _resolveReferencesAndTypes(true); |
| 136 _runInference(); |
| 137 _resolveReferencesAndTypes(false); |
| 138 } |
| 139 |
| 140 // Note: this was split from _resolveReferencesAndTypesInLibrary so we do it |
| 141 // only once. |
| 142 void _resolveVariableReferences() { |
| 143 for (Library library in resolvedLibraries) { |
| 144 for (Source source in library.compilationUnitSources) { |
| 145 library.getAST(source).accept( |
| 146 new VariableResolverVisitor.con1(library, source, typeProvider)); |
| 147 } |
| 148 } |
| 149 } |
| 150 |
| 151 // Note: this was split from _resolveReferencesAndTypesInLibrary so we can do |
| 152 // resolution in pieces. |
| 153 void _resolveReferencesAndTypes(bool skipMethods) { |
| 154 for (Library library in resolvedLibraries) { |
| 155 for (Source source in library.compilationUnitSources) { |
| 156 library.getAST(source).accept(new RestrictedResolverVisitor( |
| 157 library, source, typeProvider, _options, skipMethods)); |
| 158 } |
| 159 } |
| 160 } |
| 161 |
| 162 _runInference() { |
| 163 var consts = []; |
| 164 var statics = []; |
| 165 var classes = []; |
| 166 |
| 167 // Extract top-level members that are const, statics, or classes. |
| 168 for (Library library in resolvedLibraries) { |
| 169 for (Source source in library.compilationUnitSources) { |
| 170 CompilationUnit ast = library.getAST(source); |
| 171 for (var declaration in ast.declarations) { |
| 172 if (declaration is TopLevelVariableDeclaration) { |
| 173 if (declaration.variables.isConst) { |
| 174 consts.addAll(declaration.variables.variables); |
| 175 } else { |
| 176 statics.addAll(declaration.variables.variables); |
| 177 } |
| 178 } else if (declaration is ClassDeclaration) { |
| 179 classes.add(declaration); |
| 180 for (var member in declaration.members) { |
| 181 if (member is! FieldDeclaration) continue; |
| 182 if (member.fields.isConst) { |
| 183 consts.addAll(member.fields.variables); |
| 184 } else if (member.isStatic) { |
| 185 statics.addAll(member.fields.variables); |
| 186 } |
| 187 } |
| 188 } |
| 189 } |
| 190 } |
| 191 } |
| 192 |
| 193 // TODO(sigmund): consider propagating const types after this layer of |
| 194 // inference, so their types can be used to initialize other members below. |
| 195 _inferVariableFromInitializer(consts); |
| 196 _inferVariableFromInitializer(statics); |
| 197 |
| 198 // Track types in this strongly connected component, ensure we visit |
| 199 // supertypes before subtypes. |
| 200 var typeToDeclaration = <InterfaceType, ClassDeclaration>{}; |
| 201 classes.forEach((c) => typeToDeclaration[c.element.type] = c); |
| 202 var seen = new Set<InterfaceType>(); |
| 203 visit(ClassDeclaration cls) { |
| 204 var element = cls.element; |
| 205 var type = element.type; |
| 206 if (seen.contains(type)) return; |
| 207 for (var supertype in element.allSupertypes) { |
| 208 var supertypeClass = typeToDeclaration[supertype]; |
| 209 if (supertypeClass != null) visit(supertypeClass); |
| 210 } |
| 211 seen.add(type); |
| 212 |
| 213 _isInstanceField(f) => |
| 214 f is FieldDeclaration && !f.isStatic && !f.fields.isConst; |
| 215 |
| 216 if (_options.inferFromOverrides) { |
| 217 // Infer field types from overrides first, otherwise from initializers. |
| 218 var pending = new Set<VariableDeclaration>(); |
| 219 cls.members |
| 220 .where(_isInstanceField) |
| 221 .forEach((f) => _inferFieldTypeFromOverride(f, pending)); |
| 222 if (pending.isNotEmpty) _inferVariableFromInitializer(pending); |
| 223 |
| 224 // Infer return-types from overrides |
| 225 cls.members |
| 226 .where((m) => m is MethodDeclaration && !m.isStatic) |
| 227 .forEach(_inferMethodReturnTypeFromOverride); |
| 228 } else { |
| 229 _inferVariableFromInitializer(cls.members |
| 230 .where(_isInstanceField) |
| 231 .expand((f) => f.fields.variables)); |
| 232 } |
| 233 } |
| 234 classes.forEach(visit); |
| 235 } |
| 236 |
| 237 /// Attempts to infer the type on [field] from overridden fields or getters if |
| 238 /// a type was not specified. If no type could be inferred, but it contains an |
| 239 /// initializer, we add it to [pending] so we can try to infer it using the |
| 240 /// initializer type instead. |
| 241 void _inferFieldTypeFromOverride( |
| 242 FieldDeclaration field, Set<VariableDeclaration> pending) { |
| 243 var variables = field.fields; |
| 244 for (var variable in variables.variables) { |
| 245 var varElement = variable.element; |
| 246 if (!varElement.type.isDynamic || variables.type != null) continue; |
| 247 var getter = varElement.getter; |
| 248 // Note: type will be null only when there are no overrides. When some |
| 249 // override's type was not specified and couldn't be inferred, the type |
| 250 // here will be dynamic. |
| 251 var type = searchTypeFor(varElement.enclosingElement.type, getter); |
| 252 |
| 253 // Infer from the RHS when there are no overrides. |
| 254 if (type == null) { |
| 255 if (variable.initializer != null) pending.add(variable); |
| 256 continue; |
| 257 } |
| 258 |
| 259 // When field is final and overriden getter is dynamic, we can infer from |
| 260 // the RHS without breaking subtyping rules (return type is covariant). |
| 261 if (type.returnType.isDynamic) { |
| 262 if (variables.isFinal && variable.initializer != null) { |
| 263 pending.add(variable); |
| 264 } |
| 265 continue; |
| 266 } |
| 267 |
| 268 // Use type from the override. |
| 269 var newType = type.returnType; |
| 270 varElement.type = newType; |
| 271 varElement.getter.returnType = newType; |
| 272 if (!varElement.isFinal) varElement.setter.parameters[0].type = newType; |
| 273 } |
| 274 } |
| 275 |
| 276 void _inferMethodReturnTypeFromOverride(MethodDeclaration method) { |
| 277 var methodElement = method.element; |
| 278 if ((methodElement is MethodElement || |
| 279 methodElement is PropertyAccessorElement) && |
| 280 methodElement.returnType.isDynamic && |
| 281 method.returnType == null) { |
| 282 var type = |
| 283 searchTypeFor(methodElement.enclosingElement.type, methodElement); |
| 284 if (type != null && !type.returnType.isDynamic) { |
| 285 methodElement.returnType = type.returnType; |
| 286 } |
| 287 } |
| 288 } |
| 289 |
| 290 void _inferVariableFromInitializer(Iterable<VariableDeclaration> variables) { |
| 291 for (var variable in variables) { |
| 292 var declaration = variable.parent; |
| 293 // Only infer on variables that don't have any declared type. |
| 294 if (declaration.type != null) continue; |
| 295 if (_options.onlyInferConstsAndFinalFields && |
| 296 !declaration.isFinal && |
| 297 !declaration.isConst) { |
| 298 return; |
| 299 } |
| 300 var initializer = variable.initializer; |
| 301 if (initializer == null) continue; |
| 302 var type = initializer.staticType; |
| 303 if (type == null || type.isDynamic || type.isBottom) continue; |
| 304 if (!_canInferFrom(initializer)) continue; |
| 305 var element = variable.element; |
| 306 // Note: it's ok to update the type here, since initializer.staticType |
| 307 // is already computed for all declarations in the library cycle. The |
| 308 // new types will only be propagated on a second run of the |
| 309 // ResolverVisitor. |
| 310 element.type = type; |
| 311 element.getter.returnType = type; |
| 312 if (!element.isFinal && !element.isConst) { |
| 313 element.setter.parameters[0].type = type; |
| 314 } |
| 315 } |
| 316 } |
| 317 |
| 318 bool _canInferFrom(Expression expression) { |
| 319 if (expression is Literal) return true; |
| 320 if (expression is InstanceCreationExpression) return true; |
| 321 if (expression is FunctionExpression) return true; |
| 322 if (expression is AsExpression) return true; |
| 323 if (expression is CascadeExpression) { |
| 324 return _canInferFrom(expression.target); |
| 325 } |
| 326 if (expression is SimpleIdentifier || expression is PropertyAccess) { |
| 327 return _options.inferStaticsFromIdentifiers; |
| 328 } |
| 329 if (expression is PrefixedIdentifier) { |
| 330 if (expression.staticElement is PropertyAccessorElement) { |
| 331 return _options.inferStaticsFromIdentifiers; |
| 332 } |
| 333 return _canInferFrom(expression.identifier); |
| 334 } |
| 335 if (expression is MethodInvocation) { |
| 336 return _canInferFrom(expression.target); |
| 337 } |
| 338 if (expression is BinaryExpression) { |
| 339 return _canInferFrom(expression.leftOperand); |
| 340 } |
| 341 if (expression is ConditionalExpression) { |
| 342 return _canInferFrom(expression.thenExpression) && |
| 343 _canInferFrom(expression.elseExpression); |
| 344 } |
| 345 if (expression is PrefixExpression) { |
| 346 return _canInferFrom(expression.operand); |
| 347 } |
| 348 if (expression is PostfixExpression) { |
| 349 return _canInferFrom(expression.operand); |
| 350 } |
| 351 return false; |
| 352 } |
| 353 } |
| 354 |
| 355 /// Overrides the default [ResolverVisitor] to support type inference in |
| 356 /// [LibraryResolverWithInference] above. |
| 357 /// |
| 358 /// Before inference, this visitor is used to resolve top-levels, classes, and |
| 359 /// fields, but nothing withihn method bodies. After inference, this visitor is |
| 360 /// used again to step into method bodies and complete resolution as a second |
| 361 /// phase. |
119 class RestrictedResolverVisitor extends ResolverVisitor { | 362 class RestrictedResolverVisitor extends ResolverVisitor { |
120 final TypeProvider _typeProvider; | 363 final TypeProvider _typeProvider; |
121 | 364 |
| 365 /// Whether to skip resolution within method bodies. |
| 366 final bool skipMethodBodies; |
| 367 |
122 RestrictedResolverVisitor(Library library, Source source, | 368 RestrictedResolverVisitor(Library library, Source source, |
123 TypeProvider typeProvider, ResolverOptions options) | 369 TypeProvider typeProvider, ResolverOptions options, this.skipMethodBodies) |
124 : _typeProvider = typeProvider, | 370 : _typeProvider = typeProvider, |
125 super.con1(library, source, typeProvider, | 371 super.con1(library, source, typeProvider, |
126 typeAnalyzerFactory: RestrictedStaticTypeAnalyzer | 372 typeAnalyzerFactory: RestrictedStaticTypeAnalyzer.constructor); |
127 .constructor(options)); | |
128 | |
129 static constructor(options) => | |
130 (Library library, Source source, TypeProvider typeProvider) => | |
131 new RestrictedResolverVisitor(library, source, typeProvider, options); | |
132 | 373 |
133 @override | 374 @override |
134 visitCatchClause(CatchClause node) { | 375 visitCatchClause(CatchClause node) { |
135 var stack = node.stackTraceParameter; | 376 var stack = node.stackTraceParameter; |
136 if (stack != null) { | 377 if (stack != null) { |
137 // TODO(jmesserly): analyzer does not correctly associate StackTrace type. | 378 // TODO(jmesserly): analyzer does not correctly associate StackTrace type. |
138 // It happens too late in TypeResolverVisitor visitCatchClause. | 379 // It happens too late in TypeResolverVisitor visitCatchClause. |
139 var element = stack.staticElement; | 380 var element = stack.staticElement; |
140 if (element is VariableElementImpl && element.type == null) { | 381 if (element is VariableElementImpl && element.type == null) { |
141 // From the language spec: | 382 // From the language spec: |
142 // The static type of p1 is T and the static type of p2 is StackTrace. | 383 // The static type of p1 is T and the static type of p2 is StackTrace. |
143 element.type = _typeProvider.stackTraceType; | 384 element.type = _typeProvider.stackTraceType; |
144 } | 385 } |
145 } | 386 } |
146 return super.visitCatchClause(node); | 387 return super.visitCatchClause(node); |
147 } | 388 } |
148 | 389 |
149 @override | 390 @override |
150 Object visitCompilationUnit(CompilationUnit node) { | 391 Object visitNode(AstNode node) { |
151 // Similar to the definition in ResolverVisitor.visitCompilationUnit, but | 392 if (skipMethodBodies && |
152 // changed to visit all top-level fields first, then static fields on all | 393 (node is FunctionBody || |
153 // classes, then all top-level functions, then the rest of the classes. | 394 node is FunctionExpression || |
154 RestrictedStaticTypeAnalyzer restrictedAnalyzer = typeAnalyzer_J2DAccessor; | 395 node is FunctionExpressionInvocation || |
155 overrideManager.enterScope(); | 396 node is SuperConstructorInvocation || |
156 try { | 397 node is RedirectingConstructorInvocation || |
157 var thisLib = node.element.enclosingElement; | 398 node is Annotation || |
158 restrictedAnalyzer._isLibraryContainedInSingleUnit.putIfAbsent(thisLib, | 399 node is Comment)) { |
159 () { | 400 return null; |
160 if (thisLib.units.length > 1) return false; | |
161 for (var lib in thisLib.visibleLibraries) { | |
162 if (lib != thisLib && lib.visibleLibraries.contains(thisLib)) { | |
163 return false; | |
164 } | |
165 } | |
166 return true; | |
167 }); | |
168 | |
169 void accept(n) { | |
170 n.accept(this); | |
171 } | |
172 node.directives.forEach(accept); | |
173 var declarations = node.declarations; | |
174 | |
175 declarations | |
176 .where((d) => d is TopLevelVariableDeclaration) | |
177 .forEach(accept); | |
178 | |
179 // Visit classes before top-level methods so that we can visit static | |
180 // fields first. | |
181 // TODO(sigmund): consider visiting static fields only at this point | |
182 // (the challenge is that to visit them we first need to create the scope | |
183 // for the class here, and reuse it later when visiting the class | |
184 // declaration to ensure that we correctly construct the scopes and that | |
185 // we visit each static field only once). | |
186 declarations.where((d) => d is ClassDeclaration).forEach(accept); | |
187 | |
188 declarations | |
189 .where((d) => | |
190 d is! TopLevelVariableDeclaration && d is! ClassDeclaration) | |
191 .forEach(accept); | |
192 } finally { | |
193 overrideManager.exitScope(); | |
194 } | 401 } |
195 node.accept(elementResolver_J2DAccessor); | 402 assert(node is! Statement || !skipMethodBodies); |
196 node.accept(restrictedAnalyzer); | 403 return super.visitNode(node); |
197 return null; | |
198 } | 404 } |
199 | 405 |
200 @override | 406 @override |
201 void visitClassMembersInScope(ClassDeclaration node) { | 407 Object visitMethodDeclaration(MethodDeclaration node) { |
202 safelyVisit(node.documentationComment); | 408 if (skipMethodBodies) { |
203 node.metadata.accept(this); | 409 node.accept(elementResolver_J2DAccessor); |
| 410 node.accept(typeAnalyzer_J2DAccessor); |
| 411 return null; |
| 412 } else { |
| 413 return super.visitMethodDeclaration(node); |
| 414 } |
| 415 } |
204 | 416 |
205 // This overrides the default way members are visited so that fields are | 417 @override |
206 // visited before method declarations. | 418 Object visitFunctionDeclaration(FunctionDeclaration node) { |
207 for (var n in node.members) { | 419 if (skipMethodBodies) { |
208 if (n is FieldDeclaration) n.accept(this); | 420 node.accept(elementResolver_J2DAccessor); |
| 421 node.accept(typeAnalyzer_J2DAccessor); |
| 422 return null; |
| 423 } else { |
| 424 return super.visitFunctionDeclaration(node); |
209 } | 425 } |
210 for (var n in node.members) { | 426 } |
211 if (n is! FieldDeclaration) n.accept(this); | 427 |
| 428 @override |
| 429 Object visitConstructorDeclaration(ConstructorDeclaration node) { |
| 430 if (skipMethodBodies) { |
| 431 node.accept(elementResolver_J2DAccessor); |
| 432 node.accept(typeAnalyzer_J2DAccessor); |
| 433 return null; |
| 434 } else { |
| 435 return super.visitConstructorDeclaration(node); |
212 } | 436 } |
213 } | 437 } |
214 } | 438 } |
215 | 439 |
216 /// Overrides the default [StaticTypeAnalyzer] to adjust rules that are stricter | 440 /// Overrides the default [StaticTypeAnalyzer] to adjust rules that are stricter |
217 /// in the restricted type system and to infer types for untyped local | 441 /// in the restricted type system and to infer types for untyped local |
218 /// variables. | 442 /// variables. |
219 class RestrictedStaticTypeAnalyzer extends StaticTypeAnalyzer { | 443 class RestrictedStaticTypeAnalyzer extends StaticTypeAnalyzer { |
220 final TypeProvider _typeProvider; | 444 final TypeProvider _typeProvider; |
221 final ResolverOptions _options; | |
222 | 445 |
223 // TODO(sigmund): this needs to go away. This is currently a restriction | 446 RestrictedStaticTypeAnalyzer(ResolverVisitor r) |
224 // because we are not overriding things early enough in the analyzer. This | |
225 // restriction makes it safe to run the inference later, but only on libraries | |
226 // that are contained in a single file and are not part of a cycle. | |
227 Map<LibraryElement, bool> _isLibraryContainedInSingleUnit = {}; | |
228 | |
229 RestrictedStaticTypeAnalyzer(ResolverVisitor r, this._options) | |
230 : _typeProvider = r.typeProvider, | 447 : _typeProvider = r.typeProvider, |
231 super(r); | 448 super(r); |
232 | 449 |
233 static constructor(options) => | 450 static constructor(ResolverVisitor r) => new RestrictedStaticTypeAnalyzer(r); |
234 (r) => new RestrictedStaticTypeAnalyzer(r, options); | |
235 | 451 |
236 @override // to infer type from initializers | 452 @override // to infer type from initializers |
237 visitVariableDeclaration(VariableDeclaration node) { | 453 visitVariableDeclaration(VariableDeclaration node) { |
238 _inferType(node); | 454 _inferType(node); |
239 return super.visitVariableDeclaration(node); | 455 return super.visitVariableDeclaration(node); |
240 } | 456 } |
241 | 457 |
242 /// Infer the type of a variable based on the initializer's type. | 458 /// Infer the type of a variable based on the initializer's type. |
243 void _inferType(VariableDeclaration node) { | 459 void _inferType(VariableDeclaration node) { |
244 var initializer = node.initializer; | 460 var initializer = node.initializer; |
245 if (initializer == null) return; | 461 if (initializer == null) return; |
246 | 462 |
247 var declaredType = (node.parent as VariableDeclarationList).type; | 463 var declaredType = (node.parent as VariableDeclarationList).type; |
248 if (declaredType != null) return; | 464 if (declaredType != null) return; |
249 var element = node.element; | 465 var element = node.element; |
| 466 if (element is! LocalVariableElement) return; |
250 if (element.type != _typeProvider.dynamicType) return; | 467 if (element.type != _typeProvider.dynamicType) return; |
251 | 468 |
252 // Local variables can be inferred automatically, for top-levels and fields | |
253 // we rule out cases that could depend on the order in which we process | |
254 // them. | |
255 if (element is! LocalVariableElement) { | |
256 if (_options.onlyInferConstsAndFinalFields && | |
257 !element.isConst && | |
258 !element.isFinal) { | |
259 return; | |
260 } | |
261 // Only infer types if the library is not in a cycle. Otherwise we can't | |
262 // guarantee that we are order independent (we can't guarantee that we'll | |
263 // visit all top-level declarations in all libraries, before we visit | |
264 // methods in all libraries). | |
265 var thisLib = enclosingLibrary(element); | |
266 if (!_canBeInferredIndependently(initializer, thisLib)) return; | |
267 } | |
268 | |
269 var type = initializer.staticType; | 469 var type = initializer.staticType; |
270 if (type == null || type == _typeProvider.bottomType) return; | 470 if (type == null || type == _typeProvider.bottomType) return; |
271 element.type = type; | 471 element.type = type; |
272 if (element is PropertyInducingElement) { | 472 if (element is PropertyInducingElement) { |
273 element.getter.returnType = type; | 473 element.getter.returnType = type; |
274 if (!element.isFinal && !element.isConst) { | 474 if (!element.isFinal && !element.isConst) { |
275 element.setter.parameters[0].type = type; | 475 element.setter.parameters[0].type = type; |
276 } | 476 } |
277 } | 477 } |
278 } | 478 } |
279 | 479 |
280 /// Whether we could determine the type of an [expression] in a way | |
281 /// that doesn't depend on the order in which we infer types within a | |
282 /// strongest connected component of libraries. | |
283 /// | |
284 /// This will return true if the expression consists just of literals or | |
285 /// allocations, if it only uses symbols that come from libraries that are | |
286 /// clearly processed before the library where this expression occurs | |
287 /// ([thisLib]), or if it's composed of these subexpressions (excluding fields | |
288 /// and top-levels that could've been inferred as well). | |
289 /// | |
290 /// The [inFieldContext] is used internally when visiting nested expressions | |
291 /// recursively. It indicates that the subexpression will be used in the | |
292 /// context of a field dereference. | |
293 bool _canBeInferredIndependently( | |
294 Expression expression, LibraryElement thisLib, | |
295 {bool inFieldContext: false}) { | |
296 if (_options.inferInNonStableOrder) return true; | |
297 if (!_options.inferStaticsFromIdentifiers && inFieldContext) return false; | |
298 if (!_isLibraryContainedInSingleUnit[thisLib]) return false; | |
299 if (expression is Literal) return true; | |
300 | |
301 if (expression is InstanceCreationExpression) { | |
302 if (!inFieldContext) return true; | |
303 var element = expression.staticElement; | |
304 if (element == null) { | |
305 print('Unexpected `null` element for $expression'); | |
306 return false; | |
307 } | |
308 return !_sameConnectedComponent(thisLib, element); | |
309 } | |
310 if (expression is FunctionExpression) return true; | |
311 if (expression is CascadeExpression) { | |
312 return _canBeInferredIndependently(expression.target, thisLib, | |
313 inFieldContext: inFieldContext); | |
314 } | |
315 | |
316 if (expression is MethodInvocation) { | |
317 return _canBeInferredIndependently(expression.target, thisLib, | |
318 inFieldContext: true); | |
319 } | |
320 | |
321 // Binary expressions, prefix/postfix expressions are are derived from the | |
322 // type of the operand, which is known at this time even for classes in the | |
323 // same library. | |
324 if (expression is BinaryExpression) { | |
325 return _canBeInferredIndependently(expression.leftOperand, thisLib, | |
326 inFieldContext: false); | |
327 } | |
328 if (expression is PrefixExpression) { | |
329 return _canBeInferredIndependently(expression.operand, thisLib, | |
330 inFieldContext: false); | |
331 } | |
332 if (expression is PostfixExpression) { | |
333 return _canBeInferredIndependently(expression.operand, thisLib, | |
334 inFieldContext: false); | |
335 } | |
336 | |
337 // Property accesses and prefix identifiers can be resolved as fields, in | |
338 // which case, we need to choose whether or not to infer based on the | |
339 // target. | |
340 if (expression is PropertyAccess) { | |
341 return _canBeInferredIndependently(expression.target, thisLib, | |
342 inFieldContext: true); | |
343 } | |
344 if (expression is PrefixedIdentifier) { | |
345 return _canBeInferredIndependently(expression.identifier, thisLib, | |
346 inFieldContext: true); | |
347 } | |
348 | |
349 if (expression is SimpleIdentifier) { | |
350 if (!_options.inferStaticsFromIdentifiers) return false; | |
351 var element = expression.bestElement; | |
352 if (element == null) { | |
353 print('Unexpected `null` element for $expression'); | |
354 return false; | |
355 } | |
356 return !_sameConnectedComponent(thisLib, element); | |
357 } | |
358 return false; | |
359 } | |
360 | |
361 /// Whether [dependency] is in the same strongest connected component of | |
362 /// libraries as [declaration]. | |
363 bool _sameConnectedComponent(LibraryElement thisLib, Element dependency) { | |
364 assert(dependency != null); | |
365 var otherLib = enclosingLibrary(dependency); | |
366 // Note: we would check here also whether | |
367 // otherLib.visibleLibraries.contains(thisLib), however because we are not | |
368 // inferring type on any library that belongs to a cycle or that contains | |
369 // parts, we know that this cannot be true. | |
370 return thisLib == otherLib; | |
371 } | |
372 | |
373 @override // to propagate types to identifiers | 480 @override // to propagate types to identifiers |
374 visitMethodInvocation(MethodInvocation node) { | 481 visitMethodInvocation(MethodInvocation node) { |
375 // TODO(sigmund): follow up with analyzer team - why is this needed? | 482 // TODO(sigmund): follow up with analyzer team - why is this needed? |
376 visitSimpleIdentifier(node.methodName); | 483 visitSimpleIdentifier(node.methodName); |
377 super.visitMethodInvocation(node); | 484 super.visitMethodInvocation(node); |
378 | 485 |
379 var e = node.methodName.staticElement; | 486 var e = node.methodName.staticElement; |
380 if (e is FunctionElement && | 487 if (e is FunctionElement && |
381 e.library.name == '_foreign_helper' && | 488 e.library.name == '_foreign_helper' && |
382 e.name == 'JS') { | 489 e.name == 'JS') { |
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
415 } | 522 } |
416 } | 523 } |
417 | 524 |
418 // Review note: no longer need to override visitFunctionExpression, this is | 525 // Review note: no longer need to override visitFunctionExpression, this is |
419 // handled by the analyzer internally. | 526 // handled by the analyzer internally. |
420 // TODO(vsm): in visitbinaryExpression: check computeStaticReturnType result? | 527 // TODO(vsm): in visitbinaryExpression: check computeStaticReturnType result? |
421 // TODO(vsm): in visitFunctionDeclaration: Should we ever use the expression | 528 // TODO(vsm): in visitFunctionDeclaration: Should we ever use the expression |
422 // type in a (...) => expr or just the written type? | 529 // type in a (...) => expr or just the written type? |
423 | 530 |
424 } | 531 } |
425 | |
426 class RestrictedTypeResolverVisitor extends TypeResolverVisitor { | |
427 RestrictedTypeResolverVisitor( | |
428 Library library, Source source, TypeProvider typeProvider) | |
429 : super.con1(library, source, typeProvider); | |
430 | |
431 static TypeResolverVisitor constructor( | |
432 Library library, Source source, TypeProvider typeProvider) => | |
433 new RestrictedTypeResolverVisitor(library, source, typeProvider); | |
434 | |
435 @override | |
436 Object visitVariableDeclaration(VariableDeclaration node) { | |
437 var res = super.visitVariableDeclaration(node); | |
438 | |
439 var element = node.element; | |
440 VariableDeclarationList parent = node.parent; | |
441 // only infer types if it was left blank | |
442 if (!element.type.isDynamic || parent.type != null) return res; | |
443 | |
444 // const fields and top-levels will be inferred from the initializer value | |
445 // somewhere else. | |
446 if (parent.isConst) return res; | |
447 | |
448 // If the type was omitted on a field, we can infer it from a supertype. | |
449 if (node.element is FieldElement) { | |
450 var getter = element.getter; | |
451 var type = searchTypeFor(element.enclosingElement.type, getter); | |
452 if (type != null && !type.returnType.isDynamic) { | |
453 var newType = type.returnType; | |
454 element.type = newType; | |
455 getter.returnType = newType; | |
456 if (!element.isFinal) element.setter.parameters[0].type = newType; | |
457 } | |
458 } | |
459 return res; | |
460 } | |
461 | |
462 @override | |
463 Object visitMethodDeclaration(MethodDeclaration node) { | |
464 var res = super.visitMethodDeclaration(node); | |
465 var element = node.element; | |
466 if ((element is MethodElement || element is PropertyAccessorElement) && | |
467 element.returnType.isDynamic && | |
468 node.returnType == null) { | |
469 var type = searchTypeFor(element.enclosingElement.type, element); | |
470 if (type != null && !type.returnType.isDynamic) { | |
471 element.returnType = type.returnType; | |
472 } | |
473 } | |
474 return res; | |
475 } | |
476 } | |
OLD | NEW |