Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(66)

Side by Side Diff: pkg/analyzer/lib/src/task/strong/checker.dart

Issue 1507933002: Refactor strong mode to remove duplicate TypeRules (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
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 // TODO(jmesserly): this was ported from package:dev_compiler, and needs to be 5 // TODO(jmesserly): this was ported from package:dev_compiler, and needs to be
6 // refactored to fit into analyzer. 6 // refactored to fit into analyzer.
7 library analyzer.src.task.strong.checker; 7 library analyzer.src.task.strong.checker;
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/resolver.dart' show TypeProvider;
12 import 'package:analyzer/src/generated/scanner.dart' show Token, TokenType; 13 import 'package:analyzer/src/generated/scanner.dart' show Token, TokenType;
14 import 'package:analyzer/src/generated/type_system.dart';
15 import 'package:analyzer/src/task/strong/rules.dart';
13 16
14 import 'info.dart'; 17 import 'info.dart';
15 import 'rules.dart';
16 18
17 /// Checks for overriding declarations of fields and methods. This is used to 19 /// Checks for overriding declarations of fields and methods. This is used to
18 /// check overrides between classes and superclasses, interfaces, and mixin 20 /// check overrides between classes and superclasses, interfaces, and mixin
19 /// applications. 21 /// applications.
20 class _OverrideChecker { 22 class _OverrideChecker {
21 bool _failure = false; 23 bool _failure = false;
22 final TypeRules _rules; 24 final StrongTypeSystemImpl rules;
23 final AnalysisErrorListener _reporter; 25 final AnalysisErrorListener _reporter;
24 26
25 _OverrideChecker(this._rules, this._reporter); 27 _OverrideChecker(this.rules, this._reporter);
26 28
27 void check(ClassDeclaration node) { 29 void check(ClassDeclaration node) {
28 if (node.element.type.isObject) return; 30 if (node.element.type.isObject) return;
29 _checkSuperOverrides(node); 31 _checkSuperOverrides(node);
30 _checkMixinApplicationOverrides(node); 32 _checkMixinApplicationOverrides(node);
31 _checkAllInterfaceOverrides(node); 33 _checkAllInterfaceOverrides(node);
32 } 34 }
33 35
34 /// Check overrides from mixin applications themselves. For example, in: 36 /// Check overrides from mixin applications themselves. For example, in:
35 /// 37 ///
(...skipping 256 matching lines...) Expand 10 before | Expand all | Expand 10 after
292 /// class A extends B with C implements E { ... } 294 /// class A extends B with C implements E { ... }
293 /// ^ 295 /// ^
294 /// 296 ///
295 /// When checking for overrides from a type and it's super types, [node] is 297 /// When checking for overrides from a type and it's super types, [node] is
296 /// the AST node that defines [element]. This is used to determine whether the 298 /// the AST node that defines [element]. This is used to determine whether the
297 /// type of the element could be inferred from the types in the super classes. 299 /// type of the element could be inferred from the types in the super classes.
298 bool _checkSingleOverride(ExecutableElement element, InterfaceType type, 300 bool _checkSingleOverride(ExecutableElement element, InterfaceType type,
299 AstNode node, AstNode errorLocation, bool isSubclass) { 301 AstNode node, AstNode errorLocation, bool isSubclass) {
300 assert(!element.isStatic); 302 assert(!element.isStatic);
301 303
302 FunctionType subType = _rules.elementType(element); 304 FunctionType subType = _elementType(element);
303 // TODO(vsm): Test for generic 305 // TODO(vsm): Test for generic
304 FunctionType baseType = _getMemberType(type, element); 306 FunctionType baseType = _getMemberType(type, element);
305 if (baseType == null) return false; 307 if (baseType == null) return false;
306 308
307 if (isSubclass && element is PropertyAccessorElement) { 309 if (isSubclass && element is PropertyAccessorElement) {
308 // Disallow any overriding if the base class defines this member 310 // Disallow any overriding if the base class defines this member
309 // as a field. We effectively treat fields as final / non-virtual. 311 // as a field. We effectively treat fields as final / non-virtual.
310 PropertyInducingElement field = _getMemberField(type, element); 312 PropertyInducingElement field = _getMemberField(type, element);
311 if (field != null) { 313 if (field != null) {
312 _recordMessage(new InvalidFieldOverride( 314 _recordMessage(new InvalidFieldOverride(
313 errorLocation, element, type, subType, baseType)); 315 errorLocation, element, type, subType, baseType));
314 } 316 }
315 } 317 }
316 if (!_rules.isAssignable(subType, baseType)) { 318 if (!rules.isSubtypeOf(subType, baseType)) {
317 // See whether non-assignable cases fit one of our common patterns: 319 // See whether non-subtype cases fit one of our common patterns:
318 // 320 //
319 // Common pattern 1: Inferable return type (on getters and methods) 321 // Common pattern 1: Inferable return type (on getters and methods)
320 // class A { 322 // class A {
321 // int get foo => ...; 323 // int get foo => ...;
322 // String toString() { ... } 324 // String toString() { ... }
323 // } 325 // }
324 // class B extends A { 326 // class B extends A {
325 // get foo => e; // no type specified. 327 // get foo => e; // no type specified.
326 // toString() { ... } // no return type specified. 328 // toString() { ... } // no return type specified.
327 // } 329 // }
328 _recordMessage(new InvalidMethodOverride( 330 _recordMessage(new InvalidMethodOverride(
329 errorLocation, element, type, subType, baseType)); 331 errorLocation, element, type, subType, baseType));
330 } 332 }
331 return true; 333 return true;
332 } 334 }
333 335
334 void _recordMessage(StaticInfo info) { 336 void _recordMessage(StaticInfo info) {
335 if (info == null) return; 337 if (info == null) return;
336 var error = info.toAnalysisError(); 338 var error = info.toAnalysisError();
337 if (error.errorCode.errorSeverity == ErrorSeverity.ERROR) _failure = true; 339 if (error.errorCode.errorSeverity == ErrorSeverity.ERROR) _failure = true;
338 _reporter.onError(error); 340 _reporter.onError(error);
339 } 341 }
340 } 342 }
341 343
342 /// Checks the body of functions and properties. 344 /// Checks the body of functions and properties.
343 class CodeChecker extends RecursiveAstVisitor { 345 class CodeChecker extends RecursiveAstVisitor {
344 final TypeRules rules; 346 final StrongTypeSystemImpl rules;
347 final TypeProvider typeProvider;
345 final AnalysisErrorListener reporter; 348 final AnalysisErrorListener reporter;
346 final _OverrideChecker _overrideChecker; 349 final _OverrideChecker _overrideChecker;
350 final DownwardsInference inferrer;
347 final bool _hints; 351 final bool _hints;
348 352
349 bool _failure = false; 353 bool _failure = false;
350 bool get failure => _failure || _overrideChecker._failure; 354 bool get failure => _failure || _overrideChecker._failure;
351 355
352 void reset() { 356 void reset() {
353 _failure = false; 357 _failure = false;
354 _overrideChecker._failure = false; 358 _overrideChecker._failure = false;
355 } 359 }
356 360
357 CodeChecker(TypeRules rules, AnalysisErrorListener reporter, 361 CodeChecker(this.typeProvider, StrongTypeSystemImpl rules, AnalysisErrorListen er reporter,
358 {bool hints: false}) 362 {bool hints: false})
359 : rules = rules, 363 : rules = rules,
360 reporter = reporter, 364 reporter = reporter,
361 _hints = hints, 365 _hints = hints,
362 _overrideChecker = new _OverrideChecker(rules, reporter); 366 _overrideChecker = new _OverrideChecker(rules, reporter),
367 inferrer = new DownwardsInference(rules);
363 368
364 @override 369 @override
365 void visitComment(Comment node) { 370 void visitComment(Comment node) {
366 // skip, no need to do typechecking inside comments (they may contain 371 // skip, no need to do typechecking inside comments (they may contain
367 // comment references which would require resolution). 372 // comment references which would require resolution).
368 } 373 }
369 374
370 @override 375 @override
371 void visitClassDeclaration(ClassDeclaration node) { 376 void visitClassDeclaration(ClassDeclaration node) {
372 _overrideChecker.check(node); 377 _overrideChecker.check(node);
(...skipping 23 matching lines...) Expand all
396 if (node is SuperConstructorInvocation) { 401 if (node is SuperConstructorInvocation) {
397 _recordMessage(new InvalidSuperInvocation(node)); 402 _recordMessage(new InvalidSuperInvocation(node));
398 } 403 }
399 } 404 }
400 } 405 }
401 406
402 @override 407 @override
403 void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { 408 void visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
404 var field = node.fieldName; 409 var field = node.fieldName;
405 var element = field.staticElement; 410 var element = field.staticElement;
406 DartType staticType = rules.elementType(element); 411 DartType staticType = _elementType(element);
407 checkAssignment(node.expression, staticType); 412 checkAssignment(node.expression, staticType);
408 node.visitChildren(this); 413 node.visitChildren(this);
409 } 414 }
410 415
411 @override 416 @override
412 void visitForEachStatement(ForEachStatement node) { 417 void visitForEachStatement(ForEachStatement node) {
413 // Check that the expression is an Iterable. 418 // Check that the expression is an Iterable.
414 var expr = node.iterable; 419 var expr = node.iterable;
415 var iterableType = node.awaitKeyword != null 420 var iterableType = node.awaitKeyword != null
416 ? rules.provider.streamType 421 ? typeProvider.streamType
417 : rules.provider.iterableType; 422 : typeProvider.iterableType;
418 var loopVariable = node.identifier != null 423 var loopVariable = node.identifier != null
419 ? node.identifier 424 ? node.identifier
420 : node.loopVariable?.identifier; 425 : node.loopVariable?.identifier;
421 if (loopVariable != null) { 426 if (loopVariable != null) {
422 var iteratorType = loopVariable.staticType; 427 var iteratorType = loopVariable.staticType;
423 var checkedType = iterableType.substitute4([iteratorType]); 428 var checkedType = iterableType.substitute4([iteratorType]);
424 checkAssignment(expr, checkedType); 429 checkAssignment(expr, checkedType);
425 } 430 }
426 node.visitChildren(this); 431 node.visitChildren(this);
427 } 432 }
(...skipping 28 matching lines...) Expand all
456 void visitSwitchStatement(SwitchStatement node) { 461 void visitSwitchStatement(SwitchStatement node) {
457 // SwitchStatement defines a boolean conversion to check the result of the 462 // SwitchStatement defines a boolean conversion to check the result of the
458 // case value == the switch value, but in dev_compiler we require a boolean 463 // case value == the switch value, but in dev_compiler we require a boolean
459 // return type from an overridden == operator (because Object.==), so 464 // return type from an overridden == operator (because Object.==), so
460 // checking in SwitchStatement shouldn't be necessary. 465 // checking in SwitchStatement shouldn't be necessary.
461 node.visitChildren(this); 466 node.visitChildren(this);
462 } 467 }
463 468
464 @override 469 @override
465 void visitListLiteral(ListLiteral node) { 470 void visitListLiteral(ListLiteral node) {
466 var type = rules.provider.dynamicType; 471 var type = DynamicTypeImpl.instance;
467 if (node.typeArguments != null) { 472 if (node.typeArguments != null) {
468 var targs = node.typeArguments.arguments; 473 var targs = node.typeArguments.arguments;
469 if (targs.length > 0) type = targs[0].type; 474 if (targs.length > 0) type = targs[0].type;
470 } else if (node.staticType is InterfaceType) { 475 } else if (node.staticType is InterfaceType) {
471 InterfaceType listT = node.staticType; 476 InterfaceType listT = node.staticType;
472 var targs = listT.typeArguments; 477 var targs = listT.typeArguments;
473 if (targs != null && targs.length > 0) type = targs[0]; 478 if (targs != null && targs.length > 0) type = targs[0];
474 } 479 }
475 var elements = node.elements; 480 var elements = node.elements;
476 for (int i = 0; i < elements.length; i++) { 481 for (int i = 0; i < elements.length; i++) {
477 checkArgument(elements[i], type); 482 checkArgument(elements[i], type);
478 } 483 }
479 super.visitListLiteral(node); 484 super.visitListLiteral(node);
480 } 485 }
481 486
482 @override 487 @override
483 void visitMapLiteral(MapLiteral node) { 488 void visitMapLiteral(MapLiteral node) {
484 var ktype = rules.provider.dynamicType; 489 var ktype = DynamicTypeImpl.instance;
485 var vtype = rules.provider.dynamicType; 490 var vtype = DynamicTypeImpl.instance;
486 if (node.typeArguments != null) { 491 if (node.typeArguments != null) {
487 var targs = node.typeArguments.arguments; 492 var targs = node.typeArguments.arguments;
488 if (targs.length > 0) ktype = targs[0].type; 493 if (targs.length > 0) ktype = targs[0].type;
489 if (targs.length > 1) vtype = targs[1].type; 494 if (targs.length > 1) vtype = targs[1].type;
490 } else if (node.staticType is InterfaceType) { 495 } else if (node.staticType is InterfaceType) {
491 InterfaceType mapT = node.staticType; 496 InterfaceType mapT = node.staticType;
492 var targs = mapT.typeArguments; 497 var targs = mapT.typeArguments;
493 if (targs != null) { 498 if (targs != null) {
494 if (targs.length > 0) ktype = targs[0]; 499 if (targs.length > 0) ktype = targs[0];
495 if (targs.length > 1) vtype = targs[1]; 500 if (targs.length > 1) vtype = targs[1];
(...skipping 18 matching lines...) Expand all
514 if (element == null) { 519 if (element == null) {
515 if (type.parameters.length < len) { 520 if (type.parameters.length < len) {
516 // We found an argument mismatch, the analyzer will report this too, 521 // We found an argument mismatch, the analyzer will report this too,
517 // so no need to insert an error for this here. 522 // so no need to insert an error for this here.
518 continue; 523 continue;
519 } 524 }
520 element = type.parameters[i]; 525 element = type.parameters[i];
521 // TODO(vsm): When can this happen? 526 // TODO(vsm): When can this happen?
522 assert(element != null); 527 assert(element != null);
523 } 528 }
524 DartType expectedType = rules.elementType(element); 529 DartType expectedType = _elementType(element);
525 if (expectedType == null) expectedType = rules.provider.dynamicType; 530 if (expectedType == null) expectedType = DynamicTypeImpl.instance;
526 checkArgument(arg, expectedType); 531 checkArgument(arg, expectedType);
527 } 532 }
528 } 533 }
529 534
530 void checkArgument(Expression arg, DartType expectedType) { 535 void checkArgument(Expression arg, DartType expectedType) {
531 // Preserve named argument structure, so their immediate parent is the 536 // Preserve named argument structure, so their immediate parent is the
532 // method invocation. 537 // method invocation.
533 if (arg is NamedExpression) { 538 if (arg is NamedExpression) {
534 arg = (arg as NamedExpression).expression; 539 arg = (arg as NamedExpression).expression;
535 } 540 }
536 checkAssignment(arg, expectedType); 541 checkAssignment(arg, expectedType);
537 } 542 }
538 543
539 void checkFunctionApplication( 544 void checkFunctionApplication(
540 Expression node, Expression f, ArgumentList list) { 545 Expression node, Expression f, ArgumentList list) {
541 if (rules.isDynamicCall(f)) { 546 if (_isDynamicCall(f)) {
542 // If f is Function and this is a method invocation, we should have 547 // If f is Function and this is a method invocation, we should have
543 // gotten an analyzer error, so no need to issue another error. 548 // gotten an analyzer error, so no need to issue another error.
544 _recordDynamicInvoke(node, f); 549 _recordDynamicInvoke(node, f);
545 } else { 550 } else {
546 checkArgumentList(list, rules.getTypeAsCaller(f)); 551 checkArgumentList(list, _getTypeAsCaller(f));
547 } 552 }
548 } 553 }
549 554
550 @override 555 @override
551 visitMethodInvocation(MethodInvocation node) { 556 visitMethodInvocation(MethodInvocation node) {
552 var target = node.realTarget; 557 var target = node.realTarget;
553 if (rules.isDynamicTarget(target) && 558 if (_isDynamicTarget(target) &&
554 !_isObjectMethod(node, node.methodName)) { 559 !_isObjectMethod(node, node.methodName)) {
555 _recordDynamicInvoke(node, target); 560 _recordDynamicInvoke(node, target);
556 561
557 // Mark the tear-off as being dynamic, too. This lets us distinguish 562 // Mark the tear-off as being dynamic, too. This lets us distinguish
558 // cases like: 563 // cases like:
559 // 564 //
560 // dynamic d; 565 // dynamic d;
561 // d.someMethod(...); // the whole method call must be a dynamic send. 566 // d.someMethod(...); // the whole method call must be a dynamic send.
562 // 567 //
563 // ... from case like: 568 // ... from case like:
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
599 if (element != null) { 604 if (element != null) {
600 var type = node.staticElement.type; 605 var type = node.staticElement.type;
601 checkArgumentList(node.argumentList, type); 606 checkArgumentList(node.argumentList, type);
602 } 607 }
603 node.visitChildren(this); 608 node.visitChildren(this);
604 } 609 }
605 610
606 void _checkReturnOrYield(Expression expression, AstNode node, 611 void _checkReturnOrYield(Expression expression, AstNode node,
607 {bool yieldStar: false}) { 612 {bool yieldStar: false}) {
608 var body = node.getAncestor((n) => n is FunctionBody); 613 var body = node.getAncestor((n) => n is FunctionBody);
609 var type = rules.getExpectedReturnType(body, yieldStar: yieldStar); 614 var type = _getExpectedReturnType(body, yieldStar: yieldStar);
610 if (type == null) { 615 if (type == null) {
611 // We have a type mismatch: the async/async*/sync* modifier does 616 // We have a type mismatch: the async/async*/sync* modifier does
612 // not match the return or yield type. We should have already gotten an 617 // not match the return or yield type. We should have already gotten an
613 // analyzer error in this case. 618 // analyzer error in this case.
614 return; 619 return;
615 } 620 }
616 InterfaceType futureType = rules.provider.futureType; 621 InterfaceType futureType = typeProvider.futureType;
617 DartType actualType = expression.staticType; 622 DartType actualType = expression.staticType;
618 if (body.isAsynchronous && 623 if (body.isAsynchronous &&
619 !body.isGenerator && 624 !body.isGenerator &&
620 actualType is InterfaceType && 625 actualType is InterfaceType &&
621 actualType.element == futureType.element) { 626 actualType.element == futureType.element) {
622 type = futureType.substitute4([type]); 627 type = futureType.substitute4([type]);
623 } 628 }
624 // TODO(vsm): Enforce void or dynamic (to void?) when expression is null. 629 // TODO(vsm): Enforce void or dynamic (to void?) when expression is null.
625 if (expression != null) checkAssignment(expression, type); 630 if (expression != null) checkAssignment(expression, type);
626 } 631 }
627 632
633 /// Gets the expected return type of the given function [body], either from
634 /// a normal return/yield, or from a yield*.
635 DartType _getExpectedReturnType(FunctionBody body, {bool yieldStar: false}) {
636 FunctionType functionType;
637 var parent = body.parent;
638 if (parent is Declaration) {
639 functionType = _elementType(parent.element);
640 } else {
641 assert(parent is FunctionExpression);
642 functionType = parent.staticType ?? DynamicTypeImpl.instance;
643 }
644
645 var type = functionType.returnType;
646
647 InterfaceType expectedType = null;
648 if (body.isAsynchronous) {
649 if (body.isGenerator) {
650 // Stream<T> -> T
651 expectedType = typeProvider.streamType;
652 } else {
653 // Future<T> -> T
654 // TODO(vsm): Revisit with issue #228.
655 expectedType = typeProvider.futureType;
656 }
657 } else {
658 if (body.isGenerator) {
659 // Iterable<T> -> T
660 expectedType = typeProvider.iterableType;
661 } else {
662 // T -> T
663 return type;
664 }
665 }
666 if (yieldStar) {
667 if (type.isDynamic) {
668 // Ensure it's at least a Stream / Iterable.
669 return expectedType.substitute4([typeProvider.dynamicType]);
670 } else {
671 // Analyzer will provide a separate error if expected type
672 // is not compatible with type.
673 return type;
674 }
675 }
676 if (type.isDynamic) {
677 return type;
678 } else if (type is InterfaceType && type.element == expectedType.element) {
679 return type.typeArguments[0];
680 } else {
681 // Malformed type - fallback on analyzer error.
682 return null;
683 }
684 }
685
628 @override 686 @override
629 void visitExpressionFunctionBody(ExpressionFunctionBody node) { 687 void visitExpressionFunctionBody(ExpressionFunctionBody node) {
630 _checkReturnOrYield(node.expression, node); 688 _checkReturnOrYield(node.expression, node);
631 node.visitChildren(this); 689 node.visitChildren(this);
632 } 690 }
633 691
634 @override 692 @override
635 void visitReturnStatement(ReturnStatement node) { 693 void visitReturnStatement(ReturnStatement node) {
636 _checkReturnOrYield(node.expression, node); 694 _checkReturnOrYield(node.expression, node);
637 node.visitChildren(this); 695 node.visitChildren(this);
638 } 696 }
639 697
640 @override 698 @override
641 void visitYieldStatement(YieldStatement node) { 699 void visitYieldStatement(YieldStatement node) {
642 _checkReturnOrYield(node.expression, node, yieldStar: node.star != null); 700 _checkReturnOrYield(node.expression, node, yieldStar: node.star != null);
643 node.visitChildren(this); 701 node.visitChildren(this);
644 } 702 }
645 703
646 void _checkFieldAccess(AstNode node, AstNode target, SimpleIdentifier field) { 704 void _checkFieldAccess(AstNode node, AstNode target, SimpleIdentifier field) {
647 if ((rules.isDynamicTarget(target) || field.staticElement == null) && 705 if ((_isDynamicTarget(target) || field.staticElement == null) &&
648 !_isObjectProperty(target, field)) { 706 !_isObjectProperty(target, field)) {
649 _recordDynamicInvoke(node, target); 707 _recordDynamicInvoke(node, target);
650 } 708 }
651 node.visitChildren(this); 709 node.visitChildren(this);
652 } 710 }
653 711
654 @override 712 @override
655 void visitPropertyAccess(PropertyAccess node) { 713 void visitPropertyAccess(PropertyAccess node) {
656 _checkFieldAccess(node, node.realTarget, node.propertyName); 714 _checkFieldAccess(node, node.realTarget, node.propertyName);
657 } 715 }
658 716
659 @override 717 @override
660 void visitPrefixedIdentifier(PrefixedIdentifier node) { 718 void visitPrefixedIdentifier(PrefixedIdentifier node) {
661 _checkFieldAccess(node, node.prefix, node.identifier); 719 _checkFieldAccess(node, node.prefix, node.identifier);
662 } 720 }
663 721
664 @override 722 @override
665 void visitDefaultFormalParameter(DefaultFormalParameter node) { 723 void visitDefaultFormalParameter(DefaultFormalParameter node) {
666 // Check that defaults have the proper subtype. 724 // Check that defaults have the proper subtype.
667 var parameter = node.parameter; 725 var parameter = node.parameter;
668 var parameterType = rules.elementType(parameter.element); 726 var parameterType = _elementType(parameter.element);
669 assert(parameterType != null); 727 assert(parameterType != null);
670 var defaultValue = node.defaultValue; 728 var defaultValue = node.defaultValue;
671 if (defaultValue != null) { 729 if (defaultValue != null) {
672 checkAssignment(defaultValue, parameterType); 730 checkAssignment(defaultValue, parameterType);
673 } 731 }
674 732
675 node.visitChildren(this); 733 node.visitChildren(this);
676 } 734 }
677 735
678 @override 736 @override
679 void visitFieldFormalParameter(FieldFormalParameter node) { 737 void visitFieldFormalParameter(FieldFormalParameter node) {
680 var element = node.element; 738 var element = node.element;
681 var typeName = node.type; 739 var typeName = node.type;
682 if (typeName != null) { 740 if (typeName != null) {
683 var type = rules.elementType(element); 741 var type = _elementType(element);
684 var fieldElement = 742 var fieldElement =
685 node.identifier.staticElement as FieldFormalParameterElement; 743 node.identifier.staticElement as FieldFormalParameterElement;
686 var fieldType = rules.elementType(fieldElement.field); 744 var fieldType = _elementType(fieldElement.field);
687 if (!rules.isSubTypeOf(type, fieldType)) { 745 if (!rules.isSubtypeOf(type, fieldType)) {
688 var staticInfo = 746 var staticInfo =
689 new InvalidParameterDeclaration(rules, node, fieldType); 747 new InvalidParameterDeclaration(rules, node, fieldType);
690 _recordMessage(staticInfo); 748 _recordMessage(staticInfo);
691 } 749 }
692 } 750 }
693 node.visitChildren(this); 751 node.visitChildren(this);
694 } 752 }
695 753
696 @override 754 @override
697 void visitInstanceCreationExpression(InstanceCreationExpression node) { 755 void visitInstanceCreationExpression(InstanceCreationExpression node) {
698 var arguments = node.argumentList; 756 var arguments = node.argumentList;
699 var element = node.staticElement; 757 var element = node.staticElement;
700 if (element != null) { 758 if (element != null) {
701 var type = rules.elementType(node.staticElement); 759 var type = _elementType(node.staticElement);
702 checkArgumentList(arguments, type); 760 checkArgumentList(arguments, type);
703 } 761 }
704 node.visitChildren(this); 762 node.visitChildren(this);
705 } 763 }
706 764
707 @override 765 @override
708 void visitVariableDeclarationList(VariableDeclarationList node) { 766 void visitVariableDeclarationList(VariableDeclarationList node) {
709 TypeName type = node.type; 767 TypeName type = node.type;
710 if (type == null) { 768 if (type == null) {
711 // No checks are needed when the type is var. Although internally the 769 // No checks are needed when the type is var. Although internally the
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
758 void visitPostfixExpression(PostfixExpression node) { 816 void visitPostfixExpression(PostfixExpression node) {
759 _checkUnary(node); 817 _checkUnary(node);
760 node.visitChildren(this); 818 node.visitChildren(this);
761 } 819 }
762 820
763 void _checkUnary(/*PrefixExpression|PostfixExpression*/ node) { 821 void _checkUnary(/*PrefixExpression|PostfixExpression*/ node) {
764 var op = node.operator; 822 var op = node.operator;
765 if (op.isUserDefinableOperator || 823 if (op.isUserDefinableOperator ||
766 op.type == TokenType.PLUS_PLUS || 824 op.type == TokenType.PLUS_PLUS ||
767 op.type == TokenType.MINUS_MINUS) { 825 op.type == TokenType.MINUS_MINUS) {
768 if (rules.isDynamicTarget(node.operand)) { 826 if (_isDynamicTarget(node.operand)) {
769 _recordDynamicInvoke(node, node.operand); 827 _recordDynamicInvoke(node, node.operand);
770 } 828 }
771 // For ++ and --, even if it is not dynamic, we still need to check 829 // For ++ and --, even if it is not dynamic, we still need to check
772 // that the user defined method accepts an `int` as the RHS. 830 // that the user defined method accepts an `int` as the RHS.
773 // We assume Analyzer has done this already. 831 // We assume Analyzer has done this already.
774 } 832 }
775 } 833 }
776 834
777 @override 835 @override
778 void visitBinaryExpression(BinaryExpression node) { 836 void visitBinaryExpression(BinaryExpression node) {
779 var op = node.operator; 837 var op = node.operator;
780 if (op.isUserDefinableOperator) { 838 if (op.isUserDefinableOperator) {
781 if (rules.isDynamicTarget(node.leftOperand)) { 839 if (_isDynamicTarget(node.leftOperand)) {
782 // Dynamic invocation 840 // Dynamic invocation
783 // TODO(vsm): Move this logic to the resolver? 841 // TODO(vsm): Move this logic to the resolver?
784 if (op.type != TokenType.EQ_EQ && op.type != TokenType.BANG_EQ) { 842 if (op.type != TokenType.EQ_EQ && op.type != TokenType.BANG_EQ) {
785 _recordDynamicInvoke(node, node.leftOperand); 843 _recordDynamicInvoke(node, node.leftOperand);
786 } 844 }
787 } else { 845 } else {
788 var element = node.staticElement; 846 var element = node.staticElement;
789 // Method invocation. 847 // Method invocation.
790 if (element is MethodElement) { 848 if (element is MethodElement) {
791 var type = element.type; 849 var type = element.type;
(...skipping 27 matching lines...) Expand all
819 877
820 @override 878 @override
821 void visitConditionalExpression(ConditionalExpression node) { 879 void visitConditionalExpression(ConditionalExpression node) {
822 checkBoolean(node.condition); 880 checkBoolean(node.condition);
823 node.visitChildren(this); 881 node.visitChildren(this);
824 } 882 }
825 883
826 @override 884 @override
827 void visitIndexExpression(IndexExpression node) { 885 void visitIndexExpression(IndexExpression node) {
828 var target = node.realTarget; 886 var target = node.realTarget;
829 if (rules.isDynamicTarget(target)) { 887 if (_isDynamicTarget(target)) {
830 _recordDynamicInvoke(node, target); 888 _recordDynamicInvoke(node, target);
831 } else { 889 } else {
832 var element = node.staticElement; 890 var element = node.staticElement;
833 if (element is MethodElement) { 891 if (element is MethodElement) {
834 var type = element.type; 892 var type = element.type;
835 // Analyzer should enforce number of parameter types, but check in 893 // Analyzer should enforce number of parameter types, but check in
836 // case we have erroneous input. 894 // case we have erroneous input.
837 if (type.normalParameterTypes.isNotEmpty) { 895 if (type.normalParameterTypes.isNotEmpty) {
838 checkArgument(node.index, type.normalParameterTypes[0]); 896 checkArgument(node.index, type.normalParameterTypes[0]);
839 } 897 }
840 } else { 898 } else {
841 // TODO(vsm): Assert that the analyzer found an error here? 899 // TODO(vsm): Assert that the analyzer found an error here?
842 } 900 }
843 } 901 }
844 node.visitChildren(this); 902 node.visitChildren(this);
845 } 903 }
846 904
847 DartType getType(TypeName name) { 905 DartType getType(TypeName name) {
848 return (name == null) ? rules.provider.dynamicType : name.type; 906 return (name == null) ? DynamicTypeImpl.instance : name.type;
849 } 907 }
850 908
851 /// Analyzer checks boolean conversions, but we need to check too, because 909 /// Analyzer checks boolean conversions, but we need to check too, because
852 /// it uses the default assignability rules that allow `dynamic` and `Object` 910 /// it uses the default assignability rules that allow `dynamic` and `Object`
853 /// to be assigned to bool with no message. 911 /// to be assigned to bool with no message.
854 void checkBoolean(Expression expr) => 912 void checkBoolean(Expression expr) =>
855 checkAssignment(expr, rules.provider.boolType); 913 checkAssignment(expr, typeProvider.boolType);
856 914
857 void checkAssignment(Expression expr, DartType type) { 915 void checkAssignment(Expression expr, DartType type) {
858 if (expr is ParenthesizedExpression) { 916 if (expr is ParenthesizedExpression) {
859 checkAssignment(expr.expression, type); 917 checkAssignment(expr.expression, type);
860 } else { 918 } else {
861 _recordMessage(rules.checkAssignment(expr, type)); 919 _recordMessage(_checkAssignment(expr, type));
862 } 920 }
863 } 921 }
864 922
923 StaticInfo _checkAssignment(Expression expr, DartType toT) {
924 final fromT = expr.staticType ?? DynamicTypeImpl.instance;
925 final Coercion c = _coerceTo(fromT, toT);
926 if (c is Identity) return null;
927 if (c is CoercionError) return new StaticTypeError(rules, expr, toT);
928 var reason = null;
929
930 var errors = <String>[];
931
932 var ok = inferrer.inferExpression(expr, toT, errors);
933 if (ok) return InferredType.create(rules, expr, toT);
934 reason = (errors.isNotEmpty) ? errors.first : null;
935
936 if (c is Cast) return DownCast.create(rules, expr, c, reason: reason);
937 assert(false);
938 return null;
939 }
940
941 // Produce a coercion which coerces something of type fromT
942 // to something of type toT.
943 // Returns the error coercion if the types cannot be coerced
944 // according to our current criteria.
945 Coercion _coerceTo(DartType fromT, DartType toT) {
946 // We can use anything as void
947 if (toT.isVoid) return Coercion.identity(toT);
948
949 // fromT <: toT, no coercion needed
950 if (rules.isSubtypeOf(fromT, toT)) return Coercion.identity(toT);
951
952 // TODO(vsm): We can get rid of the second clause if we disallow
953 // all sideways casts - see TODO below.
954 // -------
955 // Note: a function type is never assignable to a class per the Dart
956 // spec - even if it has a compatible call method. We disallow as
957 // well for consistency.
958 if ((fromT is FunctionType && rules.getCallMethodType(toT) != null) ||
959 (toT is FunctionType && rules.getCallMethodType(fromT) != null)) {
960 return Coercion.error();
961 }
962
963 // Downcast if toT <: fromT
964 if (rules.isSubtypeOf(toT, fromT)) return Coercion.cast(fromT, toT);
965
966 // TODO(vsm): Once we have generic methods, we should delete this
967 // workaround. These sideways casts are always ones we warn about
968 // - i.e., we think they are likely to fail at runtime.
969 // -------
970 // Downcast if toT <===> fromT
971 // The intention here is to allow casts that are sideways in the restricted
972 // type system, but allowed in the regular dart type system, since these
973 // are likely to succeed. The canonical example is List<dynamic> and
974 // Iterable<T> for some concrete T (e.g. Object). These are unrelated
975 // in the restricted system, but List<dynamic> <: Iterable<T> in dart.
976 if (fromT.isAssignableTo(toT)) {
977 return Coercion.cast(fromT, toT);
978 }
979
980 return Coercion.error();
981 }
982
865 DartType _specializedBinaryReturnType( 983 DartType _specializedBinaryReturnType(
866 TokenType op, DartType t1, DartType t2, DartType normalReturnType) { 984 TokenType op, DartType t1, DartType t2, DartType normalReturnType) {
867 // This special cases binary return types as per 16.26 and 16.27 of the 985 // This special cases binary return types as per 16.26 and 16.27 of the
868 // Dart language spec. 986 // Dart language spec.
869 switch (op) { 987 switch (op) {
870 case TokenType.PLUS: 988 case TokenType.PLUS:
871 case TokenType.MINUS: 989 case TokenType.MINUS:
872 case TokenType.STAR: 990 case TokenType.STAR:
873 case TokenType.TILDE_SLASH: 991 case TokenType.TILDE_SLASH:
874 case TokenType.PERCENT: 992 case TokenType.PERCENT:
875 case TokenType.PLUS_EQ: 993 case TokenType.PLUS_EQ:
876 case TokenType.MINUS_EQ: 994 case TokenType.MINUS_EQ:
877 case TokenType.STAR_EQ: 995 case TokenType.STAR_EQ:
878 case TokenType.TILDE_SLASH_EQ: 996 case TokenType.TILDE_SLASH_EQ:
879 case TokenType.PERCENT_EQ: 997 case TokenType.PERCENT_EQ:
880 if (t1 == rules.provider.intType && 998 if (t1 == typeProvider.intType &&
881 t2 == rules.provider.intType) return t1; 999 t2 == typeProvider.intType) return t1;
882 if (t1 == rules.provider.doubleType && 1000 if (t1 == typeProvider.doubleType &&
883 t2 == rules.provider.doubleType) return t1; 1001 t2 == typeProvider.doubleType) return t1;
884 // This particular combo is not spelled out in the spec, but all 1002 // This particular combo is not spelled out in the spec, but all
885 // implementations and analyzer seem to follow this. 1003 // implementations and analyzer seem to follow this.
886 if (t1 == rules.provider.doubleType && 1004 if (t1 == typeProvider.doubleType &&
887 t2 == rules.provider.intType) return t1; 1005 t2 == typeProvider.intType) return t1;
888 } 1006 }
889 return normalReturnType; 1007 return normalReturnType;
890 } 1008 }
891 1009
892 void _checkCompoundAssignment(AssignmentExpression expr) { 1010 void _checkCompoundAssignment(AssignmentExpression expr) {
893 var op = expr.operator.type; 1011 var op = expr.operator.type;
894 assert(op.isAssignmentOperator && op != TokenType.EQ); 1012 assert(op.isAssignmentOperator && op != TokenType.EQ);
895 var methodElement = expr.staticElement; 1013 var methodElement = expr.staticElement;
896 if (methodElement == null) { 1014 if (methodElement == null) {
897 // Dynamic invocation 1015 // Dynamic invocation
898 _recordDynamicInvoke(expr, expr.leftHandSide); 1016 _recordDynamicInvoke(expr, expr.leftHandSide);
899 } else { 1017 } else {
900 // Sanity check the operator 1018 // Sanity check the operator
901 assert(methodElement.isOperator); 1019 assert(methodElement.isOperator);
902 var functionType = methodElement.type; 1020 var functionType = methodElement.type;
903 var paramTypes = functionType.normalParameterTypes; 1021 var paramTypes = functionType.normalParameterTypes;
904 assert(paramTypes.length == 1); 1022 assert(paramTypes.length == 1);
905 assert(functionType.namedParameterTypes.isEmpty); 1023 assert(functionType.namedParameterTypes.isEmpty);
906 assert(functionType.optionalParameterTypes.isEmpty); 1024 assert(functionType.optionalParameterTypes.isEmpty);
907 1025
908 // Check the lhs type 1026 // Check the lhs type
909 var staticInfo; 1027 var staticInfo;
910 var rhsType = _getStaticType(expr.rightHandSide); 1028 var rhsType = _getStaticType(expr.rightHandSide);
911 var lhsType = _getStaticType(expr.leftHandSide); 1029 var lhsType = _getStaticType(expr.leftHandSide);
912 var returnType = _specializedBinaryReturnType( 1030 var returnType = _specializedBinaryReturnType(
913 op, lhsType, rhsType, functionType.returnType); 1031 op, lhsType, rhsType, functionType.returnType);
914 1032
915 if (!rules.isSubTypeOf(returnType, lhsType)) { 1033 if (!rules.isSubtypeOf(returnType, lhsType)) {
916 final numType = rules.provider.numType; 1034 final numType = typeProvider.numType;
917 // Try to fix up the numerical case if possible. 1035 // Try to fix up the numerical case if possible.
918 if (rules.isSubTypeOf(lhsType, numType) && 1036 if (rules.isSubtypeOf(lhsType, numType) &&
919 rules.isSubTypeOf(lhsType, rhsType)) { 1037 rules.isSubtypeOf(lhsType, rhsType)) {
920 // This is also slightly different from spec, but allows us to keep 1038 // This is also slightly different from spec, but allows us to keep
921 // compound operators in the int += num and num += dynamic cases. 1039 // compound operators in the int += num and num += dynamic cases.
922 staticInfo = DownCast.create( 1040 staticInfo = DownCast.create(
923 rules, expr.rightHandSide, Coercion.cast(rhsType, lhsType)); 1041 rules, expr.rightHandSide, Coercion.cast(rhsType, lhsType));
924 rhsType = lhsType; 1042 rhsType = lhsType;
925 } else { 1043 } else {
926 // Static type error 1044 // Static type error
927 staticInfo = new StaticTypeError(rules, expr, lhsType); 1045 staticInfo = new StaticTypeError(rules, expr, lhsType);
928 } 1046 }
929 _recordMessage(staticInfo); 1047 _recordMessage(staticInfo);
930 } 1048 }
931 1049
932 // Check the rhs type 1050 // Check the rhs type
933 if (staticInfo is! CoercionInfo) { 1051 if (staticInfo is! CoercionInfo) {
934 var paramType = paramTypes.first; 1052 var paramType = paramTypes.first;
935 staticInfo = rules.checkAssignment(expr.rightHandSide, paramType); 1053 staticInfo = _checkAssignment(expr.rightHandSide, paramType);
936 _recordMessage(staticInfo); 1054 _recordMessage(staticInfo);
937 } 1055 }
938 } 1056 }
939 } 1057 }
940 1058
941 bool _isObjectGetter(Expression target, SimpleIdentifier id) { 1059 bool _isObjectGetter(Expression target, SimpleIdentifier id) {
942 PropertyAccessorElement element = 1060 PropertyAccessorElement element =
943 rules.provider.objectType.element.getGetter(id.name); 1061 typeProvider.objectType.element.getGetter(id.name);
944 return (element != null && !element.isStatic); 1062 return (element != null && !element.isStatic);
945 } 1063 }
946 1064
947 bool _isObjectMethod(Expression target, SimpleIdentifier id) { 1065 bool _isObjectMethod(Expression target, SimpleIdentifier id) {
948 MethodElement element = 1066 MethodElement element =
949 rules.provider.objectType.element.getMethod(id.name); 1067 typeProvider.objectType.element.getMethod(id.name);
950 return (element != null && !element.isStatic); 1068 return (element != null && !element.isStatic);
951 } 1069 }
952 1070
953 bool _isObjectProperty(Expression target, SimpleIdentifier id) { 1071 bool _isObjectProperty(Expression target, SimpleIdentifier id) {
954 return _isObjectGetter(target, id) || _isObjectMethod(target, id); 1072 return _isObjectGetter(target, id) || _isObjectMethod(target, id);
955 } 1073 }
956 1074
957 DartType _getStaticType(Expression expr) { 1075 DartType _getStaticType(Expression expr) {
958 return expr.staticType ?? rules.provider.dynamicType; 1076 return expr.staticType ?? DynamicTypeImpl.instance;
959 } 1077 }
960 1078
961 void _recordDynamicInvoke(AstNode node, AstNode target) { 1079 void _recordDynamicInvoke(AstNode node, AstNode target) {
962 if (_hints) { 1080 if (_hints) {
963 reporter.onError(new DynamicInvoke(rules, node).toAnalysisError()); 1081 reporter.onError(new DynamicInvoke(rules, node).toAnalysisError());
964 } 1082 }
965 // TODO(jmesserly): we may eventually want to record if the whole operation 1083 // TODO(jmesserly): we may eventually want to record if the whole operation
966 // (node) was dynamic, rather than the target, but this is an easier fit 1084 // (node) was dynamic, rather than the target, but this is an easier fit
967 // with what we used to do. 1085 // with what we used to do.
968 DynamicInvoke.set(target, true); 1086 DynamicInvoke.set(target, true);
(...skipping 10 matching lines...) Expand all
979 1097
980 if (info is CoercionInfo) { 1098 if (info is CoercionInfo) {
981 // TODO(jmesserly): if we're run again on the same AST, we'll produce the 1099 // TODO(jmesserly): if we're run again on the same AST, we'll produce the
982 // same annotations. This should be harmless. This might go away once 1100 // same annotations. This should be harmless. This might go away once
983 // CodeChecker is integrated better with analyzer, as it will know that 1101 // CodeChecker is integrated better with analyzer, as it will know that
984 // checking has already been performed. 1102 // checking has already been performed.
985 // assert(CoercionInfo.get(info.node) == null); 1103 // assert(CoercionInfo.get(info.node) == null);
986 CoercionInfo.set(info.node, info); 1104 CoercionInfo.set(info.node, info);
987 } 1105 }
988 } 1106 }
1107
1108 bool _isLibraryPrefix(Expression node) =>
1109 node is SimpleIdentifier && node.staticElement is PrefixElement;
1110
1111 /// Returns `true` if the target expression is dynamic.
1112 bool _isDynamicTarget(Expression node) {
1113 if (node == null) return false;
1114
1115 if (_isLibraryPrefix(node)) return false;
1116
1117 // Null type happens when we have unknown identifiers, like a dart: import
1118 // that doesn't resolve.
1119 var type = node.staticType;
1120 return type == null || type.isDynamic;
1121 }
1122
1123 /// Returns `true` if the expression is a dynamic function call or method
1124 /// invocation.
1125 bool _isDynamicCall(Expression call) {
1126 var ft = _getTypeAsCaller(call);
1127 // TODO(leafp): This will currently return true if t is Function
1128 // This is probably the most correct thing to do for now, since
1129 // this code is also used by the back end. Maybe revisit at some
1130 // point?
1131 if (ft == null) return true;
1132 // Dynamic as the parameter type is treated as bottom. A function with
1133 // a dynamic parameter type requires a dynamic call in general.
1134 // However, as an optimization, if we have an original definition, we know
1135 // dynamic is reified as Object - in this case a regular call is fine.
1136 if (call is SimpleIdentifier) {
1137 var element = call.staticElement;
1138 if (element is FunctionElement || element is MethodElement) {
1139 // An original declaration.
1140 return false;
1141 }
1142 }
1143
1144 return rules.anyParameterType(ft, (pt) => pt.isDynamic);
1145 }
1146
1147 /// Given an expression, return its type assuming it is
1148 /// in the caller position of a call (that is, accounting
1149 /// for the possibility of a call method). Returns null
1150 /// if expression is not statically callable.
1151 FunctionType _getTypeAsCaller(Expression applicand) {
1152 var t = applicand.staticType ?? DynamicTypeImpl.instance;
1153 if (t is InterfaceType) {
1154 return rules.getCallMethodType(t);
1155 }
1156 if (t is FunctionType) return t;
1157 return null;
1158 }
989 } 1159 }
990 1160
991 // Return the field on type corresponding to member, or null if none 1161 // Return the field on type corresponding to member, or null if none
992 // exists or the "field" is actually a getter/setter. 1162 // exists or the "field" is actually a getter/setter.
993 PropertyInducingElement _getMemberField( 1163 PropertyInducingElement _getMemberField(
994 InterfaceType type, PropertyAccessorElement member) { 1164 InterfaceType type, PropertyAccessorElement member) {
995 String memberName = member.name; 1165 String memberName = member.name;
996 PropertyInducingElement field; 1166 PropertyInducingElement field;
997 if (member.isGetter) { 1167 if (member.isGetter) {
998 // The subclass member is an explicit getter or a field 1168 // The subclass member is an explicit getter or a field
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after
1047 baseMethod = type.getSetter(memberName); 1217 baseMethod = type.getSetter(memberName);
1048 } else { 1218 } else {
1049 baseMethod = type.getMethod(memberName); 1219 baseMethod = type.getMethod(memberName);
1050 } 1220 }
1051 } catch (e) { 1221 } catch (e) {
1052 // TODO(sigmund): remove this try-catch block (see issue #48). 1222 // TODO(sigmund): remove this try-catch block (see issue #48).
1053 } 1223 }
1054 if (baseMethod == null || baseMethod.isStatic) return null; 1224 if (baseMethod == null || baseMethod.isStatic) return null;
1055 return baseMethod.type; 1225 return baseMethod.type;
1056 } 1226 }
1057 ;
1058 return f; 1227 return f;
1059 } 1228 }
1229
1230
1231 DartType _elementType(Element e) {
1232 if (e == null) {
1233 // Malformed code - just return dynamic.
1234 return DynamicTypeImpl.instance;
1235 }
1236 return (e as dynamic).type;
1237 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698