OLD | NEW |
(Empty) | |
| 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 |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library analyzer.src.task.strong_mode; |
| 6 |
| 7 import 'dart:collection'; |
| 8 |
| 9 import 'package:analyzer/src/generated/ast.dart'; |
| 10 import 'package:analyzer/src/generated/element.dart'; |
| 11 import 'package:analyzer/src/generated/resolver.dart'; |
| 12 import 'package:analyzer/src/generated/utilities_dart.dart'; |
| 13 |
| 14 /** |
| 15 * Set the type of the sole parameter of the given [element] to the given [type]
. |
| 16 */ |
| 17 void setParameterType(PropertyAccessorElement element, DartType type) { |
| 18 if (element is PropertyAccessorElementImpl) { |
| 19 ParameterElement parameter = _getParameter(element); |
| 20 if (parameter is ParameterElementImpl) { |
| 21 // |
| 22 // Update the type of the parameter. |
| 23 // |
| 24 parameter.type = type; |
| 25 // |
| 26 // Update the type of the setter to reflect the new parameter type. |
| 27 // |
| 28 FunctionType functionType = element.type; |
| 29 if (functionType is FunctionTypeImpl) { |
| 30 element.type = |
| 31 new FunctionTypeImpl(element, functionType.prunedTypedefs) |
| 32 ..typeArguments = functionType.typeArguments; |
| 33 } else { |
| 34 assert(false); |
| 35 } |
| 36 } else { |
| 37 assert(false); |
| 38 } |
| 39 } else { |
| 40 throw new StateError('element is an instance of ${element.runtimeType}'); |
| 41 assert(false); |
| 42 } |
| 43 } |
| 44 |
| 45 /** |
| 46 * Set the return type of the given [element] to the given [type]. |
| 47 */ |
| 48 void setReturnType(ExecutableElement element, DartType type) { |
| 49 if (element is ExecutableElementImpl) { |
| 50 // |
| 51 // Update the return type of the element, which is stored in two places: |
| 52 // directly in the element and indirectly in the type of the element. |
| 53 // |
| 54 element.returnType = type; |
| 55 FunctionType functionType = element.type; |
| 56 if (functionType is FunctionTypeImpl) { |
| 57 element.type = new FunctionTypeImpl(element, functionType.prunedTypedefs) |
| 58 ..typeArguments = functionType.typeArguments; |
| 59 } else { |
| 60 assert(false); |
| 61 } |
| 62 } else { |
| 63 assert(false); |
| 64 } |
| 65 } |
| 66 |
| 67 /** |
| 68 * Return the element for the single parameter of the given [setter], or `null` |
| 69 * if the executable element is not a setter or does not have a single |
| 70 * parameter. |
| 71 */ |
| 72 ParameterElement _getParameter(ExecutableElement setter) { |
| 73 if (setter is PropertyAccessorElement && setter.isSetter) { |
| 74 List<ParameterElement> parameters = setter.parameters; |
| 75 if (parameters.length == 1) { |
| 76 return parameters[0]; |
| 77 } |
| 78 } |
| 79 return null; |
| 80 } |
| 81 |
| 82 /** |
| 83 * A function that returns `true` if the given [variable] passes the filter. |
| 84 */ |
| 85 typedef bool VariableFilter(VariableElement element); |
| 86 |
| 87 /** |
| 88 * An object used to infer the type of instance fields and the return types of |
| 89 * instance methods within a single compilation unit. |
| 90 */ |
| 91 class InstanceMemberInferrer { |
| 92 /** |
| 93 * The type provider used to look up types. |
| 94 */ |
| 95 final TypeProvider typeProvider; |
| 96 |
| 97 /** |
| 98 * The type system used to compute the least upper bound of types. |
| 99 */ |
| 100 TypeSystem typeSystem; |
| 101 |
| 102 /** |
| 103 * The inheritance manager used to find overridden method. |
| 104 */ |
| 105 InheritanceManager inheritanceManager; |
| 106 |
| 107 /** |
| 108 * The classes that have been visited while attempting to infer the types of |
| 109 * instance members of some base class. |
| 110 */ |
| 111 HashSet<ClassElementImpl> elementsBeingInferred = |
| 112 new HashSet<ClassElementImpl>(); |
| 113 |
| 114 /** |
| 115 * Initialize a newly create inferrer. |
| 116 */ |
| 117 InstanceMemberInferrer(this.typeProvider, {TypeSystem typeSystem}) |
| 118 : typeSystem = (typeSystem != null) ? typeSystem : new TypeSystemImpl(); |
| 119 |
| 120 /** |
| 121 * Infer type information for all of the instance members in the given |
| 122 * compilation [unit]. |
| 123 */ |
| 124 void inferCompilationUnit(CompilationUnitElement unit) { |
| 125 inheritanceManager = new InheritanceManager(unit.library); |
| 126 unit.types.forEach((ClassElement classElement) { |
| 127 try { |
| 128 _inferClass(classElement); |
| 129 } on _CycleException { |
| 130 // This is a short circuit return to prevent types that inherit from |
| 131 // types containing a circular reference from being inferred. |
| 132 } |
| 133 }); |
| 134 } |
| 135 |
| 136 /** |
| 137 * Compute the best type for the [parameter] at the given [index] that must be |
| 138 * compatible with the types of the corresponding parameters of the given |
| 139 * [overriddenMethods]. |
| 140 * |
| 141 * At the moment, this method will only return a type other than 'dynamic' if |
| 142 * the types of all of the parameters are the same. In the future we might |
| 143 * want to be smarter about it, such as by returning the least upper bound of |
| 144 * the parameter types. |
| 145 */ |
| 146 DartType _computeParameterType(ParameterElement parameter, int index, |
| 147 List<ExecutableElement> overriddenMethods) { |
| 148 DartType parameterType = null; |
| 149 int length = overriddenMethods.length; |
| 150 for (int i = 0; i < length; i++) { |
| 151 DartType type = _getTypeOfCorrespondingParameter( |
| 152 parameter, index, overriddenMethods[i]); |
| 153 if (parameterType == null) { |
| 154 parameterType = type; |
| 155 } else if (parameterType != type) { |
| 156 return typeProvider.dynamicType; |
| 157 } |
| 158 } |
| 159 return parameterType == null ? typeProvider.dynamicType : parameterType; |
| 160 } |
| 161 |
| 162 /** |
| 163 * Compute the best return type for a method that must be compatible with the |
| 164 * return types of each of the given [overriddenMethods]. |
| 165 * |
| 166 * At the moment, this method will only return a type other than 'dynamic' if |
| 167 * the return types of all of the methods are the same. In the future we might |
| 168 * want to be smarter about it. |
| 169 */ |
| 170 DartType _computeReturnType(List<ExecutableElement> overriddenMethods) { |
| 171 DartType returnType = null; |
| 172 int length = overriddenMethods.length; |
| 173 for (int i = 0; i < length; i++) { |
| 174 DartType type = _getReturnType(overriddenMethods[i]); |
| 175 if (returnType == null) { |
| 176 returnType = type; |
| 177 } else if (returnType != type) { |
| 178 return typeProvider.dynamicType; |
| 179 } |
| 180 } |
| 181 return returnType == null ? typeProvider.dynamicType : returnType; |
| 182 } |
| 183 |
| 184 DartType _getReturnType(ExecutableElement element) { |
| 185 DartType returnType = element.returnType; |
| 186 if (returnType == null) { |
| 187 return typeProvider.dynamicType; |
| 188 } |
| 189 return returnType; |
| 190 } |
| 191 |
| 192 /** |
| 193 * Given a [method], return the type of the parameter in the method that |
| 194 * corresponds to the given [parameter]. If the parameter is positional, then |
| 195 * it appears at the given [index] in its enclosing element's list of |
| 196 * parameters. |
| 197 */ |
| 198 DartType _getTypeOfCorrespondingParameter( |
| 199 ParameterElement parameter, int index, ExecutableElement method) { |
| 200 // |
| 201 // Find the corresponding parameter. |
| 202 // |
| 203 List<ParameterElement> methodParameters = method.parameters; |
| 204 ParameterElement matchingParameter = null; |
| 205 if (parameter.parameterKind == ParameterKind.NAMED) { |
| 206 // |
| 207 // If we're looking for a named parameter, only a named parameter with |
| 208 // the same name will be matched. |
| 209 // |
| 210 matchingParameter = methodParameters.lastWhere( |
| 211 (ParameterElement methodParameter) => |
| 212 methodParameter.parameterKind == ParameterKind.NAMED && |
| 213 methodParameter.name == parameter.name, |
| 214 orElse: () => null); |
| 215 } else { |
| 216 // |
| 217 // If we're looking for a positional parameter we ignore the difference |
| 218 // between required and optional parameters. |
| 219 // |
| 220 if (index < methodParameters.length) { |
| 221 matchingParameter = methodParameters[index]; |
| 222 if (matchingParameter.parameterKind == ParameterKind.NAMED) { |
| 223 matchingParameter = null; |
| 224 } |
| 225 } |
| 226 } |
| 227 // |
| 228 // Then return the type of the parameter. |
| 229 // |
| 230 return matchingParameter == null |
| 231 ? typeProvider.dynamicType |
| 232 : matchingParameter.type; |
| 233 } |
| 234 |
| 235 /** |
| 236 * Infer type information for all of the instance members in the given |
| 237 * [classElement]. |
| 238 */ |
| 239 void _inferClass(ClassElement classElement) { |
| 240 if (classElement is ClassElementImpl) { |
| 241 if (classElement.hasBeenInferred) { |
| 242 return; |
| 243 } |
| 244 if (!elementsBeingInferred.add(classElement)) { |
| 245 // We have found a circularity in the class hierarchy. For now we just |
| 246 // stop trying to infer any type information for any classes that |
| 247 // inherit from any class in the cycle. We could potentially limit the |
| 248 // algorithm to only not inferring types in the classes in the cycle, |
| 249 // but it isn't clear that the results would be significantly better. |
| 250 throw new _CycleException(); |
| 251 } |
| 252 try { |
| 253 // |
| 254 // Ensure that all of instance members in the supertypes have had types |
| 255 // inferred for them. |
| 256 // |
| 257 _inferType(classElement.supertype); |
| 258 classElement.mixins.forEach(_inferType); |
| 259 classElement.interfaces.forEach(_inferType); |
| 260 // |
| 261 // Then infer the types for the members. |
| 262 // |
| 263 classElement.fields.forEach(_inferField); |
| 264 classElement.accessors.forEach(_inferExecutable); |
| 265 classElement.methods.forEach(_inferExecutable); |
| 266 // |
| 267 // Infer initializing formal parameter types. This must happen after |
| 268 // field types are inferred. |
| 269 // |
| 270 classElement.constructors.forEach(_inferConstructorFieldFormals); |
| 271 classElement.hasBeenInferred = true; |
| 272 } finally { |
| 273 elementsBeingInferred.remove(classElement); |
| 274 } |
| 275 } |
| 276 } |
| 277 |
| 278 /** |
| 279 * If the given [fieldElement] represents a non-synthetic instance field for |
| 280 * which no type was provided, infer the type of the field. |
| 281 */ |
| 282 void _inferField(FieldElement fieldElement) { |
| 283 if (!fieldElement.isSynthetic && |
| 284 !fieldElement.isStatic && |
| 285 fieldElement.hasImplicitType) { |
| 286 // |
| 287 // First look for overridden getters with the same name as the field. |
| 288 // |
| 289 List<ExecutableElement> overriddenGetters = inheritanceManager |
| 290 .lookupOverrides(fieldElement.enclosingElement, fieldElement.name); |
| 291 DartType newType = null; |
| 292 if (overriddenGetters.isNotEmpty && _onlyGetters(overriddenGetters)) { |
| 293 newType = _computeReturnType(overriddenGetters); |
| 294 List<ExecutableElement> overriddenSetters = inheritanceManager |
| 295 .lookupOverrides( |
| 296 fieldElement.enclosingElement, fieldElement.name + '='); |
| 297 if (!_isCompatible(newType, overriddenSetters)) { |
| 298 newType = null; |
| 299 } |
| 300 } |
| 301 // |
| 302 // If there is no overridden getter or if the overridden getter's type is |
| 303 // dynamic, then we can infer the type from the initialization expression |
| 304 // without breaking subtype rules. We could potentially infer a consistent |
| 305 // return type even if the overridden getter's type was not dynamic, but |
| 306 // choose not to for simplicity. The field is required to be final to |
| 307 // prevent choosing a type that is inconsistent with assignments we cannot |
| 308 // analyze. |
| 309 // |
| 310 if (newType == null || newType.isDynamic) { |
| 311 if (fieldElement.initializer != null && |
| 312 (fieldElement.isFinal || overriddenGetters.isEmpty)) { |
| 313 newType = fieldElement.initializer.returnType; |
| 314 } |
| 315 } |
| 316 if (newType == null || newType.isBottom) { |
| 317 newType = typeProvider.dynamicType; |
| 318 } |
| 319 (fieldElement as FieldElementImpl).type = newType; |
| 320 setReturnType(fieldElement.getter, newType); |
| 321 if (!fieldElement.isFinal && !fieldElement.isConst) { |
| 322 setParameterType(fieldElement.setter, newType); |
| 323 } |
| 324 } |
| 325 } |
| 326 |
| 327 /** |
| 328 * If the given [element] represents a non-synthetic instance method, |
| 329 * getter or setter, infer the return type and any parameter type(s) where |
| 330 * they were not provided. |
| 331 */ |
| 332 void _inferExecutable(ExecutableElement element) { |
| 333 if (element.isSynthetic || element.isStatic) { |
| 334 return; |
| 335 } |
| 336 List<ExecutableElement> overriddenMethods = null; |
| 337 // |
| 338 // Infer the return type. |
| 339 // |
| 340 if (element.hasImplicitReturnType) { |
| 341 overriddenMethods = inheritanceManager.lookupOverrides( |
| 342 element.enclosingElement, element.name); |
| 343 if (overriddenMethods.isEmpty || |
| 344 !_allSameElementKind(element, overriddenMethods)) { |
| 345 return; |
| 346 } |
| 347 setReturnType(element, _computeReturnType(overriddenMethods)); |
| 348 if (element is PropertyAccessorElement) { |
| 349 _updateSyntheticVariableType(element); |
| 350 } |
| 351 } |
| 352 // |
| 353 // Infer the parameter types. |
| 354 // |
| 355 List<ParameterElement> parameters = element.parameters; |
| 356 int length = parameters.length; |
| 357 for (int i = 0; i < length; ++i) { |
| 358 ParameterElement parameter = parameters[i]; |
| 359 if (parameter is ParameterElementImpl && parameter.hasImplicitType) { |
| 360 if (overriddenMethods == null) { |
| 361 overriddenMethods = inheritanceManager.lookupOverrides( |
| 362 element.enclosingElement, element.name); |
| 363 } |
| 364 if (overriddenMethods.isEmpty || |
| 365 !_allSameElementKind(element, overriddenMethods)) { |
| 366 return; |
| 367 } |
| 368 parameter.type = _computeParameterType(parameter, i, overriddenMethods); |
| 369 if (element is PropertyAccessorElement) { |
| 370 _updateSyntheticVariableType(element); |
| 371 } |
| 372 } |
| 373 } |
| 374 } |
| 375 |
| 376 /** |
| 377 * If the given [element] is a non-synthetic getter or setter, update its |
| 378 * synthetic variable's type to match the getter's return type, or if no |
| 379 * corresponding getter exists, use the setter's parameter type. |
| 380 * |
| 381 * In general, the type of the synthetic variable should not be used, because |
| 382 * getters and setters are independent methods. But this logic matches what |
| 383 * `TypeResolverVisitor.visitMethodDeclaration` would fill in there. |
| 384 */ |
| 385 void _updateSyntheticVariableType(PropertyAccessorElement element) { |
| 386 assert(!element.isSynthetic); |
| 387 PropertyAccessorElement getter = element; |
| 388 if (element.isSetter) { |
| 389 // See if we can find any getter. |
| 390 getter = element.correspondingGetter; |
| 391 } |
| 392 DartType newType; |
| 393 if (getter != null) { |
| 394 newType = getter.returnType; |
| 395 } else if (element.isSetter && element.parameters.isNotEmpty) { |
| 396 newType = element.parameters[0].type; |
| 397 } |
| 398 if (newType != null) { |
| 399 (element.variable as VariableElementImpl).type = newType; |
| 400 } |
| 401 } |
| 402 |
| 403 /** |
| 404 * Infer type information for all of the instance members in the given |
| 405 * interface [type]. |
| 406 */ |
| 407 void _inferType(InterfaceType type) { |
| 408 if (type != null) { |
| 409 ClassElement element = type.element; |
| 410 if (element != null) { |
| 411 _inferClass(element); |
| 412 } |
| 413 } |
| 414 } |
| 415 |
| 416 /** |
| 417 * Return `true` if the given [type] is compatible with the argument types of |
| 418 * all of the given [setters]. |
| 419 */ |
| 420 bool _isCompatible(DartType type, List<ExecutableElement> setters) { |
| 421 for (ExecutableElement setter in setters) { |
| 422 ParameterElement parameter = _getParameter(setter); |
| 423 if (parameter != null && !typeSystem.isSubtypeOf(parameter.type, type)) { |
| 424 return false; |
| 425 } |
| 426 } |
| 427 return true; |
| 428 } |
| 429 |
| 430 /** |
| 431 * Return `true` if the list of [elements] contains only getters. |
| 432 */ |
| 433 bool _onlyGetters(List<ExecutableElement> elements) { |
| 434 for (ExecutableElement element in elements) { |
| 435 if (!(element is PropertyAccessorElement && element.isGetter)) { |
| 436 return false; |
| 437 } |
| 438 } |
| 439 return true; |
| 440 } |
| 441 |
| 442 /** |
| 443 * Return `true` if the list of [elements] contains only methods. |
| 444 */ |
| 445 bool _allSameElementKind( |
| 446 ExecutableElement element, List<ExecutableElement> elements) { |
| 447 return elements.every((e) => e.kind == element.kind); |
| 448 } |
| 449 |
| 450 void _inferConstructorFieldFormals(ConstructorElement element) { |
| 451 for (ParameterElement p in element.parameters) { |
| 452 if (p is FieldFormalParameterElement) { |
| 453 _inferFieldFormalParameter(p); |
| 454 } |
| 455 } |
| 456 } |
| 457 |
| 458 void _inferFieldFormalParameter(FieldFormalParameterElement element) { |
| 459 FieldElement field = element.field; |
| 460 if (field != null && element.hasImplicitType) { |
| 461 (element as FieldFormalParameterElementImpl).type = field.type; |
| 462 } |
| 463 } |
| 464 } |
| 465 |
| 466 /** |
| 467 * A visitor that will gather all of the variables referenced within a given |
| 468 * AST structure. The collection can be restricted to contain only those |
| 469 * variables that pass a specified filter. |
| 470 */ |
| 471 class VariableGatherer extends RecursiveAstVisitor { |
| 472 /** |
| 473 * The filter used to limit which variables are gathered, or `null` if no |
| 474 * filtering is to be performed. |
| 475 */ |
| 476 final VariableFilter filter; |
| 477 |
| 478 /** |
| 479 * The variables that were found. |
| 480 */ |
| 481 final Set<VariableElement> results = new HashSet<VariableElement>(); |
| 482 |
| 483 /** |
| 484 * Initialize a newly created gatherer to gather all of the variables that |
| 485 * pass the given [filter] (or all variables if no filter is provided). |
| 486 */ |
| 487 VariableGatherer([this.filter = null]); |
| 488 |
| 489 @override |
| 490 void visitSimpleIdentifier(SimpleIdentifier node) { |
| 491 if (!node.inDeclarationContext()) { |
| 492 Element element = node.staticElement; |
| 493 if (element is PropertyAccessorElement && element.isSynthetic) { |
| 494 element = (element as PropertyAccessorElement).variable; |
| 495 } |
| 496 if (element is VariableElement && (filter == null || filter(element))) { |
| 497 results.add(element); |
| 498 } |
| 499 } |
| 500 } |
| 501 } |
| 502 |
| 503 /** |
| 504 * A class of exception that is not used anywhere else. |
| 505 */ |
| 506 class _CycleException implements Exception {} |
OLD | NEW |