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

Side by Side Diff: pkg/analyzer/test/generated/all_the_rest.dart

Issue 762823003: Rename all_the_rest.dart to all_the_rest_test.dart. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 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 | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2014, 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 // This code was auto-generated, is not intended to be edited, and is subject to
6 // significant change. Please see the README file for more information.
7
8 library engine.all_the_rest_test;
9
10 import 'dart:collection';
11
12 import 'package:analyzer/src/generated/ast.dart' hide ConstantEvaluator;
13 import 'package:analyzer/src/generated/constant.dart';
14 import 'package:analyzer/src/generated/element.dart';
15 import 'package:analyzer/src/generated/engine.dart';
16 import 'package:analyzer/src/generated/error.dart';
17 import 'package:analyzer/src/generated/html.dart' as ht;
18 import 'package:analyzer/src/generated/java_core.dart';
19 import 'package:analyzer/src/generated/java_engine.dart';
20 import 'package:analyzer/src/generated/java_engine_io.dart';
21 import 'package:analyzer/src/generated/java_io.dart';
22 import 'package:analyzer/src/generated/resolver.dart';
23 import 'package:analyzer/src/generated/scanner.dart';
24 import 'package:analyzer/src/generated/sdk.dart';
25 import 'package:analyzer/src/generated/sdk_io.dart';
26 import 'package:analyzer/src/generated/source.dart';
27 import 'package:analyzer/src/generated/source_io.dart';
28 import 'package:analyzer/src/generated/testing/ast_factory.dart';
29 import 'package:analyzer/src/generated/testing/element_factory.dart';
30 import 'package:analyzer/src/generated/testing/html_factory.dart';
31 import 'package:analyzer/src/generated/utilities_collection.dart';
32 import 'package:analyzer/src/generated/utilities_dart.dart';
33 import 'package:unittest/unittest.dart';
34
35 import '../reflective_tests.dart';
36 import 'parser_test.dart';
37 import 'resolver_test.dart';
38 import 'test_support.dart';
39
40
41 main() {
42 groupSep = ' | ';
43 runReflectiveTests(AngularCompilationUnitBuilderTest);
44 runReflectiveTests(AngularHtmlUnitResolverTest);
45 runReflectiveTests(AngularHtmlUnitUtilsTest);
46 runReflectiveTests(ConstantEvaluatorTest);
47 runReflectiveTests(ConstantFinderTest);
48 runReflectiveTests(ConstantValueComputerTest);
49 runReflectiveTests(ConstantVisitorTest);
50 runReflectiveTests(ContentCacheTest);
51 runReflectiveTests(DartObjectImplTest);
52 runReflectiveTests(DartUriResolverTest);
53 runReflectiveTests(DeclaredVariablesTest);
54 runReflectiveTests(DirectoryBasedDartSdkTest);
55 runReflectiveTests(DirectoryBasedSourceContainerTest);
56 runReflectiveTests(ElementBuilderTest);
57 runReflectiveTests(ElementLocatorTest);
58 runReflectiveTests(EnumMemberBuilderTest);
59 runReflectiveTests(ErrorReporterTest);
60 runReflectiveTests(ErrorSeverityTest);
61 runReflectiveTests(ExitDetectorTest);
62 runReflectiveTests(FileBasedSourceTest);
63 runReflectiveTests(FileUriResolverTest);
64 runReflectiveTests(HtmlParserTest);
65 runReflectiveTests(HtmlTagInfoBuilderTest);
66 runReflectiveTests(HtmlUnitBuilderTest);
67 runReflectiveTests(HtmlWarningCodeTest);
68 runReflectiveTests(ReferenceFinderTest);
69 runReflectiveTests(SDKLibrariesReaderTest);
70 runReflectiveTests(SourceFactoryTest);
71 runReflectiveTests(ToSourceVisitorTest);
72 runReflectiveTests(UriKindTest);
73 runReflectiveTests(StringScannerTest);
74 }
75
76 abstract class AbstractScannerTest {
77 ht.AbstractScanner newScanner(String input);
78
79 void test_tokenize_attribute() {
80 _tokenize(
81 "<html bob=\"one two\">",
82 <Object>[
83 ht.TokenType.LT,
84 "html",
85 "bob",
86 ht.TokenType.EQ,
87 "\"one two\"",
88 ht.TokenType.GT]);
89 }
90
91 void test_tokenize_comment() {
92 _tokenize("<!-- foo -->", <Object>["<!-- foo -->"]);
93 }
94
95 void test_tokenize_comment_incomplete() {
96 _tokenize("<!-- foo", <Object>["<!-- foo"]);
97 }
98
99 void test_tokenize_comment_with_gt() {
100 _tokenize("<!-- foo > -> -->", <Object>["<!-- foo > -> -->"]);
101 }
102
103 void test_tokenize_declaration() {
104 _tokenize(
105 "<! foo ><html>",
106 <Object>["<! foo >", ht.TokenType.LT, "html", ht.TokenType.GT]);
107 }
108
109 void test_tokenize_declaration_malformed() {
110 _tokenize(
111 "<! foo /><html>",
112 <Object>["<! foo />", ht.TokenType.LT, "html", ht.TokenType.GT]);
113 }
114
115 void test_tokenize_directive_incomplete() {
116 _tokenize2("<? \nfoo", <Object>["<? \nfoo"], <int>[0, 4]);
117 }
118
119 void test_tokenize_directive_xml() {
120 _tokenize(
121 "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
122 <Object>["<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"]);
123 }
124
125 void test_tokenize_directives_incomplete_with_newline() {
126 _tokenize2("<! \nfoo", <Object>["<! \nfoo"], <int>[0, 4]);
127 }
128
129 void test_tokenize_empty() {
130 _tokenize("", <Object>[]);
131 }
132
133 void test_tokenize_lt() {
134 _tokenize("<", <Object>[ht.TokenType.LT]);
135 }
136
137 void test_tokenize_script_embedded_tags() {
138 _tokenize(
139 "<script> <p></p></script>",
140 <Object>[
141 ht.TokenType.LT,
142 "script",
143 ht.TokenType.GT,
144 " <p></p>",
145 ht.TokenType.LT_SLASH,
146 "script",
147 ht.TokenType.GT]);
148 }
149
150 void test_tokenize_script_embedded_tags2() {
151 _tokenize(
152 "<script> <p></p><</script>",
153 <Object>[
154 ht.TokenType.LT,
155 "script",
156 ht.TokenType.GT,
157 " <p></p><",
158 ht.TokenType.LT_SLASH,
159 "script",
160 ht.TokenType.GT]);
161 }
162
163 void test_tokenize_script_embedded_tags3() {
164 _tokenize(
165 "<script> <p></p></</script>",
166 <Object>[
167 ht.TokenType.LT,
168 "script",
169 ht.TokenType.GT,
170 " <p></p></",
171 ht.TokenType.LT_SLASH,
172 "script",
173 ht.TokenType.GT]);
174 }
175
176 void test_tokenize_script_partial() {
177 _tokenize(
178 "<script> <p> ",
179 <Object>[ht.TokenType.LT, "script", ht.TokenType.GT, " <p> "]);
180 }
181
182 void test_tokenize_script_partial2() {
183 _tokenize(
184 "<script> <p> <",
185 <Object>[ht.TokenType.LT, "script", ht.TokenType.GT, " <p> <"]);
186 }
187
188 void test_tokenize_script_partial3() {
189 _tokenize(
190 "<script> <p> </",
191 <Object>[ht.TokenType.LT, "script", ht.TokenType.GT, " <p> </"]);
192 }
193
194 void test_tokenize_script_ref() {
195 _tokenize(
196 "<script source='some.dart'/> <p>",
197 <Object>[
198 ht.TokenType.LT,
199 "script",
200 "source",
201 ht.TokenType.EQ,
202 "'some.dart'",
203 ht.TokenType.SLASH_GT,
204 " ",
205 ht.TokenType.LT,
206 "p",
207 ht.TokenType.GT]);
208 }
209
210 void test_tokenize_script_with_newline() {
211 _tokenize2(
212 "<script> <p>\n </script>",
213 <Object>[
214 ht.TokenType.LT,
215 "script",
216 ht.TokenType.GT,
217 " <p>\n ",
218 ht.TokenType.LT_SLASH,
219 "script",
220 ht.TokenType.GT],
221 <int>[0, 13]);
222 }
223
224 void test_tokenize_spaces_and_newlines() {
225 ht.Token token = _tokenize2(
226 " < html \n bob = 'joe\n' >\n <\np > one \r\n two <!-- \rfoo --> </ p > </ html > ",
227 <Object>[
228 " ",
229 ht.TokenType.LT,
230 "html",
231 "bob",
232 ht.TokenType.EQ,
233 "'joe\n'",
234 ht.TokenType.GT,
235 "\n ",
236 ht.TokenType.LT,
237 "p",
238 ht.TokenType.GT,
239 " one \r\n two ",
240 "<!-- \rfoo -->",
241 " ",
242 ht.TokenType.LT_SLASH,
243 "p",
244 ht.TokenType.GT,
245 " ",
246 ht.TokenType.LT_SLASH,
247 "html",
248 ht.TokenType.GT,
249 " "],
250 <int>[0, 9, 21, 25, 28, 38, 49]);
251 token = token.next;
252 expect(token.offset, 1);
253 token = token.next;
254 expect(token.offset, 3);
255 token = token.next;
256 expect(token.offset, 10);
257 }
258
259 void test_tokenize_string() {
260 _tokenize(
261 "<p bob=\"foo\">",
262 <Object>[
263 ht.TokenType.LT,
264 "p",
265 "bob",
266 ht.TokenType.EQ,
267 "\"foo\"",
268 ht.TokenType.GT]);
269 }
270
271 void test_tokenize_string_partial() {
272 _tokenize(
273 "<p bob=\"foo",
274 <Object>[ht.TokenType.LT, "p", "bob", ht.TokenType.EQ, "\"foo"]);
275 }
276
277 void test_tokenize_string_single_quote() {
278 _tokenize(
279 "<p bob='foo'>",
280 <Object>[
281 ht.TokenType.LT,
282 "p",
283 "bob",
284 ht.TokenType.EQ,
285 "'foo'",
286 ht.TokenType.GT]);
287 }
288
289 void test_tokenize_string_single_quote_partial() {
290 _tokenize(
291 "<p bob='foo",
292 <Object>[ht.TokenType.LT, "p", "bob", ht.TokenType.EQ, "'foo"]);
293 }
294
295 void test_tokenize_tag_begin_end() {
296 _tokenize(
297 "<html></html>",
298 <Object>[
299 ht.TokenType.LT,
300 "html",
301 ht.TokenType.GT,
302 ht.TokenType.LT_SLASH,
303 "html",
304 ht.TokenType.GT]);
305 }
306
307 void test_tokenize_tag_begin_only() {
308 ht.Token token =
309 _tokenize("<html>", <Object>[ht.TokenType.LT, "html", ht.TokenType.GT]);
310 token = token.next;
311 expect(token.offset, 1);
312 }
313
314 void test_tokenize_tag_incomplete_with_special_characters() {
315 _tokenize("<br-a_b", <Object>[ht.TokenType.LT, "br-a_b"]);
316 }
317
318 void test_tokenize_tag_self_contained() {
319 _tokenize("<br/>", <Object>[ht.TokenType.LT, "br", ht.TokenType.SLASH_GT]);
320 }
321
322 void test_tokenize_tags_wellformed() {
323 _tokenize(
324 "<html><p>one two</p></html>",
325 <Object>[
326 ht.TokenType.LT,
327 "html",
328 ht.TokenType.GT,
329 ht.TokenType.LT,
330 "p",
331 ht.TokenType.GT,
332 "one two",
333 ht.TokenType.LT_SLASH,
334 "p",
335 ht.TokenType.GT,
336 ht.TokenType.LT_SLASH,
337 "html",
338 ht.TokenType.GT]);
339 }
340
341 /**
342 * Given an object representing an expected token, answer the expected token t ype.
343 *
344 * @param count the token count for error reporting
345 * @param expected the object representing an expected token
346 * @return the expected token type
347 */
348 ht.TokenType _getExpectedTokenType(int count, Object expected) {
349 if (expected is ht.TokenType) {
350 return expected;
351 }
352 if (expected is String) {
353 String lexeme = expected;
354 if (lexeme.startsWith("\"") || lexeme.startsWith("'")) {
355 return ht.TokenType.STRING;
356 }
357 if (lexeme.startsWith("<!--")) {
358 return ht.TokenType.COMMENT;
359 }
360 if (lexeme.startsWith("<!")) {
361 return ht.TokenType.DECLARATION;
362 }
363 if (lexeme.startsWith("<?")) {
364 return ht.TokenType.DIRECTIVE;
365 }
366 if (_isTag(lexeme)) {
367 return ht.TokenType.TAG;
368 }
369 return ht.TokenType.TEXT;
370 }
371 fail(
372 "Unknown expected token $count: ${expected != null ? expected.runtimeTyp e : "null"}");
373 return null;
374 }
375
376 bool _isTag(String lexeme) {
377 if (lexeme.length == 0 || !Character.isLetter(lexeme.codeUnitAt(0))) {
378 return false;
379 }
380 for (int index = 1; index < lexeme.length; index++) {
381 int ch = lexeme.codeUnitAt(index);
382 if (!Character.isLetterOrDigit(ch) && ch != 0x2D && ch != 0x5F) {
383 return false;
384 }
385 }
386 return true;
387 }
388
389 ht.Token _tokenize(String input, List<Object> expectedTokens) =>
390 _tokenize2(input, expectedTokens, <int>[0]);
391 ht.Token _tokenize2(String input, List<Object> expectedTokens,
392 List<int> expectedLineStarts) {
393 ht.AbstractScanner scanner = newScanner(input);
394 scanner.passThroughElements = <String>["script"];
395 int count = 0;
396 ht.Token firstToken = scanner.tokenize();
397 ht.Token token = firstToken;
398 ht.Token previousToken = token.previous;
399 expect(previousToken.type == ht.TokenType.EOF, isTrue);
400 expect(previousToken.previous, same(previousToken));
401 expect(previousToken.offset, -1);
402 expect(previousToken.next, same(token));
403 expect(token.offset, 0);
404 while (token.type != ht.TokenType.EOF) {
405 if (count == expectedTokens.length) {
406 fail("too many parsed tokens");
407 }
408 Object expected = expectedTokens[count];
409 ht.TokenType expectedTokenType = _getExpectedTokenType(count, expected);
410 expect(token.type, same(expectedTokenType), reason: "token $count");
411 if (expectedTokenType.lexeme != null) {
412 expect(token.lexeme, expectedTokenType.lexeme, reason: "token $count");
413 } else {
414 expect(token.lexeme, expected, reason: "token $count");
415 }
416 count++;
417 previousToken = token;
418 token = token.next;
419 expect(token.previous, same(previousToken));
420 }
421 expect(token.next, same(token));
422 expect(token.offset, input.length);
423 if (count != expectedTokens.length) {
424 expect(false, isTrue, reason: "not enough parsed tokens");
425 }
426 List<int> lineStarts = scanner.lineStarts;
427 bool success = expectedLineStarts.length == lineStarts.length;
428 if (success) {
429 for (int i = 0; i < lineStarts.length; i++) {
430 if (expectedLineStarts[i] != lineStarts[i]) {
431 success = false;
432 break;
433 }
434 }
435 }
436 if (!success) {
437 StringBuffer buffer = new StringBuffer();
438 buffer.write("Expected line starts ");
439 for (int start in expectedLineStarts) {
440 buffer.write(start);
441 buffer.write(", ");
442 }
443 buffer.write(" but found ");
444 for (int start in lineStarts) {
445 buffer.write(start);
446 buffer.write(", ");
447 }
448 fail(buffer.toString());
449 }
450 return firstToken;
451 }
452 }
453
454
455 class AngularCompilationUnitBuilderTest extends AngularTest {
456 void test_bad_notConstructorAnnotation() {
457 String mainContent = r'''
458 const MY_ANNOTATION = null;
459 @MY_ANNOTATION()
460 class MyFilter {
461 }''';
462 resolveMainSource(mainContent);
463 // prepare AngularFilterElement
464 ClassElement classElement = mainUnitElement.getType("MyFilter");
465 AngularFormatterElement filter =
466 getAngularElement(classElement, (e) => e is AngularFormatterElement);
467 expect(filter, isNull);
468 }
469
470 void test_Decorator() {
471 String mainContent = _createAngularSource(r'''
472 @Decorator(selector: '[my-dir]',
473 map: const {
474 'my-dir' : '=>myPropA',
475 '.' : '&myPropB',
476 })
477 class MyDirective {
478 set myPropA(value) {}
479 set myPropB(value) {}
480 @NgTwoWay('my-prop-c')
481 String myPropC;
482 }''');
483 resolveMainSourceNoErrors(mainContent);
484 // prepare AngularDirectiveElement
485 ClassElement classElement = mainUnitElement.getType("MyDirective");
486 AngularDecoratorElement directive =
487 getAngularElement(classElement, (e) => e is AngularDecoratorElement);
488 expect(directive, isNotNull);
489 // verify
490 expect(directive.name, null);
491 expect(directive.nameOffset, -1);
492 _assertHasAttributeSelector(directive.selector, "my-dir");
493 // verify properties
494 List<AngularPropertyElement> properties = directive.properties;
495 expect(properties, hasLength(3));
496 _assertProperty(
497 properties[0],
498 "my-dir",
499 findMainOffset("my-dir' :"),
500 AngularPropertyKind.ONE_WAY,
501 "myPropA",
502 findMainOffset("myPropA'"));
503 _assertProperty(
504 properties[1],
505 ".",
506 findMainOffset(".' :"),
507 AngularPropertyKind.CALLBACK,
508 "myPropB",
509 findMainOffset("myPropB'"));
510 _assertProperty(
511 properties[2],
512 "my-prop-c",
513 findMainOffset("my-prop-c'"),
514 AngularPropertyKind.TWO_WAY,
515 "myPropC",
516 -1);
517 }
518
519 void test_Decorator_bad_cannotParseSelector() {
520 String mainContent = _createAngularSource(r'''
521 @Decorator(selector: '~bad-selector',
522 map: const {
523 'my-dir' : '=>myPropA',
524 '.' : '&myPropB',
525 })
526 class MyDirective {
527 set myPropA(value) {}
528 set myPropB(value) {}
529 }''');
530 resolveMainSource(mainContent);
531 // has error
532 assertMainErrors([AngularCode.CANNOT_PARSE_SELECTOR]);
533 }
534
535 void test_Decorator_bad_missingSelector() {
536 String mainContent = _createAngularSource(r'''
537 @Decorator(/*selector: '[my-dir]',*/
538 map: const {
539 'my-dir' : '=>myPropA',
540 '.' : '&myPropB',
541 })
542 class MyDirective {
543 set myPropA(value) {}
544 set myPropB(value) {}
545 }''');
546 resolveMainSource(mainContent);
547 // has error
548 assertMainErrors([AngularCode.MISSING_SELECTOR]);
549 }
550
551 void test_Formatter() {
552 String mainContent = _createAngularSource(r'''
553 @Formatter(name: 'myFilter')
554 class MyFilter {
555 call(p1, p2) {}
556 }''');
557 resolveMainSourceNoErrors(mainContent);
558 // prepare AngularFilterElement
559 ClassElement classElement = mainUnitElement.getType("MyFilter");
560 AngularFormatterElement filter =
561 getAngularElement(classElement, (e) => e is AngularFormatterElement);
562 expect(filter, isNotNull);
563 // verify
564 expect(filter.name, "myFilter");
565 expect(filter.nameOffset, AngularTest.findOffset(mainContent, "myFilter'"));
566 }
567
568 void test_Formatter_missingName() {
569 String mainContent = _createAngularSource(r'''
570 @Formatter()
571 class MyFilter {
572 call(p1, p2) {}
573 }''');
574 resolveMainSource(mainContent);
575 // has error
576 assertMainErrors([AngularCode.MISSING_NAME]);
577 // no filter
578 ClassElement classElement = mainUnitElement.getType("MyFilter");
579 AngularFormatterElement filter =
580 getAngularElement(classElement, (e) => e is AngularFormatterElement);
581 expect(filter, isNull);
582 }
583
584 void test_getElement_component_name() {
585 resolveMainSource(_createAngularSource(r'''
586 @Component(publishAs: 'ctrl', selector: 'myComp',
587 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
588 class MyComponent {}'''));
589 SimpleStringLiteral node =
590 _findMainNode("ctrl'", (n) => n is SimpleStringLiteral);
591 int offset = node.offset;
592 // find AngularComponentElement
593 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
594 EngineTestCase.assertInstanceOf(
595 (obj) => obj is AngularComponentElement,
596 AngularComponentElement,
597 element);
598 }
599
600 void test_getElement_component_property_fromFieldAnnotation() {
601 resolveMainSource(_createAngularSource(r'''
602 @Component(publishAs: 'ctrl', selector: 'myComp',
603 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
604 class MyComponent {
605 @NgOneWay('prop')
606 var field;
607 }'''));
608 // prepare node
609 SimpleStringLiteral node =
610 _findMainNode("prop'", (n) => n is SimpleStringLiteral);
611 int offset = node.offset;
612 // prepare Element
613 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
614 expect(element, isNotNull);
615 // check AngularPropertyElement
616 AngularPropertyElement property = element as AngularPropertyElement;
617 expect(property.name, "prop");
618 }
619
620 void test_getElement_component_property_fromMap() {
621 resolveMainSource(_createAngularSource(r'''
622 @Component(publishAs: 'ctrl', selector: 'myComp',
623 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
624 map: const {
625 'prop' : '@field',
626 })
627 class MyComponent {
628 var field;
629 }'''));
630 // AngularPropertyElement
631 {
632 SimpleStringLiteral node =
633 _findMainNode("prop'", (n) => n is SimpleStringLiteral);
634 int offset = node.offset;
635 // prepare Element
636 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
637 expect(element, isNotNull);
638 // check AngularPropertyElement
639 AngularPropertyElement property = element as AngularPropertyElement;
640 expect(property.name, "prop");
641 }
642 // FieldElement
643 {
644 SimpleStringLiteral node =
645 _findMainNode("@field'", (n) => n is SimpleStringLiteral);
646 int offset = node.offset;
647 // prepare Element
648 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
649 expect(element, isNotNull);
650 // check FieldElement
651 FieldElement field = element as FieldElement;
652 expect(field.name, "field");
653 }
654 }
655
656 void test_getElement_component_selector() {
657 resolveMainSource(_createAngularSource(r'''
658 @Component(publishAs: 'ctrl', selector: 'myComp',
659 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
660 class MyComponent {}'''));
661 SimpleStringLiteral node =
662 _findMainNode("myComp'", (n) => n is SimpleStringLiteral);
663 int offset = node.offset;
664 // find AngularSelectorElement
665 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
666 EngineTestCase.assertInstanceOf(
667 (obj) => obj is AngularSelectorElement,
668 AngularSelectorElement,
669 element);
670 }
671
672 void test_getElement_controller_name() {
673 resolveMainSource(_createAngularSource(r'''
674 @Controller(publishAs: 'ctrl', selector: '[myApp]')
675 class MyController {
676 }'''));
677 SimpleStringLiteral node =
678 _findMainNode("ctrl'", (n) => n is SimpleStringLiteral);
679 int offset = node.offset;
680 // find AngularControllerElement
681 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
682 EngineTestCase.assertInstanceOf(
683 (obj) => obj is AngularControllerElement,
684 AngularControllerElement,
685 element);
686 }
687
688 void test_getElement_directive_property() {
689 resolveMainSource(_createAngularSource(r'''
690 @Decorator(selector: '[my-dir]',
691 map: const {
692 'my-dir' : '=>field'
693 })
694 class MyDirective {
695 set field(value) {}
696 }'''));
697 // prepare node
698 SimpleStringLiteral node =
699 _findMainNode("my-dir'", (n) => n is SimpleStringLiteral);
700 int offset = node.offset;
701 // prepare Element
702 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
703 expect(element, isNotNull);
704 // check AngularPropertyElement
705 AngularPropertyElement property = element as AngularPropertyElement;
706 expect(property.name, "my-dir");
707 }
708
709 void test_getElement_directive_selector() {
710 resolveMainSource(_createAngularSource(r'''
711 @Decorator(selector: '[my-dir]')
712 class MyDirective {}'''));
713 SimpleStringLiteral node =
714 _findMainNode("my-dir]'", (n) => n is SimpleStringLiteral);
715 int offset = node.offset;
716 // find AngularSelectorElement
717 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
718 EngineTestCase.assertInstanceOf(
719 (obj) => obj is AngularSelectorElement,
720 AngularSelectorElement,
721 element);
722 }
723
724 void test_getElement_filter_name() {
725 resolveMainSource(_createAngularSource(r'''
726 @Formatter(name: 'myFilter')
727 class MyFilter {
728 call(p1, p2) {}
729 }'''));
730 SimpleStringLiteral node =
731 _findMainNode("myFilter'", (n) => n is SimpleStringLiteral);
732 int offset = node.offset;
733 // find FilterElement
734 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
735 EngineTestCase.assertInstanceOf(
736 (obj) => obj is AngularFormatterElement,
737 AngularFormatterElement,
738 element);
739 }
740
741 void test_getElement_noClassDeclaration() {
742 resolveMainSource("var foo = 'bar';");
743 SimpleStringLiteral node =
744 _findMainNode("bar'", (n) => n is SimpleStringLiteral);
745 Element element = AngularCompilationUnitBuilder.getElement(node, 0);
746 expect(element, isNull);
747 }
748
749 void test_getElement_noClassElement() {
750 resolveMainSource(r'''
751 class A {
752 const A(p);
753 }
754
755 @A('bar')
756 class B {}''');
757 SimpleStringLiteral node =
758 _findMainNode("bar'", (n) => n is SimpleStringLiteral);
759 // reset B element
760 ClassDeclaration classDeclaration =
761 node.getAncestor((node) => node is ClassDeclaration);
762 classDeclaration.name.staticElement = null;
763 // class is not resolved - no element
764 Element element = AngularCompilationUnitBuilder.getElement(node, 0);
765 expect(element, isNull);
766 }
767
768 void test_getElement_noNode() {
769 Element element = AngularCompilationUnitBuilder.getElement(null, 0);
770 expect(element, isNull);
771 }
772
773 void test_getElement_notFound() {
774 resolveMainSource(r'''
775 class MyComponent {
776 var str = 'some string';
777 }''');
778 // prepare node
779 SimpleStringLiteral node =
780 _findMainNode("some string'", (n) => n is SimpleStringLiteral);
781 int offset = node.offset;
782 // no Element
783 Element element = AngularCompilationUnitBuilder.getElement(node, offset);
784 expect(element, isNull);
785 }
786
787 void test_getElement_SimpleStringLiteral_withToolkitElement() {
788 SimpleStringLiteral literal = AstFactory.string2("foo");
789 Element element = new AngularScopePropertyElementImpl("foo", 0, null);
790 literal.toolkitElement = element;
791 expect(
792 AngularCompilationUnitBuilder.getElement(literal, -1),
793 same(element));
794 }
795
796 void test_NgComponent_bad_cannotParseSelector() {
797 contextHelper.addSource("/my_template.html", "");
798 contextHelper.addSource("/my_styles.css", "");
799 String mainContent = _createAngularSource(r'''
800 @Component(publishAs: 'ctrl', selector: '~myComp',
801 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
802 class MyComponent {
803 }''');
804 resolveMainSource(mainContent);
805 // has error
806 assertMainErrors([AngularCode.CANNOT_PARSE_SELECTOR]);
807 }
808
809 void test_NgComponent_bad_missingSelector() {
810 contextHelper.addSource("/my_template.html", "");
811 contextHelper.addSource("/my_styles.css", "");
812 String mainContent = _createAngularSource(r'''
813 @Component(publishAs: 'ctrl', /*selector: 'myComp',*/
814 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
815 class MyComponent {
816 }''');
817 resolveMainSource(mainContent);
818 // has error
819 assertMainErrors([AngularCode.MISSING_SELECTOR]);
820 }
821
822 /**
823 *
824 * https://code.google.com/p/dart/issues/detail?id=16346
825 */
826 void test_NgComponent_bad_notHtmlTemplate() {
827 contextHelper.addSource("/my_template", "");
828 contextHelper.addSource("/my_styles.css", "");
829 addMainSource(_createAngularSource(r'''
830 @NgComponent(publishAs: 'ctrl', selector: 'myComp',
831 templateUrl: 'my_template', cssUrl: 'my_styles.css')
832 class MyComponent {
833 }'''));
834 contextHelper.runTasks();
835 }
836
837 void test_NgComponent_bad_properties_invalidBinding() {
838 contextHelper.addSource("/my_template.html", "");
839 contextHelper.addSource("/my_styles.css", "");
840 String mainContent = _createAngularSource(r'''
841 @Component(publishAs: 'ctrl', selector: 'myComp',
842 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
843 map: const {'name' : '?field'})
844 class MyComponent {
845 }''');
846 resolveMainSource(mainContent);
847 // has error
848 assertMainErrors([AngularCode.INVALID_PROPERTY_KIND]);
849 }
850
851 void test_NgComponent_bad_properties_nameNotStringLiteral() {
852 contextHelper.addSource("/my_template.html", "");
853 contextHelper.addSource("/my_styles.css", "");
854 String mainContent = _createAngularSource(r'''
855 @Component(publishAs: 'ctrl', selector: 'myComp',
856 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
857 map: const {null : 'field'})
858 class MyComponent {
859 }''');
860 resolveMainSource(mainContent);
861 // has error
862 assertMainErrors([AngularCode.INVALID_PROPERTY_NAME]);
863 }
864
865 void test_NgComponent_bad_properties_noSuchField() {
866 contextHelper.addSource("/my_template.html", "");
867 contextHelper.addSource("/my_styles.css", "");
868 String mainContent = _createAngularSource(r'''
869 @Component(publishAs: 'ctrl', selector: 'myComp',
870 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
871 map: const {'name' : '=>field'})
872 class MyComponent {
873 }''');
874 resolveMainSource(mainContent);
875 // has error
876 assertMainErrors([AngularCode.INVALID_PROPERTY_FIELD]);
877 }
878
879 void test_NgComponent_bad_properties_notMapLiteral() {
880 contextHelper.addSource("/my_template.html", "");
881 contextHelper.addSource("/my_styles.css", "");
882 String mainContent = _createAngularSource(r'''
883 @Component(publishAs: 'ctrl', selector: 'myComp',
884 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
885 map: null)
886 class MyComponent {
887 }''');
888 resolveMainSource(mainContent);
889 // has error
890 assertMainErrors([AngularCode.INVALID_PROPERTY_MAP]);
891 }
892
893 void test_NgComponent_bad_properties_specNotStringLiteral() {
894 contextHelper.addSource("/my_template.html", "");
895 contextHelper.addSource("/my_styles.css", "");
896 String mainContent = _createAngularSource(r'''
897 @Component(publishAs: 'ctrl', selector: 'myComp',
898 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
899 map: const {'name' : null})
900 class MyComponent {
901 }''');
902 resolveMainSource(mainContent);
903 // has error
904 assertMainErrors([AngularCode.INVALID_PROPERTY_SPEC]);
905 }
906
907 void test_NgComponent_no_cssUrl() {
908 contextHelper.addSource("/my_template.html", "");
909 contextHelper.addSource("/my_styles.css", "");
910 String mainContent = _createAngularSource(r'''
911 @Component(publishAs: 'ctrl', selector: 'myComp',
912 templateUrl: 'my_template.html'/*, cssUrl: 'my_styles.css'*/)
913 class MyComponent {
914 }''');
915 resolveMainSource(mainContent);
916 // prepare AngularComponentElement
917 ClassElement classElement = mainUnitElement.getType("MyComponent");
918 AngularComponentElement component =
919 getAngularElement(classElement, (e) => e is AngularComponentElement);
920 expect(component, isNotNull);
921 // no CSS
922 expect(component.styleUri, null);
923 expect(component.styleUriOffset, -1);
924 }
925
926 void test_NgComponent_no_publishAs() {
927 contextHelper.addSource("/my_template.html", "");
928 contextHelper.addSource("/my_styles.css", "");
929 String mainContent = _createAngularSource(r'''
930 @Component(/*publishAs: 'ctrl',*/ selector: 'myComp',
931 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
932 class MyComponent {
933 }''');
934 resolveMainSource(mainContent);
935 // prepare AngularComponentElement
936 ClassElement classElement = mainUnitElement.getType("MyComponent");
937 AngularComponentElement component =
938 getAngularElement(classElement, (e) => e is AngularComponentElement);
939 expect(component, isNotNull);
940 // no name
941 expect(component.name, null);
942 expect(component.nameOffset, -1);
943 }
944
945 void test_NgComponent_no_templateUrl() {
946 contextHelper.addSource("/my_template.html", "");
947 contextHelper.addSource("/my_styles.css", "");
948 String mainContent = _createAngularSource(r'''
949 @Component(publishAs: 'ctrl', selector: 'myComp',
950 /*templateUrl: 'my_template.html',*/ cssUrl: 'my_styles.css')
951 class MyComponent {
952 }''');
953 resolveMainSource(mainContent);
954 // prepare AngularComponentElement
955 ClassElement classElement = mainUnitElement.getType("MyComponent");
956 AngularComponentElement component =
957 getAngularElement(classElement, (e) => e is AngularComponentElement);
958 expect(component, isNotNull);
959 // no template
960 expect(component.templateUri, null);
961 expect(component.templateSource, null);
962 expect(component.templateUriOffset, -1);
963 }
964
965 /**
966 * https://code.google.com/p/dart/issues/detail?id=19023
967 */
968 void test_NgComponent_notAngular() {
969 contextHelper.addSource("/my_template.html", "");
970 contextHelper.addSource("/my_styles.css", "");
971 String mainContent = r'''
972 class Component {
973 const Component(a, b);
974 }
975
976 @Component('foo', 42)
977 class MyComponent {
978 }''';
979 resolveMainSource(mainContent);
980 assertNoMainErrors();
981 }
982
983 void test_NgComponent_properties_fieldFromSuper() {
984 contextHelper.addSource("/my_template.html", "");
985 contextHelper.addSource("/my_styles.css", "");
986 resolveMainSourceNoErrors(_createAngularSource(r'''
987 class MySuper {
988 var myPropA;
989 }
990
991
992
993 @Component(publishAs: 'ctrl', selector: 'myComp',
994 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
995 map: const {
996 'prop-a' : '@myPropA'
997 })
998 class MyComponent extends MySuper {
999 }'''));
1000 // prepare AngularComponentElement
1001 ClassElement classElement = mainUnitElement.getType("MyComponent");
1002 AngularComponentElement component =
1003 getAngularElement(classElement, (e) => e is AngularComponentElement);
1004 expect(component, isNotNull);
1005 // verify
1006 List<AngularPropertyElement> properties = component.properties;
1007 expect(properties, hasLength(1));
1008 _assertProperty(
1009 properties[0],
1010 "prop-a",
1011 findMainOffset("prop-a' :"),
1012 AngularPropertyKind.ATTR,
1013 "myPropA",
1014 findMainOffset("myPropA'"));
1015 }
1016
1017 void test_NgComponent_properties_fromFields() {
1018 contextHelper.addSource("/my_template.html", "");
1019 contextHelper.addSource("/my_styles.css", "");
1020 resolveMainSourceNoErrors(_createAngularSource(r'''
1021 @Component(publishAs: 'ctrl', selector: 'myComp',
1022 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
1023 class MyComponent {
1024 @NgAttr('prop-a')
1025 var myPropA;
1026 @NgCallback('prop-b')
1027 var myPropB;
1028 @NgOneWay('prop-c')
1029 var myPropC;
1030 @NgOneWayOneTime('prop-d')
1031 var myPropD;
1032 @NgTwoWay('prop-e')
1033 var myPropE;
1034 }'''));
1035 // prepare AngularComponentElement
1036 ClassElement classElement = mainUnitElement.getType("MyComponent");
1037 AngularComponentElement component =
1038 getAngularElement(classElement, (e) => e is AngularComponentElement);
1039 expect(component, isNotNull);
1040 // verify
1041 List<AngularPropertyElement> properties = component.properties;
1042 expect(properties, hasLength(5));
1043 _assertProperty(
1044 properties[0],
1045 "prop-a",
1046 findMainOffset("prop-a')"),
1047 AngularPropertyKind.ATTR,
1048 "myPropA",
1049 -1);
1050 _assertProperty(
1051 properties[1],
1052 "prop-b",
1053 findMainOffset("prop-b')"),
1054 AngularPropertyKind.CALLBACK,
1055 "myPropB",
1056 -1);
1057 _assertProperty(
1058 properties[2],
1059 "prop-c",
1060 findMainOffset("prop-c')"),
1061 AngularPropertyKind.ONE_WAY,
1062 "myPropC",
1063 -1);
1064 _assertProperty(
1065 properties[3],
1066 "prop-d",
1067 findMainOffset("prop-d')"),
1068 AngularPropertyKind.ONE_WAY_ONE_TIME,
1069 "myPropD",
1070 -1);
1071 _assertProperty(
1072 properties[4],
1073 "prop-e",
1074 findMainOffset("prop-e')"),
1075 AngularPropertyKind.TWO_WAY,
1076 "myPropE",
1077 -1);
1078 }
1079
1080 void test_NgComponent_properties_fromMap() {
1081 contextHelper.addSource("/my_template.html", "");
1082 contextHelper.addSource("/my_styles.css", "");
1083 resolveMainSourceNoErrors(_createAngularSource(r'''
1084 @Component(publishAs: 'ctrl', selector: 'myComp',
1085 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
1086 map: const {
1087 'prop-a' : '@myPropA',
1088 'prop-b' : '&myPropB',
1089 'prop-c' : '=>myPropC',
1090 'prop-d' : '=>!myPropD',
1091 'prop-e' : '<=>myPropE'
1092 })
1093 class MyComponent {
1094 var myPropA;
1095 var myPropB;
1096 var myPropC;
1097 var myPropD;
1098 var myPropE;
1099 }'''));
1100 // prepare AngularComponentElement
1101 ClassElement classElement = mainUnitElement.getType("MyComponent");
1102 AngularComponentElement component =
1103 getAngularElement(classElement, (e) => e is AngularComponentElement);
1104 expect(component, isNotNull);
1105 // verify
1106 List<AngularPropertyElement> properties = component.properties;
1107 expect(properties, hasLength(5));
1108 _assertProperty(
1109 properties[0],
1110 "prop-a",
1111 findMainOffset("prop-a' :"),
1112 AngularPropertyKind.ATTR,
1113 "myPropA",
1114 findMainOffset("myPropA'"));
1115 _assertProperty(
1116 properties[1],
1117 "prop-b",
1118 findMainOffset("prop-b' :"),
1119 AngularPropertyKind.CALLBACK,
1120 "myPropB",
1121 findMainOffset("myPropB'"));
1122 _assertProperty(
1123 properties[2],
1124 "prop-c",
1125 findMainOffset("prop-c' :"),
1126 AngularPropertyKind.ONE_WAY,
1127 "myPropC",
1128 findMainOffset("myPropC'"));
1129 _assertProperty(
1130 properties[3],
1131 "prop-d",
1132 findMainOffset("prop-d' :"),
1133 AngularPropertyKind.ONE_WAY_ONE_TIME,
1134 "myPropD",
1135 findMainOffset("myPropD'"));
1136 _assertProperty(
1137 properties[4],
1138 "prop-e",
1139 findMainOffset("prop-e' :"),
1140 AngularPropertyKind.TWO_WAY,
1141 "myPropE",
1142 findMainOffset("myPropE'"));
1143 }
1144
1145 void test_NgComponent_properties_no() {
1146 contextHelper.addSource("/my_template.html", "");
1147 contextHelper.addSource("/my_styles.css", "");
1148 String mainContent = _createAngularSource(r'''
1149 @Component(publishAs: 'ctrl', selector: 'myComp',
1150 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
1151 class MyComponent {
1152 }''');
1153 resolveMainSourceNoErrors(mainContent);
1154 // prepare AngularComponentElement
1155 ClassElement classElement = mainUnitElement.getType("MyComponent");
1156 AngularComponentElement component =
1157 getAngularElement(classElement, (e) => e is AngularComponentElement);
1158 expect(component, isNotNull);
1159 // verify
1160 expect(component.name, "ctrl");
1161 expect(component.nameOffset, AngularTest.findOffset(mainContent, "ctrl'"));
1162 _assertIsTagSelector(component.selector, "myComp");
1163 expect(component.templateUri, "my_template.html");
1164 expect(
1165 component.templateUriOffset,
1166 AngularTest.findOffset(mainContent, "my_template.html'"));
1167 expect(component.styleUri, "my_styles.css");
1168 expect(
1169 component.styleUriOffset,
1170 AngularTest.findOffset(mainContent, "my_styles.css'"));
1171 expect(component.properties, hasLength(0));
1172 }
1173
1174 void test_NgComponent_scopeProperties() {
1175 contextHelper.addSource("/my_template.html", "");
1176 contextHelper.addSource("/my_styles.css", "");
1177 String mainContent = _createAngularSource(r'''
1178 @Component(publishAs: 'ctrl', selector: 'myComp',
1179 templateUrl: 'my_template.html', cssUrl: 'my_styles.css')
1180 class MyComponent {
1181 MyComponent(Scope scope) {
1182 scope.context['boolProp'] = true;
1183 scope.context['intProp'] = 42;
1184 scope.context['stringProp'] = 'foo';
1185 // duplicate is ignored
1186 scope.context['boolProp'] = true;
1187 // LHS is not an IndexExpression
1188 var v1;
1189 v1 = 1;
1190 // LHS is not a Scope access
1191 var v2;
1192 v2['name'] = 2;
1193 }
1194 }''');
1195 resolveMainSourceNoErrors(mainContent);
1196 // prepare AngularComponentElement
1197 ClassElement classElement = mainUnitElement.getType("MyComponent");
1198 AngularComponentElement component =
1199 getAngularElement(classElement, (e) => e is AngularComponentElement);
1200 expect(component, isNotNull);
1201 // verify
1202 List<AngularScopePropertyElement> scopeProperties =
1203 component.scopeProperties;
1204 expect(scopeProperties, hasLength(3));
1205 {
1206 AngularScopePropertyElement property = scopeProperties[0];
1207 expect(findMainElement2("boolProp"), same(property));
1208 expect(property.name, "boolProp");
1209 expect(
1210 property.nameOffset,
1211 AngularTest.findOffset(mainContent, "boolProp'"));
1212 expect(property.type.name, "bool");
1213 }
1214 {
1215 AngularScopePropertyElement property = scopeProperties[1];
1216 expect(findMainElement2("intProp"), same(property));
1217 expect(property.name, "intProp");
1218 expect(
1219 property.nameOffset,
1220 AngularTest.findOffset(mainContent, "intProp'"));
1221 expect(property.type.name, "int");
1222 }
1223 {
1224 AngularScopePropertyElement property = scopeProperties[2];
1225 expect(findMainElement2("stringProp"), same(property));
1226 expect(property.name, "stringProp");
1227 expect(
1228 property.nameOffset,
1229 AngularTest.findOffset(mainContent, "stringProp'"));
1230 expect(property.type.name, "String");
1231 }
1232 }
1233
1234 void test_NgController() {
1235 String mainContent = _createAngularSource(r'''
1236 @Controller(publishAs: 'ctrl', selector: '[myApp]')
1237 class MyController {
1238 }''');
1239 resolveMainSourceNoErrors(mainContent);
1240 // prepare AngularControllerElement
1241 ClassElement classElement = mainUnitElement.getType("MyController");
1242 AngularControllerElement controller =
1243 getAngularElement(classElement, (e) => e is AngularControllerElement);
1244 expect(controller, isNotNull);
1245 // verify
1246 expect(controller.name, "ctrl");
1247 expect(controller.nameOffset, AngularTest.findOffset(mainContent, "ctrl'"));
1248 _assertHasAttributeSelector(controller.selector, "myApp");
1249 }
1250
1251 void test_NgController_cannotParseSelector() {
1252 String mainContent = _createAngularSource(r'''
1253 @Controller(publishAs: 'ctrl', selector: '~unknown')
1254 class MyController {
1255 }''');
1256 resolveMainSource(mainContent);
1257 // has error
1258 assertMainErrors([AngularCode.CANNOT_PARSE_SELECTOR]);
1259 }
1260
1261 void test_NgController_missingPublishAs() {
1262 String mainContent = _createAngularSource(r'''
1263 @Controller(selector: '[myApp]')
1264 class MyController {
1265 }''');
1266 resolveMainSource(mainContent);
1267 // has error
1268 assertMainErrors([AngularCode.MISSING_PUBLISH_AS]);
1269 }
1270
1271 void test_NgController_missingSelector() {
1272 String mainContent = _createAngularSource(r'''
1273 @Controller(publishAs: 'ctrl')
1274 class MyController {
1275 }''');
1276 resolveMainSource(mainContent);
1277 // has error
1278 assertMainErrors([AngularCode.MISSING_SELECTOR]);
1279 }
1280
1281 void test_NgController_noAnnotationArguments() {
1282 String mainContent = _createAngularSource(r'''
1283 @NgController
1284 class MyController {
1285 }''');
1286 resolveMainSource(mainContent);
1287 }
1288
1289 void test_parseSelector_hasAttribute() {
1290 AngularSelectorElement selector =
1291 AngularCompilationUnitBuilder.parseSelector(42, "[name]");
1292 _assertHasAttributeSelector(selector, "name");
1293 expect(selector.nameOffset, 42 + 1);
1294 }
1295
1296 void test_parseSelector_hasClass() {
1297 AngularSelectorElement selector =
1298 AngularCompilationUnitBuilder.parseSelector(42, ".my-class");
1299 AngularHasClassSelectorElementImpl classSelector =
1300 selector as AngularHasClassSelectorElementImpl;
1301 expect(classSelector.name, "my-class");
1302 expect(classSelector.toString(), ".my-class");
1303 expect(selector.nameOffset, 42 + 1);
1304 // test apply()
1305 {
1306 ht.XmlTagNode node =
1307 HtmlFactory.tagNode("div", [HtmlFactory.attribute("class", "one two")] );
1308 expect(classSelector.apply(node), isFalse);
1309 }
1310 {
1311 ht.XmlTagNode node = HtmlFactory.tagNode(
1312 "div",
1313 [HtmlFactory.attribute("class", "one my-class two")]);
1314 expect(classSelector.apply(node), isTrue);
1315 }
1316 }
1317
1318 void test_parseSelector_isTag() {
1319 AngularSelectorElement selector =
1320 AngularCompilationUnitBuilder.parseSelector(42, "name");
1321 _assertIsTagSelector(selector, "name");
1322 expect(selector.nameOffset, 42);
1323 }
1324
1325 void test_parseSelector_isTag_hasAttribute() {
1326 AngularSelectorElement selector =
1327 AngularCompilationUnitBuilder.parseSelector(42, "tag[attr]");
1328 EngineTestCase.assertInstanceOf(
1329 (obj) => obj is IsTagHasAttributeSelectorElementImpl,
1330 IsTagHasAttributeSelectorElementImpl,
1331 selector);
1332 expect(selector.name, "tag[attr]");
1333 expect(selector.nameOffset, -1);
1334 expect((selector as IsTagHasAttributeSelectorElementImpl).tagName, "tag");
1335 expect(
1336 (selector as IsTagHasAttributeSelectorElementImpl).attributeName,
1337 "attr");
1338 }
1339
1340 void test_parseSelector_unknown() {
1341 AngularSelectorElement selector =
1342 AngularCompilationUnitBuilder.parseSelector(0, "~unknown");
1343 expect(selector, isNull);
1344 }
1345
1346 void test_view() {
1347 contextHelper.addSource("/wrong.html", "");
1348 contextHelper.addSource("/my_templateA.html", "");
1349 contextHelper.addSource("/my_templateB.html", "");
1350 String mainContent = _createAngularSource(r'''
1351 class MyRouteInitializer {
1352 init(ViewFactory view, foo) {
1353 foo.view('wrong.html'); // has target
1354 foo(); // less than one argument
1355 foo('wrong.html', 'bar'); // more than one argument
1356 foo('wrong' + '.html'); // not literal
1357 foo('wrong.html'); // not ViewFactory
1358 view('my_templateA.html');
1359 view('my_templateB.html');
1360 }
1361 }''');
1362 resolveMainSourceNoErrors(mainContent);
1363 // prepare AngularViewElement(s)
1364 List<AngularViewElement> views = mainUnitElement.angularViews;
1365 expect(views, hasLength(2));
1366 {
1367 AngularViewElement view = views[0];
1368 expect(view.templateUri, "my_templateA.html");
1369 expect(view.name, null);
1370 expect(view.nameOffset, -1);
1371 expect(
1372 view.templateUriOffset,
1373 AngularTest.findOffset(mainContent, "my_templateA.html'"));
1374 }
1375 {
1376 AngularViewElement view = views[1];
1377 expect(view.templateUri, "my_templateB.html");
1378 expect(view.name, null);
1379 expect(view.nameOffset, -1);
1380 expect(
1381 view.templateUriOffset,
1382 AngularTest.findOffset(mainContent, "my_templateB.html'"));
1383 }
1384 }
1385
1386 void _assertProperty(AngularPropertyElement property, String expectedName,
1387 int expectedNameOffset, AngularPropertyKind expectedKind,
1388 String expectedFieldName, int expectedFieldOffset) {
1389 expect(property.name, expectedName);
1390 expect(property.nameOffset, expectedNameOffset);
1391 expect(property.propertyKind, same(expectedKind));
1392 expect(property.field.name, expectedFieldName);
1393 expect(property.fieldNameOffset, expectedFieldOffset);
1394 }
1395
1396 /**
1397 * Find [AstNode] of the given type in [mainUnit].
1398 */
1399 AstNode _findMainNode(String search, Predicate<AstNode> predicate) {
1400 return EngineTestCase.findNode(mainUnit, mainContent, search, predicate);
1401 }
1402
1403 static AngularElement getAngularElement(Element element,
1404 Predicate<Element> predicate) {
1405 List<ToolkitObjectElement> toolkitObjects = null;
1406 if (element is ClassElement) {
1407 ClassElement classElement = element;
1408 toolkitObjects = classElement.toolkitObjects;
1409 }
1410 if (element is LocalVariableElement) {
1411 LocalVariableElement variableElement = element;
1412 toolkitObjects = variableElement.toolkitObjects;
1413 }
1414 if (toolkitObjects != null) {
1415 for (ToolkitObjectElement toolkitObject in toolkitObjects) {
1416 if (predicate(toolkitObject)) {
1417 return toolkitObject as AngularElement;
1418 }
1419 }
1420 }
1421 return null;
1422 }
1423
1424 static void _assertHasAttributeSelector(AngularSelectorElement selector,
1425 String name) {
1426 EngineTestCase.assertInstanceOf(
1427 (obj) => obj is HasAttributeSelectorElementImpl,
1428 HasAttributeSelectorElementImpl,
1429 selector);
1430 expect((selector as HasAttributeSelectorElementImpl).name, name);
1431 }
1432
1433 static void _assertIsTagSelector(AngularSelectorElement selector,
1434 String name) {
1435 EngineTestCase.assertInstanceOf(
1436 (obj) => obj is AngularTagSelectorElementImpl,
1437 AngularTagSelectorElementImpl,
1438 selector);
1439 expect((selector as AngularTagSelectorElementImpl).name, name);
1440 }
1441
1442 static String _createAngularSource(String code) {
1443 return "import 'angular.dart';\n" + code;
1444 }
1445 }
1446
1447
1448 class AngularHtmlUnitResolverTest extends AngularTest {
1449 void fail_analysisContext_changeDart_invalidateApplication() {
1450 addMainSource(r'''
1451
1452 import 'angular.dart';
1453
1454 @Component(
1455 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
1456 publishAs: 'ctrl',
1457 selector: 'myComponent')
1458 class MyComponent {
1459 }''');
1460 contextHelper.addSource(
1461 "/entry-point.html",
1462 AngularTest.createHtmlWithAngular(''));
1463 addIndexSource2("/my_template.html", r'''
1464 <div>
1465 {{ctrl.noMethod()}}
1466 </div>''');
1467 contextHelper.addSource("/my_styles.css", "");
1468 contextHelper.runTasks();
1469 // there are some errors in my_template.html
1470 {
1471 List<AnalysisError> errors = context.getErrors(indexSource).errors;
1472 expect(errors.length != 0, isTrue);
1473 }
1474 // change main.dart, there are no MyComponent anymore
1475 context.setContents(mainSource, "");
1476 // ...errors in my_template.html should be removed
1477 {
1478 List<AnalysisError> errors = context.getErrors(indexSource).errors;
1479 expect(errors, isEmpty);
1480 expect(errors.length == 0, isTrue);
1481 }
1482 }
1483
1484 void fail_ngRepeat_additionalVariables() {
1485 addMyController();
1486 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1487 <li ng-repeat='name in ctrl.names'>
1488 {{$index}} {{$first}} {{$middle}} {{$last}} {{$even}} {{$odd}}
1489 </li>'''));
1490 assertResolvedIdentifier2("\$index", "int");
1491 assertResolvedIdentifier2("\$first", "bool");
1492 assertResolvedIdentifier2("\$middle", "bool");
1493 assertResolvedIdentifier2("\$last", "bool");
1494 assertResolvedIdentifier2("\$even", "bool");
1495 assertResolvedIdentifier2("\$odd", "bool");
1496 }
1497
1498 void fail_ngRepeat_bad_expectedIdentifier() {
1499 addMyController();
1500 resolveIndex2(AngularTest.createHtmlWithMyController(r'''
1501 <li ng-repeat='name + 42 in ctrl.names'>
1502 </li>'''));
1503 assertErrors(indexSource, [AngularCode.INVALID_REPEAT_ITEM_SYNTAX]);
1504 }
1505
1506 void fail_ngRepeat_bad_expectedIn() {
1507 addMyController();
1508 resolveIndex2(AngularTest.createHtmlWithMyController(r'''
1509 <li ng-repeat='name : ctrl.names'>
1510 </li>'''));
1511 assertErrors(indexSource, [AngularCode.INVALID_REPEAT_SYNTAX]);
1512 }
1513
1514 void fail_ngRepeat_filters_filter_literal() {
1515 addMyController();
1516 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1517 <li ng-repeat='item in ctrl.items | filter:42:null'/>
1518 </li>'''));
1519 // filter "filter" is resolved
1520 Element filterElement = assertResolvedIdentifier("filter");
1521 EngineTestCase.assertInstanceOf(
1522 (obj) => obj is AngularFormatterElement,
1523 AngularFormatterElement,
1524 filterElement);
1525 }
1526
1527 void fail_ngRepeat_filters_filter_propertyMap() {
1528 addMyController();
1529 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1530 <li ng-repeat='item in ctrl.items | filter:{name:null, done:false}'/>
1531 </li>'''));
1532 assertResolvedIdentifier2("name:", "String");
1533 assertResolvedIdentifier2("done:", "bool");
1534 }
1535
1536 void fail_ngRepeat_filters_missingColon() {
1537 addMyController();
1538 resolveIndex2(AngularTest.createHtmlWithMyController(r'''
1539 <li ng-repeat="item in ctrl.items | orderBy:'' true"/>
1540 </li>'''));
1541 assertErrors(indexSource, [AngularCode.MISSING_FORMATTER_COLON]);
1542 }
1543
1544 void fail_ngRepeat_filters_noArgs() {
1545 addMyController();
1546 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1547 <li ng-repeat="item in ctrl.items | orderBy"/>
1548 </li>'''));
1549 // filter "orderBy" is resolved
1550 Element filterElement = assertResolvedIdentifier("orderBy");
1551 EngineTestCase.assertInstanceOf(
1552 (obj) => obj is AngularFormatterElement,
1553 AngularFormatterElement,
1554 filterElement);
1555 }
1556
1557 void fail_ngRepeat_filters_orderBy_emptyString() {
1558 addMyController();
1559 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1560 <li ng-repeat="item in ctrl.items | orderBy:'':true"/>
1561 </li>'''));
1562 // filter "orderBy" is resolved
1563 Element filterElement = assertResolvedIdentifier("orderBy");
1564 EngineTestCase.assertInstanceOf(
1565 (obj) => obj is AngularFormatterElement,
1566 AngularFormatterElement,
1567 filterElement);
1568 }
1569
1570 void fail_ngRepeat_filters_orderBy_propertyList() {
1571 addMyController();
1572 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1573 <li ng-repeat="item in ctrl.items | orderBy:['name', 'done']"/>
1574 </li>'''));
1575 assertResolvedIdentifier2("name'", "String");
1576 assertResolvedIdentifier2("done'", "bool");
1577 }
1578
1579 void fail_ngRepeat_filters_orderBy_propertyName() {
1580 addMyController();
1581 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1582 <li ng-repeat="item in ctrl.items | orderBy:'name'"/>
1583 </li>'''));
1584 assertResolvedIdentifier2("name'", "String");
1585 }
1586
1587 void fail_ngRepeat_filters_orderBy_propertyName_minus() {
1588 addMyController();
1589 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1590 <li ng-repeat="item in ctrl.items | orderBy:'-name'"/>
1591 </li>'''));
1592 assertResolvedIdentifier2("name'", "String");
1593 }
1594
1595 void fail_ngRepeat_filters_orderBy_propertyName_plus() {
1596 addMyController();
1597 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1598 <li ng-repeat="item in ctrl.items | orderBy:'+name'"/>
1599 </li>'''));
1600 assertResolvedIdentifier2("name'", "String");
1601 }
1602
1603 void fail_ngRepeat_filters_orderBy_propertyName_untypedItems() {
1604 addMyController();
1605 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1606 <li ng-repeat="item in ctrl.untypedItems | orderBy:'name'"/>
1607 </li>'''));
1608 assertResolvedIdentifier2("name'", "dynamic");
1609 }
1610
1611 void fail_ngRepeat_filters_two() {
1612 addMyController();
1613 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1614 <li ng-repeat="item in ctrl.items | orderBy:'+' | orderBy:'-'"/>
1615 </li>'''));
1616 EngineTestCase.assertInstanceOf(
1617 (obj) => obj is AngularFormatterElement,
1618 AngularFormatterElement,
1619 assertResolvedIdentifier("orderBy:'+'"));
1620 EngineTestCase.assertInstanceOf(
1621 (obj) => obj is AngularFormatterElement,
1622 AngularFormatterElement,
1623 assertResolvedIdentifier("orderBy:'-'"));
1624 }
1625
1626 void fail_ngRepeat_resolvedExpressions() {
1627 addMyController();
1628 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1629 <li ng-repeat='name in ctrl.names'>
1630 {{name}}
1631 </li>'''));
1632 assertResolvedIdentifier2("name in", "String");
1633 assertResolvedIdentifier2("ctrl.", "MyController");
1634 assertResolvedIdentifier2("names'", "List<String>");
1635 assertResolvedIdentifier2("name}}", "String");
1636 }
1637
1638 void fail_ngRepeat_trackBy() {
1639 addMyController();
1640 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1641 <li ng-repeat='name in ctrl.names track by name.length'/>
1642 </li>'''));
1643 assertResolvedIdentifier2("length'", "int");
1644 }
1645
1646 void test_analysisContext_changeEntryPoint_clearAngularErrors_inDart() {
1647 addMainSource(r'''
1648
1649 import 'angular.dart';
1650
1651 @Component(
1652 templateUrl: 'no-such-template.html', cssUrl: 'my_styles.css',
1653 publishAs: 'ctrl',
1654 selector: 'myComponent')
1655 class MyComponent {
1656 }''');
1657 Source entrySource = contextHelper.addSource(
1658 "/entry-point.html",
1659 AngularTest.createHtmlWithAngular(''));
1660 contextHelper.addSource("/my_styles.css", "");
1661 contextHelper.runTasks();
1662 // there are some errors in MyComponent
1663 {
1664 List<AnalysisError> errors = context.getErrors(mainSource).errors;
1665 expect(errors.length != 0, isTrue);
1666 }
1667 // make entry-point.html non-Angular
1668 context.setContents(entrySource, "<html/>");
1669 // ...errors in MyComponent should be removed
1670 {
1671 List<AnalysisError> errors = context.getErrors(mainSource).errors;
1672 expect(errors.length == 0, isTrue);
1673 }
1674 }
1675
1676 void test_analysisContext_changeEntryPoint_clearAngularErrors_inTemplate() {
1677 addMainSource(r'''
1678
1679 import 'angular.dart';
1680
1681 @Component(
1682 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
1683 publishAs: 'ctrl',
1684 selector: 'myComponent')
1685 class MyComponent {
1686 }''');
1687 Source entrySource = contextHelper.addSource(
1688 "/entry-point.html",
1689 AngularTest.createHtmlWithAngular(''));
1690 addIndexSource2("/my_template.html", r'''
1691 <div>
1692 {{ctrl.noMethod()}}
1693 </div>''');
1694 contextHelper.addSource("/my_styles.css", "");
1695 contextHelper.runTasks();
1696 // there are some errors in my_template.html
1697 {
1698 List<AnalysisError> errors = context.getErrors(indexSource).errors;
1699 expect(errors.length != 0, isTrue);
1700 }
1701 // make entry-point.html non-Angular
1702 context.setContents(entrySource, "<html/>");
1703 // ...errors in my_template.html should be removed
1704 {
1705 List<AnalysisError> errors = context.getErrors(indexSource).errors;
1706 expect(errors.length == 0, isTrue);
1707 }
1708 }
1709
1710 void test_analysisContext_removeEntryPoint_clearAngularErrors_inDart() {
1711 addMainSource(r'''
1712
1713 import 'angular.dart';
1714
1715 @Component(
1716 templateUrl: 'no-such-template.html', cssUrl: 'my_styles.css',
1717 publishAs: 'ctrl',
1718 selector: 'myComponent')
1719 class MyComponent {
1720 }''');
1721 Source entrySource = contextHelper.addSource(
1722 "/entry-point.html",
1723 AngularTest.createHtmlWithAngular(''));
1724 contextHelper.addSource("/my_styles.css", "");
1725 contextHelper.runTasks();
1726 // there are some errors in MyComponent
1727 {
1728 List<AnalysisError> errors = context.getErrors(mainSource).errors;
1729 expect(errors.length != 0, isTrue);
1730 }
1731 // remove entry-point.html
1732 {
1733 ChangeSet changeSet = new ChangeSet();
1734 changeSet.removedSource(entrySource);
1735 context.applyChanges(changeSet);
1736 }
1737 // ...errors in MyComponent should be removed
1738 {
1739 List<AnalysisError> errors = context.getErrors(mainSource).errors;
1740 expect(errors.length == 0, isTrue);
1741 }
1742 }
1743
1744 void test_contextProperties() {
1745 addMyController();
1746 _resolveIndexNoErrors(AngularTest.createHtmlWithAngular(r'''
1747 <div>
1748 {{$id}}
1749 {{$parent}}
1750 {{$root}}
1751 </div>'''));
1752 assertResolvedIdentifier("\$id");
1753 assertResolvedIdentifier("\$parent");
1754 assertResolvedIdentifier("\$root");
1755 }
1756
1757 void test_getAngularElement_isAngular() {
1758 // prepare local variable "name" in compilation unit
1759 CompilationUnitElementImpl unit =
1760 ElementFactory.compilationUnit("test.dart");
1761 FunctionElementImpl function = ElementFactory.functionElement("main");
1762 unit.functions = <FunctionElement>[function];
1763 LocalVariableElementImpl local =
1764 ElementFactory.localVariableElement2("name");
1765 function.localVariables = <LocalVariableElement>[local];
1766 // set AngularElement
1767 AngularElement angularElement = new AngularControllerElementImpl("ctrl", 0);
1768 local.toolkitObjects = <AngularElement>[angularElement];
1769 expect(
1770 AngularHtmlUnitResolver.getAngularElement(local),
1771 same(angularElement));
1772 }
1773
1774 void test_getAngularElement_notAngular() {
1775 Element element = ElementFactory.localVariableElement2("name");
1776 expect(AngularHtmlUnitResolver.getAngularElement(element), isNull);
1777 }
1778
1779 void test_getAngularElement_notLocal() {
1780 Element element = ElementFactory.classElement2("Test");
1781 expect(AngularHtmlUnitResolver.getAngularElement(element), isNull);
1782 }
1783
1784 /**
1785 * Test that we resolve "ng-click" expression.
1786 */
1787 void test_ngClick() {
1788 addMyController();
1789 _resolveIndexNoErrors(
1790 AngularTest.createHtmlWithMyController(
1791 r"<button ng-click='ctrl.doSomething($event)'/>"));
1792 assertResolvedIdentifier("doSomething");
1793 }
1794
1795 void test_NgComponent_resolveTemplateFile() {
1796 addMainSource(r'''
1797 import 'angular.dart';
1798
1799 @Component(
1800 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
1801 publishAs: 'ctrl',
1802 selector: 'myComponent')
1803 class MyComponent {
1804 String field;
1805 }''');
1806 contextHelper.addSource(
1807 "/entry-point.html",
1808 AngularTest.createHtmlWithAngular(''));
1809 addIndexSource2("/my_template.html", r'''
1810 <div>
1811 {{ctrl.field}}
1812 </div>''');
1813 contextHelper.addSource("/my_styles.css", "");
1814 contextHelper.runTasks();
1815 resolveIndex();
1816 assertNoErrors();
1817 assertResolvedIdentifier2("ctrl.", "MyComponent");
1818 assertResolvedIdentifier2("field}}", "String");
1819 }
1820
1821 void test_NgComponent_updateDartFile() {
1822 Source componentSource = contextHelper.addSource("/my_component.dart", r'''
1823 library my.component;
1824 import 'angular.dart';
1825 @Component(selector: 'myComponent')
1826 class MyComponent {
1827 }''');
1828 contextHelper.addSource("/my_module.dart", r'''
1829 library my.module;
1830 import 'my_component.dart';''');
1831 addMainSource(r'''
1832 library main;
1833 import 'my_module.dart';''');
1834 _resolveIndexNoErrors(
1835 AngularTest.createHtmlWithMyController("<myComponent/>"));
1836 // "myComponent" tag was resolved
1837 {
1838 ht.XmlTagNode tagNode =
1839 ht.HtmlUnitUtils.getTagNode(indexUnit, findOffset2("myComponent"));
1840 AngularSelectorElement tagElement =
1841 tagNode.element as AngularSelectorElement;
1842 expect(tagElement, isNotNull);
1843 expect(tagElement.name, "myComponent");
1844 }
1845 // replace "myComponent" with "myComponent2"
1846 // in my_component.dart and index.html
1847 {
1848 context.setContents(
1849 componentSource,
1850 _getSourceContent(componentSource).replaceAll("myComponent", "myCompon ent2"));
1851 indexContent =
1852 _getSourceContent(indexSource).replaceAll("myComponent", "myComponent2 ");
1853 context.setContents(indexSource, indexContent);
1854 }
1855 contextHelper.runTasks();
1856 resolveIndex();
1857 // "myComponent2" tag should be resolved
1858 {
1859 ht.XmlTagNode tagNode =
1860 ht.HtmlUnitUtils.getTagNode(indexUnit, findOffset2("myComponent2"));
1861 AngularSelectorElement tagElement =
1862 tagNode.element as AngularSelectorElement;
1863 expect(tagElement, isNotNull);
1864 expect(tagElement.name, "myComponent2");
1865 }
1866 }
1867
1868 void test_NgComponent_use_resolveAttributes() {
1869 contextHelper.addSource("/my_template.html", r'''
1870 <div>
1871 {{ctrl.field}}
1872 </div>''');
1873 addMainSource(r'''
1874
1875 import 'angular.dart';
1876
1877 @Component(
1878 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
1879 publishAs: 'ctrl',
1880 selector: 'myComponent', // selector
1881 map: const {'attrA' : '=>setA', 'attrB' : '@setB'})
1882 class MyComponent {
1883 set setA(value) {}
1884 set setB(value) {}
1885 }''');
1886 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1887 <input type='text' ng-model='someModel'/>
1888 <myComponent attrA='someModel' attrB='bbb'/>'''));
1889 // "attrA" attribute expression was resolved
1890 expect(findIdentifier("someModel"), isNotNull);
1891 // "myComponent" tag was resolved
1892 ht.XmlTagNode tagNode =
1893 ht.HtmlUnitUtils.getTagNode(indexUnit, findOffset2("myComponent"));
1894 AngularSelectorElement tagElement =
1895 tagNode.element as AngularSelectorElement;
1896 expect(tagElement, isNotNull);
1897 expect(tagElement.name, "myComponent");
1898 expect(tagElement.nameOffset, findMainOffset("myComponent', // selector"));
1899 // "attrA" attribute was resolved
1900 {
1901 ht.XmlAttributeNode node =
1902 ht.HtmlUnitUtils.getAttributeNode(indexUnit, findOffset2("attrA='"));
1903 AngularPropertyElement element = node.element as AngularPropertyElement;
1904 expect(element, isNotNull);
1905 expect(element.name, "attrA");
1906 expect(element.field.name, "setA");
1907 }
1908 // "attrB" attribute was resolved, even if it @binding
1909 {
1910 ht.XmlAttributeNode node =
1911 ht.HtmlUnitUtils.getAttributeNode(indexUnit, findOffset2("attrB='"));
1912 AngularPropertyElement element = node.element as AngularPropertyElement;
1913 expect(element, isNotNull);
1914 expect(element.name, "attrB");
1915 expect(element.field.name, "setB");
1916 }
1917 }
1918
1919 void test_NgDirective_noAttribute() {
1920 addMainSource(r'''
1921
1922 import 'angular.dart';
1923
1924 @NgDirective(selector: '[my-directive]', map: const {'foo': '=>input'})
1925 class MyDirective {
1926 set input(value) {}
1927 }''');
1928 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1929 <div my-directive>
1930 </div>'''));
1931 }
1932
1933 void test_NgDirective_noExpression() {
1934 addMainSource(r'''
1935
1936 import 'angular.dart';
1937
1938 @NgDirective(selector: '[my-directive]', map: const {'.': '=>input'})
1939 class MyDirective {
1940 set input(value) {}
1941 }''');
1942 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1943 <div my-directive>
1944 </div>'''));
1945 }
1946
1947 void test_NgDirective_resolvedExpression() {
1948 addMainSource(r'''
1949
1950 import 'angular.dart';
1951
1952 @Decorator(selector: '[my-directive]')
1953 class MyDirective {
1954 @NgOneWay('my-property')
1955 String condition;
1956 }''');
1957 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1958 <input type='text' ng-model='name'>
1959 <div my-directive my-property='name != null'>
1960 </div>'''));
1961 resolveMainNoErrors();
1962 // "my-directive" attribute was resolved
1963 {
1964 AngularSelectorElement selector =
1965 findMainElement(ElementKind.ANGULAR_SELECTOR, "my-directive");
1966 ht.XmlAttributeNode attrNodeSelector =
1967 ht.HtmlUnitUtils.getAttributeNode(indexUnit, findOffset2("my-directive "));
1968 expect(attrNodeSelector, isNotNull);
1969 expect(attrNodeSelector.element, same(selector));
1970 }
1971 // "my-property" attribute was resolved
1972 {
1973 ht.XmlAttributeNode attrNodeProperty =
1974 ht.HtmlUnitUtils.getAttributeNode(indexUnit, findOffset2("my-property= '"));
1975 AngularPropertyElement propertyElement =
1976 attrNodeProperty.element as AngularPropertyElement;
1977 expect(propertyElement, isNotNull);
1978 expect(propertyElement.propertyKind, same(AngularPropertyKind.ONE_WAY));
1979 expect(propertyElement.field.name, "condition");
1980 }
1981 // "name" expression was resolved
1982 expect(findIdentifier("name != null"), isNotNull);
1983 }
1984
1985 void test_NgDirective_resolvedExpression_attrString() {
1986 addMainSource(r'''
1987
1988 import 'angular.dart';
1989
1990 @NgDirective(selector: '[my-directive])
1991 class MyDirective {
1992 @NgAttr('my-property')
1993 String property;
1994 }''');
1995 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
1996 <input type='text' ng-model='name'>
1997 <div my-directive my-property='name != null'>
1998 </div>'''));
1999 resolveMain();
2000 // @NgAttr means "string attribute", which we don't parse
2001 expect(findIdentifierMaybe("name != null"), isNull);
2002 }
2003
2004 void test_NgDirective_resolvedExpression_dotAsName() {
2005 addMainSource(r'''
2006
2007 import 'angular.dart';
2008
2009 @Decorator(
2010 selector: '[my-directive]',
2011 map: const {'.' : '=>condition'})
2012 class MyDirective {
2013 set condition(value) {}
2014 }''');
2015 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
2016 <input type='text' ng-model='name'>
2017 <div my-directive='name != null'>
2018 </div>'''));
2019 // "name" attribute was resolved
2020 expect(findIdentifier("name != null"), isNotNull);
2021 }
2022
2023 /**
2024 * Test that we resolve "ng-if" expression.
2025 */
2026 void test_ngIf() {
2027 addMyController();
2028 _resolveIndexNoErrors(
2029 AngularTest.createHtmlWithMyController("<div ng-if='ctrl.field != null'/ >"));
2030 assertResolvedIdentifier("field");
2031 }
2032
2033 void test_ngModel_modelAfterUsage() {
2034 addMyController();
2035 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
2036 <h3>Hello {{name}}!</h3>
2037 <input type='text' ng-model='name'>'''));
2038 assertResolvedIdentifier2("name}}!", "String");
2039 assertResolvedIdentifier2("name'>", "String");
2040 }
2041
2042 void test_ngModel_modelBeforeUsage() {
2043 addMyController();
2044 _resolveIndexNoErrors(AngularTest.createHtmlWithMyController(r'''
2045 <input type='text' ng-model='name'>
2046 <h3>Hello {{name}}!</h3>'''));
2047 assertResolvedIdentifier2("name}}!", "String");
2048 Element element = assertResolvedIdentifier2("name'>", "String");
2049 expect(element.name, "name");
2050 expect(element.nameOffset, findOffset2("name'>"));
2051 }
2052
2053 void test_ngModel_notIdentifier() {
2054 addMyController();
2055 _resolveIndexNoErrors(
2056 AngularTest.createHtmlWithMyController(
2057 "<input type='text' ng-model='ctrl.field'>"));
2058 assertResolvedIdentifier2("field'>", "String");
2059 }
2060
2061 /**
2062 * Test that we resolve "ng-mouseout" expression.
2063 */
2064 void test_ngMouseOut() {
2065 addMyController();
2066 _resolveIndexNoErrors(
2067 AngularTest.createHtmlWithMyController(
2068 r"<button ng-mouseout='ctrl.doSomething($event)'/>"));
2069 assertResolvedIdentifier("doSomething");
2070 }
2071
2072 /**
2073 * Test that we resolve "ng-show" expression.
2074 */
2075 void test_ngShow() {
2076 addMyController();
2077 _resolveIndexNoErrors(
2078 AngularTest.createHtmlWithMyController("<div ng-show='ctrl.field != null '/>"));
2079 assertResolvedIdentifier("field");
2080 }
2081
2082 void test_notResolved_noDartScript() {
2083 resolveIndex2(r'''
2084 <html ng-app>
2085 <body>
2086 <div my-marker>
2087 {{ctrl.field}}
2088 </div>
2089 </body>
2090 </html>''');
2091 assertNoErrors();
2092 // Angular is not initialized, so "ctrl" is not parsed
2093 Expression expression =
2094 ht.HtmlUnitUtils.getExpression(indexUnit, findOffset2("ctrl"));
2095 expect(expression, isNull);
2096 }
2097
2098 void test_notResolved_notAngular() {
2099 resolveIndex2(r'''
2100 <html no-ng-app>
2101 <body>
2102 <div my-marker>
2103 {{ctrl.field}}
2104 </div>
2105 </body>
2106 </html>''');
2107 assertNoErrors();
2108 // Angular is not initialized, so "ctrl" is not parsed
2109 Expression expression =
2110 ht.HtmlUnitUtils.getExpression(indexUnit, findOffset2("ctrl"));
2111 expect(expression, isNull);
2112 }
2113
2114 void test_notResolved_wrongControllerMarker() {
2115 addMyController();
2116 addIndexSource(r'''
2117 <html ng-app>
2118 <body>
2119 <div not-my-marker>
2120 {{ctrl.field}}
2121 </div>
2122 <script type='application/dart' src='main.dart'></script>
2123 </body>
2124 </html>''');
2125 contextHelper.runTasks();
2126 resolveIndex();
2127 // no errors, because we decided to ignore them at the moment
2128 assertNoErrors();
2129 // "ctrl" is not resolved
2130 SimpleIdentifier identifier = findIdentifier("ctrl");
2131 expect(identifier.bestElement, isNull);
2132 }
2133
2134 void test_resolveExpression_evenWithout_ngBootstrap() {
2135 resolveMainSource(r'''
2136
2137 import 'angular.dart';
2138
2139 @Controller(
2140 selector: '[my-controller]',
2141 publishAs: 'ctrl')
2142 class MyController {
2143 String field;
2144 }''');
2145 _resolveIndexNoErrors(r'''
2146 <html ng-app>
2147 <body>
2148 <div my-controller>
2149 {{ctrl.field}}
2150 </div>
2151 <script type='application/dart' src='main.dart'></script>
2152 </body>
2153 </html>''');
2154 assertResolvedIdentifier2("ctrl.", "MyController");
2155 }
2156
2157 void test_resolveExpression_ignoreUnresolved() {
2158 resolveMainSource(r'''
2159
2160 import 'angular.dart';
2161
2162 @Controller(
2163 selector: '[my-controller]',
2164 publishAs: 'ctrl')
2165 class MyController {
2166 Map map;
2167 Object obj;
2168 }''');
2169 resolveIndex2(r'''
2170 <html ng-app>
2171 <body>
2172 <div my-controller>
2173 {{ctrl.map.property}}
2174 {{ctrl.obj.property}}
2175 {{invisibleScopeProperty}}
2176 </div>
2177 <script type='application/dart' src='main.dart'></script>
2178 </body>
2179 </html>''');
2180 assertNoErrors();
2181 // "ctrl.map" and "ctrl.obj" are resolved
2182 assertResolvedIdentifier2("map", "Map<dynamic, dynamic>");
2183 assertResolvedIdentifier2("obj", "Object");
2184 // ...but not "invisibleScopeProperty"
2185 {
2186 SimpleIdentifier identifier = findIdentifier("invisibleScopeProperty");
2187 expect(identifier.bestElement, isNull);
2188 }
2189 }
2190
2191 void test_resolveExpression_inAttribute() {
2192 addMyController();
2193 _resolveIndexNoErrors(
2194 AngularTest.createHtmlWithMyController(
2195 "<button title='{{ctrl.field}}'></button>"));
2196 assertResolvedIdentifier2("ctrl", "MyController");
2197 }
2198
2199 void test_resolveExpression_ngApp_onBody() {
2200 addMyController();
2201 _resolveIndexNoErrors(r'''
2202 <html>
2203 <body ng-app>
2204 <div my-controller>
2205 {{ctrl.field}}
2206 </div>
2207 <script type='application/dart' src='main.dart'></script>
2208 </body>
2209 </html>''');
2210 assertResolvedIdentifier2("ctrl", "MyController");
2211 }
2212
2213 void test_resolveExpression_withFormatter() {
2214 addMyController();
2215 _resolveIndexNoErrors(
2216 AngularTest.createHtmlWithMyController("{{ctrl.field | uppercase}}"));
2217 assertResolvedIdentifier2("ctrl", "MyController");
2218 assertResolvedIdentifier("uppercase");
2219 }
2220
2221 void test_resolveExpression_withFormatter_missingColon() {
2222 addMyController();
2223 resolveIndex2(
2224 AngularTest.createHtmlWithMyController(
2225 "{{ctrl.field | uppercase, lowercase}}"));
2226 assertErrors(indexSource, [AngularCode.MISSING_FORMATTER_COLON]);
2227 }
2228
2229 void test_resolveExpression_withFormatter_notSimpleIdentifier() {
2230 addMyController();
2231 resolveIndex2(
2232 AngularTest.createHtmlWithMyController("{{ctrl.field | not.supported}}") );
2233 assertErrors(indexSource, [AngularCode.INVALID_FORMATTER_NAME]);
2234 }
2235
2236 void test_scopeProperties() {
2237 addMainSource(r'''
2238
2239 import 'angular.dart';
2240
2241 @Component(
2242 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
2243 publishAs: 'ctrl',
2244 selector: 'myComponent')
2245 class MyComponent {
2246 String field;
2247 MyComponent(Scope scope) {
2248 scope.context['scopeProperty'] = 'abc';
2249 }
2250 }
2251 ''');
2252 contextHelper.addSource(
2253 "/entry-point.html",
2254 AngularTest.createHtmlWithAngular(''));
2255 addIndexSource2("/my_template.html", r'''
2256 <div>
2257 {{scopeProperty}}
2258 </div>''');
2259 contextHelper.addSource("/my_styles.css", "");
2260 contextHelper.runTasks();
2261 resolveIndex();
2262 assertNoErrors();
2263 // "scopeProperty" is resolved
2264 Element element = assertResolvedIdentifier2("scopeProperty}}", "String");
2265 EngineTestCase.assertInstanceOf(
2266 (obj) => obj is AngularScopePropertyElement,
2267 AngularScopePropertyElement,
2268 AngularHtmlUnitResolver.getAngularElement(element));
2269 }
2270
2271 void test_scopeProperties_hideWithComponent() {
2272 addMainSource(r'''
2273
2274 import 'angular.dart';
2275
2276 @Component(
2277 templateUrl: 'my_template.html', cssUrl: 'my_styles.css',
2278 publishAs: 'ctrl',
2279 selector: 'myComponent')
2280 class MyComponent {
2281 }
2282
2283 void setScopeProperties(Scope scope) {
2284 scope.context['ctrl'] = 1;
2285 }
2286 ''');
2287 contextHelper.addSource(
2288 "/entry-point.html",
2289 AngularTest.createHtmlWithAngular(''));
2290 addIndexSource2("/my_template.html", r'''
2291 <div>
2292 {{ctrl}}
2293 </div>''');
2294 contextHelper.addSource("/my_styles.css", "");
2295 contextHelper.runTasks();
2296 resolveIndex();
2297 assertNoErrors();
2298 // "ctrl" is resolved
2299 LocalVariableElement element =
2300 assertResolvedIdentifier("ctrl}}") as LocalVariableElement;
2301 List<ToolkitObjectElement> toolkitObjects = element.toolkitObjects;
2302 EngineTestCase.assertInstanceOf(
2303 (obj) => obj is AngularComponentElement,
2304 AngularComponentElement,
2305 toolkitObjects[0]);
2306 }
2307
2308 void test_view_resolveTemplateFile() {
2309 addMainSource(r'''
2310
2311 import 'angular.dart';
2312
2313 @Controller(
2314 selector: '[my-controller]',
2315 publishAs: 'ctrl')
2316 class MyController {
2317 String field;
2318 }
2319
2320 class MyRouteInitializer {
2321 init(ViewFactory view) {
2322 view('my_template.html');
2323 }
2324 }''');
2325 contextHelper.addSource(
2326 "/entry-point.html",
2327 AngularTest.createHtmlWithAngular(''));
2328 addIndexSource2("/my_template.html", r'''
2329 <div my-controller>
2330 {{ctrl.field}}
2331 </div>''');
2332 contextHelper.addSource("/my_styles.css", "");
2333 contextHelper.runTasks();
2334 resolveIndex();
2335 assertNoErrors();
2336 assertResolvedIdentifier2("ctrl.", "MyController");
2337 assertResolvedIdentifier2("field}}", "String");
2338 }
2339
2340 String _getSourceContent(Source source) {
2341 return context.getContents(source).data.toString();
2342 }
2343
2344 void _resolveIndexNoErrors(String content) {
2345 resolveIndex2(content);
2346 assertNoErrors();
2347 verify([indexSource]);
2348 }
2349 }
2350
2351
2352 /**
2353 * Tests for [HtmlUnitUtils] for Angular HTMLs.
2354 */
2355 class AngularHtmlUnitUtilsTest extends AngularTest {
2356 void test_getElement_forExpression() {
2357 addMyController();
2358 _resolveSimpleCtrlFieldHtml();
2359 // prepare expression
2360 int offset = indexContent.indexOf("ctrl");
2361 Expression expression = ht.HtmlUnitUtils.getExpression(indexUnit, offset);
2362 // get element
2363 Element element = ht.HtmlUnitUtils.getElement(expression);
2364 EngineTestCase.assertInstanceOf(
2365 (obj) => obj is VariableElement,
2366 VariableElement,
2367 element);
2368 expect(element.name, "ctrl");
2369 }
2370
2371 void test_getElement_forExpression_null() {
2372 Element element = ht.HtmlUnitUtils.getElement(null);
2373 expect(element, isNull);
2374 }
2375
2376 void test_getElement_forOffset() {
2377 addMyController();
2378 _resolveSimpleCtrlFieldHtml();
2379 // no expression
2380 {
2381 Element element = ht.HtmlUnitUtils.getElementAtOffset(indexUnit, 0);
2382 expect(element, isNull);
2383 }
2384 // has expression at offset
2385 {
2386 int offset = indexContent.indexOf("field");
2387 Element element = ht.HtmlUnitUtils.getElementAtOffset(indexUnit, offset);
2388 EngineTestCase.assertInstanceOf(
2389 (obj) => obj is PropertyAccessorElement,
2390 PropertyAccessorElement,
2391 element);
2392 expect(element.name, "field");
2393 }
2394 }
2395
2396 void test_getElementToOpen_controller() {
2397 addMyController();
2398 _resolveSimpleCtrlFieldHtml();
2399 // prepare expression
2400 int offset = indexContent.indexOf("ctrl");
2401 Expression expression = ht.HtmlUnitUtils.getExpression(indexUnit, offset);
2402 // get element
2403 Element element = ht.HtmlUnitUtils.getElementToOpen(indexUnit, expression);
2404 EngineTestCase.assertInstanceOf(
2405 (obj) => obj is AngularControllerElement,
2406 AngularControllerElement,
2407 element);
2408 expect(element.name, "ctrl");
2409 }
2410
2411 void test_getElementToOpen_field() {
2412 addMyController();
2413 _resolveSimpleCtrlFieldHtml();
2414 // prepare expression
2415 int offset = indexContent.indexOf("field");
2416 Expression expression = ht.HtmlUnitUtils.getExpression(indexUnit, offset);
2417 // get element
2418 Element element = ht.HtmlUnitUtils.getElementToOpen(indexUnit, expression);
2419 EngineTestCase.assertInstanceOf(
2420 (obj) => obj is PropertyAccessorElement,
2421 PropertyAccessorElement,
2422 element);
2423 expect(element.name, "field");
2424 }
2425
2426 void test_getEnclosingTagNode() {
2427 resolveIndex2(r'''
2428 <html>
2429 <body ng-app>
2430 <badge name='abc'> 123 </badge>
2431 </body>
2432 </html>''');
2433 // no unit
2434 expect(ht.HtmlUnitUtils.getEnclosingTagNode(null, 0), isNull);
2435 // wrong offset
2436 expect(ht.HtmlUnitUtils.getEnclosingTagNode(indexUnit, -1), isNull);
2437 // valid offset
2438 ht.XmlTagNode expected = _getEnclosingTagNode("<badge");
2439 expect(expected, isNotNull);
2440 expect(expected.tag, "badge");
2441 expect(_getEnclosingTagNode("badge"), same(expected));
2442 expect(_getEnclosingTagNode("name="), same(expected));
2443 expect(_getEnclosingTagNode("123"), same(expected));
2444 expect(_getEnclosingTagNode("/badge"), same(expected));
2445 }
2446
2447 void test_getExpression() {
2448 addMyController();
2449 _resolveSimpleCtrlFieldHtml();
2450 // try offset without expression
2451 expect(ht.HtmlUnitUtils.getExpression(indexUnit, 0), isNull);
2452 // try offset with expression
2453 int offset = indexContent.indexOf("ctrl");
2454 expect(ht.HtmlUnitUtils.getExpression(indexUnit, offset), isNotNull);
2455 expect(ht.HtmlUnitUtils.getExpression(indexUnit, offset + 1), isNotNull);
2456 expect(ht.HtmlUnitUtils.getExpression(indexUnit, offset + 2), isNotNull);
2457 expect(
2458 ht.HtmlUnitUtils.getExpression(indexUnit, offset + "ctrl.field".length),
2459 isNotNull);
2460 // try without unit
2461 expect(ht.HtmlUnitUtils.getExpression(null, offset), isNull);
2462 }
2463
2464 void test_getTagNode() {
2465 resolveIndex2(r'''
2466 <html>
2467 <body ng-app>
2468 <badge name='abc'> 123 </badge> done
2469 </body>
2470 </html>''');
2471 // no unit
2472 expect(ht.HtmlUnitUtils.getTagNode(null, 0), isNull);
2473 // wrong offset
2474 expect(ht.HtmlUnitUtils.getTagNode(indexUnit, -1), isNull);
2475 // on tag name
2476 ht.XmlTagNode expected = _getTagNode("badge name=");
2477 expect(expected, isNotNull);
2478 expect(expected.tag, "badge");
2479 expect(_getTagNode("badge"), same(expected));
2480 expect(_getTagNode(" name="), same(expected));
2481 expect(_getTagNode("adge name="), same(expected));
2482 expect(_getTagNode("badge>"), same(expected));
2483 expect(_getTagNode("adge>"), same(expected));
2484 expect(_getTagNode("> done"), same(expected));
2485 // in tag node, but not on the name token
2486 expect(_getTagNode("name="), isNull);
2487 expect(_getTagNode("123"), isNull);
2488 }
2489
2490 ht.XmlTagNode _getEnclosingTagNode(String search) {
2491 return ht.HtmlUnitUtils.getEnclosingTagNode(
2492 indexUnit,
2493 indexContent.indexOf(search));
2494 }
2495
2496 ht.XmlTagNode _getTagNode(String search) {
2497 return ht.HtmlUnitUtils.getTagNode(indexUnit, indexContent.indexOf(search));
2498 }
2499
2500 void _resolveSimpleCtrlFieldHtml() {
2501 resolveIndex2(r'''
2502 <html>
2503 <body ng-app>
2504 <div my-controller>
2505 {{ctrl.field}}
2506 </div>
2507 <script type='application/dart' src='main.dart'></script>
2508 </body>
2509 </html>''');
2510 }
2511 }
2512
2513
2514 abstract class AngularTest extends EngineTestCase {
2515 AnalysisContextHelper contextHelper = new AnalysisContextHelper();
2516
2517 AnalysisContext context;
2518
2519 String mainContent;
2520
2521 Source mainSource;
2522
2523 CompilationUnit mainUnit;
2524
2525 CompilationUnitElement mainUnitElement;
2526 String indexContent;
2527 Source indexSource;
2528 ht.HtmlUnit indexUnit;
2529 HtmlElement indexHtmlUnit;
2530 CompilationUnitElement indexDartUnitElement;
2531 /**
2532 * Fills [indexContent] and [indexSource].
2533 */
2534 void addIndexSource(String content) {
2535 addIndexSource2("/index.html", content);
2536 }
2537 /**
2538 * Fills [indexContent] and [indexSource].
2539 */
2540 void addIndexSource2(String name, String content) {
2541 indexContent = content;
2542 indexSource = contextHelper.addSource(name, indexContent);
2543 }
2544 /**
2545 * Fills [mainContent] and [mainSource].
2546 */
2547 void addMainSource(String content) {
2548 mainContent = content;
2549 mainSource = contextHelper.addSource("/main.dart", content);
2550 }
2551 void addMyController() {
2552 resolveMainSource(r'''
2553
2554 import 'angular.dart';
2555
2556 class Item {
2557 String name;
2558 bool done;
2559 }
2560
2561 @Controller(
2562 selector: '[my-controller]',
2563 publishAs: 'ctrl')
2564 class MyController {
2565 String field;
2566 List<String> names;
2567 List<Item> items;
2568 var untypedItems;
2569 doSomething(event) {}
2570 }''');
2571 }
2572 /**
2573 * Assert that the number of errors reported against the given source matches the number of errors
2574 * that are given and that they have the expected error codes. The order in wh ich the errors were
2575 * gathered is ignored.
2576 *
2577 * @param source the source against which the errors should have been reported
2578 * @param expectedErrorCodes the error codes of the errors that should have be en reported
2579 * @throws AnalysisException if the reported errors could not be computed
2580 * @throws AssertionFailedError if a different number of errors have been repo rted than were
2581 * expected
2582 */
2583 void assertErrors(Source source, [List<ErrorCode> expectedErrorCodes =
2584 ErrorCode.EMPTY_LIST]) {
2585 GatheringErrorListener errorListener = new GatheringErrorListener();
2586 AnalysisErrorInfo errorsInfo = context.getErrors(source);
2587 for (AnalysisError error in errorsInfo.errors) {
2588 errorListener.onError(error);
2589 }
2590 errorListener.assertErrorsWithCodes(expectedErrorCodes);
2591 }
2592
2593 void assertMainErrors(List<ErrorCode> expectedErrorCodes) {
2594 assertErrors(mainSource, expectedErrorCodes);
2595 }
2596
2597 /**
2598 * Assert that no errors have been reported against the [indexSource].
2599 */
2600 void assertNoErrors() {
2601 assertErrors(indexSource);
2602 }
2603
2604 void assertNoErrors2(Source source) {
2605 assertErrors(source);
2606 }
2607
2608 /**
2609 * Assert that no errors have been reported against the [mainSource].
2610 */
2611 void assertNoMainErrors() {
2612 assertErrors(mainSource);
2613 }
2614
2615 /**
2616 * Checks that [indexHtmlUnit] has [SimpleIdentifier] with given name, resolve d to
2617 * not `null` [Element].
2618 */
2619 Element assertResolvedIdentifier(String name) {
2620 SimpleIdentifier identifier = findIdentifier(name);
2621 // check Element
2622 Element element = identifier.bestElement;
2623 expect(element, isNotNull);
2624 // return Element for further analysis
2625 return element;
2626 }
2627
2628 Element assertResolvedIdentifier2(String name, String expectedTypeName) {
2629 SimpleIdentifier identifier = findIdentifier(name);
2630 // check Element
2631 Element element = identifier.bestElement;
2632 expect(element, isNotNull);
2633 // check Type
2634 DartType type = identifier.bestType;
2635 expect(type, isNotNull);
2636 expect(type.toString(), expectedTypeName);
2637 // return Element for further analysis
2638 return element;
2639 }
2640
2641 /**
2642 * @return [AstNode] which has required offset and type.
2643 */
2644 AstNode findExpression(int offset, Predicate<AstNode> predicate) {
2645 Expression expression = ht.HtmlUnitUtils.getExpression(indexUnit, offset);
2646 return expression != null ? expression.getAncestor(predicate) : null;
2647 }
2648
2649 /**
2650 * Returns the [SimpleIdentifier] at the given search pattern. Fails if not fo und.
2651 */
2652 SimpleIdentifier findIdentifier(String search) {
2653 SimpleIdentifier identifier = findIdentifierMaybe(search);
2654 expect(identifier, isNotNull, reason: "$search in $indexContent");
2655 // check that offset/length of the identifier is valid
2656 {
2657 int offset = identifier.offset;
2658 int end = identifier.end;
2659 String contentStr = indexContent.substring(offset, end);
2660 expect(contentStr, identifier.name);
2661 }
2662 // done
2663 return identifier;
2664 }
2665
2666 /**
2667 * Returns the [SimpleIdentifier] at the given search pattern, or `null` if no t found.
2668 */
2669 SimpleIdentifier findIdentifierMaybe(String search) {
2670 return findExpression(
2671 findOffset2(search),
2672 (node) => node is SimpleIdentifier);
2673 }
2674
2675 /**
2676 * Returns [Element] from [indexDartUnitElement].
2677 */
2678 Element findIndexElement(String name) {
2679 return findElement2(indexDartUnitElement, name);
2680 }
2681
2682 /**
2683 * Returns [Element] from [mainUnitElement].
2684 */
2685 Element findMainElement(ElementKind kind, String name) {
2686 return findElement(mainUnitElement, kind, name);
2687 }
2688
2689 /**
2690 * Returns [Element] from [mainUnitElement].
2691 */
2692 Element findMainElement2(String name) => findElement2(mainUnitElement, name);
2693
2694 /**
2695 * @return the offset of given <code>search</code> string in [mainContent]. Fa ils test if
2696 * not found.
2697 */
2698 int findMainOffset(String search) => findOffset(mainContent, search);
2699
2700 /**
2701 * @return the offset of given <code>search</code> string in [indexContent]. F ails test if
2702 * not found.
2703 */
2704 int findOffset2(String search) => findOffset(indexContent, search);
2705
2706 /**
2707 * Resolves [indexSource].
2708 */
2709 void resolveIndex() {
2710 indexUnit = context.resolveHtmlUnit(indexSource);
2711 indexHtmlUnit = indexUnit.element;
2712 indexDartUnitElement = indexHtmlUnit.angularCompilationUnit;
2713 }
2714
2715 void resolveIndex2(String content) {
2716 addIndexSource(content);
2717 contextHelper.runTasks();
2718 resolveIndex();
2719 }
2720
2721 /**
2722 * Resolves [mainSource].
2723 */
2724 void resolveMain() {
2725 mainUnit = contextHelper.resolveDefiningUnit(mainSource);
2726 mainUnitElement = mainUnit.element;
2727 }
2728
2729 /**
2730 * Resolves [mainSource].
2731 */
2732 void resolveMainNoErrors() {
2733 resolveMain();
2734 assertNoErrors2(mainSource);
2735 }
2736
2737 void resolveMainSource(String content) {
2738 addMainSource(content);
2739 resolveMain();
2740 }
2741
2742 void resolveMainSourceNoErrors(String content) {
2743 resolveMainSource(content);
2744 assertNoErrors2(mainSource);
2745 }
2746
2747 @override
2748 void setUp() {
2749 super.setUp();
2750 _configureForAngular(contextHelper);
2751 context = contextHelper.context;
2752 }
2753
2754 @override
2755 void tearDown() {
2756 contextHelper = null;
2757 context = null;
2758 // main
2759 mainContent = null;
2760 mainSource = null;
2761 mainUnit = null;
2762 mainUnitElement = null;
2763 // index
2764 indexContent = null;
2765 indexSource = null;
2766 indexUnit = null;
2767 indexHtmlUnit = null;
2768 indexDartUnitElement = null;
2769 // super
2770 super.tearDown();
2771 }
2772
2773 /**
2774 * Verify that all of the identifiers in the HTML units associated with the gi ven sources have
2775 * been resolved.
2776 *
2777 * @param sources the sources identifying the compilation units to be verified
2778 * @throws Exception if the contents of the compilation unit cannot be accesse d
2779 */
2780 void verify(List<Source> sources) {
2781 ResolutionVerifier verifier = new ResolutionVerifier();
2782 for (Source source in sources) {
2783 ht.HtmlUnit htmlUnit = context.getResolvedHtmlUnit(source);
2784 htmlUnit.accept(new ExpressionVisitor_AngularTest_verify(verifier));
2785 }
2786 verifier.assertResolved();
2787 }
2788
2789 void _configureForAngular(AnalysisContextHelper contextHelper) {
2790 contextHelper.addSource("/angular.dart", r'''
2791 library angular;
2792
2793 class Scope {
2794 Map context;
2795 }
2796
2797 class Formatter {
2798 final String name;
2799 const Formatter({this.name});
2800 }
2801
2802 class Directive {
2803 const Directive({
2804 selector,
2805 children,
2806 visibility,
2807 module,
2808 map,
2809 exportedExpressions,
2810 exportedExpressionAttrs
2811 });
2812 }
2813
2814 class Decorator {
2815 const Decorator({
2816 children/*: Directive.COMPILE_CHILDREN*/,
2817 map,
2818 selector,
2819 module,
2820 visibility,
2821 exportedExpressions,
2822 exportedExpressionAttrs
2823 });
2824 }
2825
2826 class Controller {
2827 const Controller({
2828 children,
2829 publishAs,
2830 map,
2831 selector,
2832 visibility,
2833 publishTypes,
2834 exportedExpressions,
2835 exportedExpressionAttrs
2836 });
2837 }
2838
2839 class NgAttr {
2840 const NgAttr(String name);
2841 }
2842 class NgCallback {
2843 const NgCallback(String name);
2844 }
2845 class NgOneWay {
2846 const NgOneWay(String name);
2847 }
2848 class NgOneWayOneTime {
2849 const NgOneWayOneTime(String name);
2850 }
2851 class NgTwoWay {
2852 const NgTwoWay(String name);
2853 }
2854
2855 class Component extends Directive {
2856 const Component({
2857 this.template,
2858 this.templateUrl,
2859 this.cssUrl,
2860 this.applyAuthorStyles,
2861 this.resetStyleInheritance,
2862 publishAs,
2863 module,
2864 map,
2865 selector,
2866 visibility,
2867 exportExpressions,
2868 exportExpressionAttrs
2869 }) : super(selector: selector,
2870 children: null/*NgAnnotation.COMPILE_CHILDREN*/,
2871 visibility: visibility,
2872 map: map,
2873 module: module,
2874 exportExpressions: exportExpressions,
2875 exportExpressionAttrs: exportExpressionAttrs);
2876 }
2877
2878 @Decorator(selector: '[ng-click]', map: const {'ng-click': '&onEvent'})
2879 @Decorator(selector: '[ng-mouseout]', map: const {'ng-mouseout': '&onEvent'})
2880 class NgEventDirective {
2881 set onEvent(value) {}
2882 }
2883
2884 @Decorator(selector: '[ng-if]', map: const {'ng-if': '=>condition'})
2885 class NgIfDirective {
2886 set condition(value) {}
2887 }
2888
2889 @Decorator(selector: '[ng-show]', map: const {'ng-show': '=>show'})
2890 class NgShowDirective {
2891 set show(value) {}
2892 }
2893
2894 @Formatter(name: 'filter')
2895 class FilterFormatter {}
2896
2897 @Formatter(name: 'orderBy')
2898 class OrderByFilter {}
2899
2900 @Formatter(name: 'uppercase')
2901 class UppercaseFilter {}
2902
2903 class ViewFactory {
2904 call(String templateUrl) => null;
2905 }
2906
2907 class Module {
2908 install(Module m) {}
2909 type(Type t) {}
2910 value(Type t, value) {}
2911 }
2912
2913 class Injector {}
2914
2915 Injector ngBootstrap({
2916 Module module: null,
2917 List<Module> modules: null,
2918 /*dom.Element*/ element: null,
2919 String selector: '[ng-app]',
2920 /*Injector*/ injectorFactory/*(List<Module> modules): _defaultInjectorFa ctory*/}) {}
2921 ''');
2922 }
2923
2924 /**
2925 * Creates an HTML content that has Angular marker and script with
2926 * the "main.dart" reference.
2927 */
2928 static String createHtmlWithAngular(String innerCode) {
2929 String source = '''
2930 <html ng-app>
2931 <body>
2932 $innerCode
2933 <script type='application/dart' src='main.dart'></script>
2934 </body>
2935 </html>''';
2936 return source;
2937 }
2938
2939 /**
2940 * Creates an HTML content that has Angular marker, script with "main.dart" re ference and
2941 * "MyController" injected.
2942 */
2943 static String createHtmlWithMyController(String innerHtml) {
2944 String source = '''
2945 <html ng-app>
2946 <body>
2947 <div my-controller>
2948 $innerHtml
2949 </div>
2950 <script type='application/dart' src='main.dart'></script>
2951 </body>
2952 </html>''';
2953 return source;
2954 }
2955
2956 /**
2957 * Finds an [Element] with the given names inside of the given root [Element].
2958 *
2959 * TODO(scheglov) maybe move this method to Element
2960 *
2961 * @param root the root [Element] to start searching from
2962 * @param kind the kind of the [Element] to find, if `null` then any kind
2963 * @param name the name of an [Element] to find
2964 * @return the found [Element] or `null` if not found
2965 */
2966 static Element findElement(Element root, ElementKind kind, String name) {
2967 _AngularTest_findElement visitor = new _AngularTest_findElement(kind, name);
2968 root.accept(visitor);
2969 return visitor.result;
2970 }
2971
2972 /**
2973 * Finds an [Element] with the given names inside of the given root [Element].
2974 *
2975 * @param root the root [Element] to start searching from
2976 * @param name the name of an [Element] to find
2977 * @return the found [Element] or `null` if not found
2978 */
2979 static Element findElement2(Element root, String name) {
2980 return findElement(root, null, name);
2981 }
2982
2983 /**
2984 * @return the offset of given <code>search</code> string in <code>content</co de>. Fails test if
2985 * not found.
2986 */
2987 static int findOffset(String content, String search) {
2988 int offset = content.indexOf(search);
2989 expect(offset, isNot(-1));
2990 return offset;
2991 }
2992 }
2993
2994
2995 class ConstantEvaluatorTest extends ResolverTestCase {
2996 void fail_constructor() {
2997 EvaluationResult result = _getExpressionValue("?");
2998 expect(result.isValid, isTrue);
2999 DartObject value = result.value;
3000 expect(value, null);
3001 }
3002
3003 void fail_identifier_class() {
3004 EvaluationResult result = _getExpressionValue("?");
3005 expect(result.isValid, isTrue);
3006 DartObject value = result.value;
3007 expect(value, null);
3008 }
3009
3010 void fail_identifier_function() {
3011 EvaluationResult result = _getExpressionValue("?");
3012 expect(result.isValid, isTrue);
3013 DartObject value = result.value;
3014 expect(value, null);
3015 }
3016
3017 void fail_identifier_static() {
3018 EvaluationResult result = _getExpressionValue("?");
3019 expect(result.isValid, isTrue);
3020 DartObject value = result.value;
3021 expect(value, null);
3022 }
3023
3024 void fail_identifier_staticMethod() {
3025 EvaluationResult result = _getExpressionValue("?");
3026 expect(result.isValid, isTrue);
3027 DartObject value = result.value;
3028 expect(value, null);
3029 }
3030
3031 void fail_identifier_topLevel() {
3032 EvaluationResult result = _getExpressionValue("?");
3033 expect(result.isValid, isTrue);
3034 DartObject value = result.value;
3035 expect(value, null);
3036 }
3037
3038 void fail_identifier_typeParameter() {
3039 EvaluationResult result = _getExpressionValue("?");
3040 expect(result.isValid, isTrue);
3041 DartObject value = result.value;
3042 expect(value, null);
3043 }
3044
3045 void fail_plus_string_string() {
3046 _assertValue4("ab", "'a' + 'b'");
3047 }
3048
3049 void fail_prefixedIdentifier_invalid() {
3050 EvaluationResult result = _getExpressionValue("?");
3051 expect(result.isValid, isTrue);
3052 DartObject value = result.value;
3053 expect(value, null);
3054 }
3055
3056 void fail_prefixedIdentifier_valid() {
3057 EvaluationResult result = _getExpressionValue("?");
3058 expect(result.isValid, isTrue);
3059 DartObject value = result.value;
3060 expect(value, null);
3061 }
3062
3063 void fail_propertyAccess_invalid() {
3064 EvaluationResult result = _getExpressionValue("?");
3065 expect(result.isValid, isTrue);
3066 DartObject value = result.value;
3067 expect(value, null);
3068 }
3069
3070 void fail_propertyAccess_valid() {
3071 EvaluationResult result = _getExpressionValue("?");
3072 expect(result.isValid, isTrue);
3073 DartObject value = result.value;
3074 expect(value, null);
3075 }
3076
3077 void fail_simpleIdentifier_invalid() {
3078 EvaluationResult result = _getExpressionValue("?");
3079 expect(result.isValid, isTrue);
3080 DartObject value = result.value;
3081 expect(value, null);
3082 }
3083
3084 void fail_simpleIdentifier_valid() {
3085 EvaluationResult result = _getExpressionValue("?");
3086 expect(result.isValid, isTrue);
3087 DartObject value = result.value;
3088 expect(value, null);
3089 }
3090
3091 void fail_stringLength_complex() {
3092 _assertValue3(6, "('qwe' + 'rty').length");
3093 }
3094
3095 void fail_stringLength_simple() {
3096 _assertValue3(6, "'Dvorak'.length");
3097 }
3098
3099 void test_bitAnd_int_int() {
3100 _assertValue3(74 & 42, "74 & 42");
3101 }
3102
3103 void test_bitNot() {
3104 _assertValue3(~42, "~42");
3105 }
3106
3107 void test_bitOr_int_int() {
3108 _assertValue3(74 | 42, "74 | 42");
3109 }
3110
3111 void test_bitXor_int_int() {
3112 _assertValue3(74 ^ 42, "74 ^ 42");
3113 }
3114 void test_divide_double_double() {
3115 _assertValue2(3.2 / 2.3, "3.2 / 2.3");
3116 }
3117
3118 void test_divide_double_double_byZero() {
3119 EvaluationResult result = _getExpressionValue("3.2 / 0.0");
3120 expect(result.isValid, isTrue);
3121 DartObject value = result.value;
3122 expect(value.type.name, "double");
3123 expect(value.doubleValue.isInfinite, isTrue);
3124 }
3125
3126 void test_divide_int_int() {
3127 _assertValue3(1, "3 / 2");
3128 }
3129
3130 void test_divide_int_int_byZero() {
3131 EvaluationResult result = _getExpressionValue("3 / 0");
3132 expect(result.isValid, isTrue);
3133 }
3134
3135 void test_equal_boolean_boolean() {
3136 _assertValue(false, "true == false");
3137 }
3138
3139 void test_equal_int_int() {
3140 _assertValue(false, "2 == 3");
3141 }
3142
3143 void test_equal_invalidLeft() {
3144 EvaluationResult result = _getExpressionValue("a == 3");
3145 expect(result.isValid, isFalse);
3146 }
3147
3148 void test_equal_invalidRight() {
3149 EvaluationResult result = _getExpressionValue("2 == a");
3150 expect(result.isValid, isFalse);
3151 }
3152
3153 void test_equal_string_string() {
3154 _assertValue(false, "'a' == 'b'");
3155 }
3156
3157 void test_greaterThan_int_int() {
3158 _assertValue(false, "2 > 3");
3159 }
3160
3161 void test_greaterThanOrEqual_int_int() {
3162 _assertValue(false, "2 >= 3");
3163 }
3164
3165 void test_leftShift_int_int() {
3166 _assertValue3(64, "16 << 2");
3167 }
3168 void test_lessThan_int_int() {
3169 _assertValue(true, "2 < 3");
3170 }
3171
3172 void test_lessThanOrEqual_int_int() {
3173 _assertValue(true, "2 <= 3");
3174 }
3175
3176 void test_literal_boolean_false() {
3177 _assertValue(false, "false");
3178 }
3179
3180 void test_literal_boolean_true() {
3181 _assertValue(true, "true");
3182 }
3183
3184 void test_literal_list() {
3185 EvaluationResult result = _getExpressionValue("const ['a', 'b', 'c']");
3186 expect(result.isValid, isTrue);
3187 }
3188
3189 void test_literal_map() {
3190 EvaluationResult result =
3191 _getExpressionValue("const {'a' : 'm', 'b' : 'n', 'c' : 'o'}");
3192 expect(result.isValid, isTrue);
3193 }
3194
3195 void test_literal_null() {
3196 EvaluationResult result = _getExpressionValue("null");
3197 expect(result.isValid, isTrue);
3198 DartObject value = result.value;
3199 expect(value.isNull, isTrue);
3200 }
3201
3202 void test_literal_number_double() {
3203 _assertValue2(3.45, "3.45");
3204 }
3205
3206 void test_literal_number_integer() {
3207 _assertValue3(42, "42");
3208 }
3209
3210 void test_literal_string_adjacent() {
3211 _assertValue4("abcdef", "'abc' 'def'");
3212 }
3213
3214 void test_literal_string_interpolation_invalid() {
3215 EvaluationResult result = _getExpressionValue("'a\${f()}c'");
3216 expect(result.isValid, isFalse);
3217 }
3218
3219 void test_literal_string_interpolation_valid() {
3220 _assertValue4("a3c", "'a\${3}c'");
3221 }
3222
3223 void test_literal_string_simple() {
3224 _assertValue4("abc", "'abc'");
3225 }
3226
3227 void test_logicalAnd() {
3228 _assertValue(false, "true && false");
3229 }
3230
3231 void test_logicalNot() {
3232 _assertValue(false, "!true");
3233 }
3234
3235 void test_logicalOr() {
3236 _assertValue(true, "true || false");
3237 }
3238
3239 void test_minus_double_double() {
3240 _assertValue2(3.2 - 2.3, "3.2 - 2.3");
3241 }
3242
3243 void test_minus_int_int() {
3244 _assertValue3(1, "3 - 2");
3245 }
3246
3247 void test_negated_boolean() {
3248 EvaluationResult result = _getExpressionValue("-true");
3249 expect(result.isValid, isFalse);
3250 }
3251
3252 void test_negated_double() {
3253 _assertValue2(-42.3, "-42.3");
3254 }
3255
3256 void test_negated_integer() {
3257 _assertValue3(-42, "-42");
3258 }
3259
3260 void test_notEqual_boolean_boolean() {
3261 _assertValue(true, "true != false");
3262 }
3263
3264 void test_notEqual_int_int() {
3265 _assertValue(true, "2 != 3");
3266 }
3267
3268 void test_notEqual_invalidLeft() {
3269 EvaluationResult result = _getExpressionValue("a != 3");
3270 expect(result.isValid, isFalse);
3271 }
3272
3273 void test_notEqual_invalidRight() {
3274 EvaluationResult result = _getExpressionValue("2 != a");
3275 expect(result.isValid, isFalse);
3276 }
3277
3278 void test_notEqual_string_string() {
3279 _assertValue(true, "'a' != 'b'");
3280 }
3281
3282 void test_parenthesizedExpression() {
3283 _assertValue4("a", "('a')");
3284 }
3285
3286 void test_plus_double_double() {
3287 _assertValue2(2.3 + 3.2, "2.3 + 3.2");
3288 }
3289
3290 void test_plus_int_int() {
3291 _assertValue3(5, "2 + 3");
3292 }
3293
3294 void test_remainder_double_double() {
3295 _assertValue2(3.2 % 2.3, "3.2 % 2.3");
3296 }
3297
3298 void test_remainder_int_int() {
3299 _assertValue3(2, "8 % 3");
3300 }
3301
3302 void test_rightShift() {
3303 _assertValue3(16, "64 >> 2");
3304 }
3305
3306 void test_times_double_double() {
3307 _assertValue2(2.3 * 3.2, "2.3 * 3.2");
3308 }
3309
3310 void test_times_int_int() {
3311 _assertValue3(6, "2 * 3");
3312 }
3313
3314 void test_truncatingDivide_double_double() {
3315 _assertValue3(1, "3.2 ~/ 2.3");
3316 }
3317
3318 void test_truncatingDivide_int_int() {
3319 _assertValue3(3, "10 ~/ 3");
3320 }
3321
3322 void _assertValue(bool expectedValue, String contents) {
3323 EvaluationResult result = _getExpressionValue(contents);
3324 DartObject value = result.value;
3325 expect(value.type.name, "bool");
3326 expect(value.boolValue, expectedValue);
3327 }
3328
3329 void _assertValue2(double expectedValue, String contents) {
3330 EvaluationResult result = _getExpressionValue(contents);
3331 expect(result.isValid, isTrue);
3332 DartObject value = result.value;
3333 expect(value.type.name, "double");
3334 expect(value.doubleValue, expectedValue);
3335 }
3336
3337 void _assertValue3(int expectedValue, String contents) {
3338 EvaluationResult result = _getExpressionValue(contents);
3339 expect(result.isValid, isTrue);
3340 DartObject value = result.value;
3341 expect(value.type.name, "int");
3342 expect(value.intValue, expectedValue);
3343 }
3344
3345 void _assertValue4(String expectedValue, String contents) {
3346 EvaluationResult result = _getExpressionValue(contents);
3347 DartObject value = result.value;
3348 expect(value, isNotNull);
3349 ParameterizedType type = value.type;
3350 expect(type, isNotNull);
3351 expect(type.name, "String");
3352 expect(value.stringValue, expectedValue);
3353 }
3354
3355 EvaluationResult _getExpressionValue(String contents) {
3356 Source source = addSource("var x = $contents;");
3357 LibraryElement library = resolve(source);
3358 CompilationUnit unit =
3359 analysisContext.resolveCompilationUnit(source, library);
3360 expect(unit, isNotNull);
3361 NodeList<CompilationUnitMember> declarations = unit.declarations;
3362 expect(declarations, hasLength(1));
3363 CompilationUnitMember declaration = declarations[0];
3364 EngineTestCase.assertInstanceOf(
3365 (obj) => obj is TopLevelVariableDeclaration,
3366 TopLevelVariableDeclaration,
3367 declaration);
3368 NodeList<VariableDeclaration> variables =
3369 (declaration as TopLevelVariableDeclaration).variables.variables;
3370 expect(variables, hasLength(1));
3371 ConstantEvaluator evaluator = new ConstantEvaluator(
3372 source,
3373 (analysisContext as AnalysisContextImpl).typeProvider);
3374 return evaluator.evaluate(variables[0].initializer);
3375 }
3376 }
3377
3378
3379 class ConstantFinderTest extends EngineTestCase {
3380 AstNode _node;
3381
3382 void test_visitConstructorDeclaration_const() {
3383 ConstructorElement element = _setupConstructorDeclaration("A", true);
3384 expect(_findConstantDeclarations()[element], same(_node));
3385 }
3386
3387 void test_visitConstructorDeclaration_nonConst() {
3388 _setupConstructorDeclaration("A", false);
3389 expect(_findConstantDeclarations().isEmpty, isTrue);
3390 }
3391
3392 void test_visitInstanceCreationExpression_const() {
3393 _setupInstanceCreationExpression("A", true);
3394 expect(_findConstructorInvocations().contains(_node), isTrue);
3395 }
3396
3397 void test_visitInstanceCreationExpression_nonConst() {
3398 _setupInstanceCreationExpression("A", false);
3399 expect(_findConstructorInvocations().isEmpty, isTrue);
3400 }
3401
3402 void test_visitVariableDeclaration_const() {
3403 VariableElement element = _setupVariableDeclaration("v", true, true);
3404 expect(_findVariableDeclarations()[element], same(_node));
3405 }
3406
3407 void test_visitVariableDeclaration_noInitializer() {
3408 _setupVariableDeclaration("v", true, false);
3409 expect(_findVariableDeclarations().isEmpty, isTrue);
3410 }
3411
3412 void test_visitVariableDeclaration_nonConst() {
3413 _setupVariableDeclaration("v", false, true);
3414 expect(_findVariableDeclarations().isEmpty, isTrue);
3415 }
3416
3417 Map<ConstructorElement, ConstructorDeclaration> _findConstantDeclarations() {
3418 ConstantFinder finder = new ConstantFinder();
3419 _node.accept(finder);
3420 Map<ConstructorElement, ConstructorDeclaration> constructorMap =
3421 finder.constructorMap;
3422 expect(constructorMap, isNotNull);
3423 return constructorMap;
3424 }
3425
3426 List<InstanceCreationExpression> _findConstructorInvocations() {
3427 ConstantFinder finder = new ConstantFinder();
3428 _node.accept(finder);
3429 List<InstanceCreationExpression> constructorInvocations =
3430 finder.constructorInvocations;
3431 expect(constructorInvocations, isNotNull);
3432 return constructorInvocations;
3433 }
3434
3435 Map<VariableElement, VariableDeclaration> _findVariableDeclarations() {
3436 ConstantFinder finder = new ConstantFinder();
3437 _node.accept(finder);
3438 Map<VariableElement, VariableDeclaration> variableMap = finder.variableMap;
3439 expect(variableMap, isNotNull);
3440 return variableMap;
3441 }
3442
3443 ConstructorElement _setupConstructorDeclaration(String name, bool isConst) {
3444 Keyword constKeyword = isConst ? Keyword.CONST : null;
3445 ConstructorDeclaration constructorDeclaration =
3446 AstFactory.constructorDeclaration2(
3447 constKeyword,
3448 null,
3449 null,
3450 name,
3451 AstFactory.formalParameterList(),
3452 null,
3453 AstFactory.blockFunctionBody2());
3454 ClassElement classElement = ElementFactory.classElement2(name);
3455 ConstructorElement element =
3456 ElementFactory.constructorElement(classElement, name, isConst);
3457 constructorDeclaration.element = element;
3458 _node = constructorDeclaration;
3459 return element;
3460 }
3461
3462 void _setupInstanceCreationExpression(String name, bool isConst) {
3463 _node = AstFactory.instanceCreationExpression2(
3464 isConst ? Keyword.CONST : null,
3465 AstFactory.typeName3(AstFactory.identifier3(name)));
3466 }
3467
3468 VariableElement _setupVariableDeclaration(String name, bool isConst,
3469 bool isInitialized) {
3470 VariableDeclaration variableDeclaration = isInitialized ?
3471 AstFactory.variableDeclaration2(name, AstFactory.integer(0)) :
3472 AstFactory.variableDeclaration(name);
3473 SimpleIdentifier identifier = variableDeclaration.name;
3474 VariableElement element = ElementFactory.localVariableElement(identifier);
3475 identifier.staticElement = element;
3476 AstFactory.variableDeclarationList2(
3477 isConst ? Keyword.CONST : null,
3478 [variableDeclaration]);
3479 _node = variableDeclaration;
3480 return element;
3481 }
3482 }
3483
3484
3485 class ConstantValueComputerTest extends ResolverTestCase {
3486 void test_computeValues_cycle() {
3487 TestLogger logger = new TestLogger();
3488 AnalysisEngine.instance.logger = logger;
3489 Source librarySource = addSource(r'''
3490 const int a = c;
3491 const int b = a;
3492 const int c = b;''');
3493 LibraryElement libraryElement = resolve(librarySource);
3494 CompilationUnit unit =
3495 analysisContext.resolveCompilationUnit(librarySource, libraryElement);
3496 analysisContext.computeErrors(librarySource);
3497 expect(unit, isNotNull);
3498 ConstantValueComputer computer = _makeConstantValueComputer();
3499 computer.add(unit);
3500 computer.computeValues();
3501 NodeList<CompilationUnitMember> members = unit.declarations;
3502 expect(members, hasLength(3));
3503 _validate(false, (members[0] as TopLevelVariableDeclaration).variables);
3504 _validate(false, (members[1] as TopLevelVariableDeclaration).variables);
3505 _validate(false, (members[2] as TopLevelVariableDeclaration).variables);
3506 }
3507
3508 void test_computeValues_dependentVariables() {
3509 Source librarySource = addSource(r'''
3510 const int b = a;
3511 const int a = 0;''');
3512 LibraryElement libraryElement = resolve(librarySource);
3513 CompilationUnit unit =
3514 analysisContext.resolveCompilationUnit(librarySource, libraryElement);
3515 expect(unit, isNotNull);
3516 ConstantValueComputer computer = _makeConstantValueComputer();
3517 computer.add(unit);
3518 computer.computeValues();
3519 NodeList<CompilationUnitMember> members = unit.declarations;
3520 expect(members, hasLength(2));
3521 _validate(true, (members[0] as TopLevelVariableDeclaration).variables);
3522 _validate(true, (members[1] as TopLevelVariableDeclaration).variables);
3523 }
3524
3525 void test_computeValues_empty() {
3526 ConstantValueComputer computer = _makeConstantValueComputer();
3527 computer.computeValues();
3528 }
3529
3530 void test_computeValues_multipleSources() {
3531 Source librarySource = addNamedSource("/lib.dart", r'''
3532 library lib;
3533 part 'part.dart';
3534 const int c = b;
3535 const int a = 0;''');
3536 Source partSource = addNamedSource("/part.dart", r'''
3537 part of lib;
3538 const int b = a;
3539 const int d = c;''');
3540 LibraryElement libraryElement = resolve(librarySource);
3541 CompilationUnit libraryUnit =
3542 analysisContext.resolveCompilationUnit(librarySource, libraryElement);
3543 expect(libraryUnit, isNotNull);
3544 CompilationUnit partUnit =
3545 analysisContext.resolveCompilationUnit(partSource, libraryElement);
3546 expect(partUnit, isNotNull);
3547 ConstantValueComputer computer = _makeConstantValueComputer();
3548 computer.add(libraryUnit);
3549 computer.add(partUnit);
3550 computer.computeValues();
3551 NodeList<CompilationUnitMember> libraryMembers = libraryUnit.declarations;
3552 expect(libraryMembers, hasLength(2));
3553 _validate(
3554 true,
3555 (libraryMembers[0] as TopLevelVariableDeclaration).variables);
3556 _validate(
3557 true,
3558 (libraryMembers[1] as TopLevelVariableDeclaration).variables);
3559 NodeList<CompilationUnitMember> partMembers = libraryUnit.declarations;
3560 expect(partMembers, hasLength(2));
3561 _validate(true, (partMembers[0] as TopLevelVariableDeclaration).variables);
3562 _validate(true, (partMembers[1] as TopLevelVariableDeclaration).variables);
3563 }
3564
3565 void test_computeValues_singleVariable() {
3566 Source librarySource = addSource("const int a = 0;");
3567 LibraryElement libraryElement = resolve(librarySource);
3568 CompilationUnit unit =
3569 analysisContext.resolveCompilationUnit(librarySource, libraryElement);
3570 expect(unit, isNotNull);
3571 ConstantValueComputer computer = _makeConstantValueComputer();
3572 computer.add(unit);
3573 computer.computeValues();
3574 NodeList<CompilationUnitMember> members = unit.declarations;
3575 expect(members, hasLength(1));
3576 _validate(true, (members[0] as TopLevelVariableDeclaration).variables);
3577 }
3578
3579 void test_dependencyOnConstructor() {
3580 // x depends on "const A()"
3581 _assertProperDependencies(r'''
3582 class A {
3583 const A();
3584 }
3585 const x = const A();''');
3586 }
3587
3588 void test_dependencyOnConstructorArgument() {
3589 // "const A(x)" depends on x
3590 _assertProperDependencies(r'''
3591 class A {
3592 const A(this.next);
3593 final A next;
3594 }
3595 const A x = const A(null);
3596 const A y = const A(x);''');
3597 }
3598
3599 void test_dependencyOnConstructorArgument_unresolvedConstructor() {
3600 // "const A.a(x)" depends on x even if the constructor A.a can't be found.
3601 _assertProperDependencies(r'''
3602 class A {
3603 }
3604 const int x = 1;
3605 const A y = const A.a(x);''',
3606 [CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR]);
3607 }
3608
3609 void test_dependencyOnConstructorInitializer() {
3610 // "const A()" depends on x
3611 _assertProperDependencies(r'''
3612 const int x = 1;
3613 class A {
3614 const A() : v = x;
3615 final int v;
3616 }''');
3617 }
3618
3619 void test_dependencyOnExplicitSuperConstructor() {
3620 // b depends on B() depends on A()
3621 _assertProperDependencies(r'''
3622 class A {
3623 const A(this.x);
3624 final int x;
3625 }
3626 class B extends A {
3627 const B() : super(5);
3628 }
3629 const B b = const B();''');
3630 }
3631
3632 void test_dependencyOnExplicitSuperConstructorParameters() {
3633 // b depends on B() depends on i
3634 _assertProperDependencies(r'''
3635 class A {
3636 const A(this.x);
3637 final int x;
3638 }
3639 class B extends A {
3640 const B() : super(i);
3641 }
3642 const B b = const B();
3643 const int i = 5;''');
3644 }
3645
3646 void test_dependencyOnFactoryRedirect() {
3647 // a depends on A.foo() depends on A.bar()
3648 _assertProperDependencies(r'''
3649 const A a = const A.foo();
3650 class A {
3651 factory const A.foo() = A.bar;
3652 const A.bar();
3653 }''');
3654 }
3655
3656 void test_dependencyOnFactoryRedirectWithTypeParams() {
3657 _assertProperDependencies(r'''
3658 class A {
3659 const factory A(var a) = B<int>;
3660 }
3661
3662 class B<T> implements A {
3663 final T x;
3664 const B(this.x);
3665 }
3666
3667 const A a = const A(10);''');
3668 }
3669
3670 void test_dependencyOnImplicitSuperConstructor() {
3671 // b depends on B() depends on A()
3672 _assertProperDependencies(r'''
3673 class A {
3674 const A() : x = 5;
3675 final int x;
3676 }
3677 class B extends A {
3678 const B();
3679 }
3680 const B b = const B();''');
3681 }
3682
3683 void test_dependencyOnNonFactoryRedirect() {
3684 // a depends on A.foo() depends on A.bar()
3685 _assertProperDependencies(r'''
3686 const A a = const A.foo();
3687 class A {
3688 const A.foo() : this.bar();
3689 const A.bar();
3690 }''');
3691 }
3692
3693 void test_dependencyOnNonFactoryRedirect_arg() {
3694 // a depends on A.foo() depends on b
3695 _assertProperDependencies(r'''
3696 const A a = const A.foo();
3697 const int b = 1;
3698 class A {
3699 const A.foo() : this.bar(b);
3700 const A.bar(x) : y = x;
3701 final int y;
3702 }''');
3703 }
3704
3705 void test_dependencyOnNonFactoryRedirect_defaultValue() {
3706 // a depends on A.foo() depends on A.bar() depends on b
3707 _assertProperDependencies(r'''
3708 const A a = const A.foo();
3709 const int b = 1;
3710 class A {
3711 const A.foo() : this.bar();
3712 const A.bar([x = b]) : y = x;
3713 final int y;
3714 }''');
3715 }
3716
3717 void test_dependencyOnNonFactoryRedirect_toMissing() {
3718 // a depends on A.foo() which depends on nothing, since A.bar() is
3719 // missing.
3720 _assertProperDependencies(r'''
3721 const A a = const A.foo();
3722 class A {
3723 const A.foo() : this.bar();
3724 }''', [CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR]);
3725 }
3726
3727 void test_dependencyOnNonFactoryRedirect_toNonConst() {
3728 // a depends on A.foo() which depends on nothing, since A.bar() is
3729 // non-const.
3730 _assertProperDependencies(r'''
3731 const A a = const A.foo();
3732 class A {
3733 const A.foo() : this.bar();
3734 A.bar();
3735 }''');
3736 }
3737
3738 void test_dependencyOnNonFactoryRedirect_unnamed() {
3739 // a depends on A.foo() depends on A()
3740 _assertProperDependencies(r'''
3741 const A a = const A.foo();
3742 class A {
3743 const A.foo() : this();
3744 const A();
3745 }''');
3746 }
3747
3748 void test_dependencyOnOptionalParameterDefault() {
3749 // a depends on A() depends on B()
3750 _assertProperDependencies(r'''
3751 class A {
3752 const A([x = const B()]) : b = x;
3753 final B b;
3754 }
3755 class B {
3756 const B();
3757 }
3758 const A a = const A();''');
3759 }
3760
3761 void test_dependencyOnVariable() {
3762 // x depends on y
3763 _assertProperDependencies(r'''
3764 const x = y + 1;
3765 const y = 2;''');
3766 }
3767
3768 void test_fromEnvironment_bool_default_false() {
3769 expect(_assertValidBool(_check_fromEnvironment_bool(null, "false")), false);
3770 }
3771
3772 void test_fromEnvironment_bool_default_overridden() {
3773 expect(
3774 _assertValidBool(_check_fromEnvironment_bool("false", "true")),
3775 false);
3776 }
3777
3778 void test_fromEnvironment_bool_default_parseError() {
3779 expect(
3780 _assertValidBool(_check_fromEnvironment_bool("parseError", "true")),
3781 true);
3782 }
3783
3784 void test_fromEnvironment_bool_default_true() {
3785 expect(_assertValidBool(_check_fromEnvironment_bool(null, "true")), true);
3786 }
3787
3788 void test_fromEnvironment_bool_false() {
3789 expect(_assertValidBool(_check_fromEnvironment_bool("false", null)), false);
3790 }
3791
3792 void test_fromEnvironment_bool_parseError() {
3793 expect(
3794 _assertValidBool(_check_fromEnvironment_bool("parseError", null)),
3795 false);
3796 }
3797
3798 void test_fromEnvironment_bool_true() {
3799 expect(_assertValidBool(_check_fromEnvironment_bool("true", null)), true);
3800 }
3801
3802 void test_fromEnvironment_bool_undeclared() {
3803 _assertValidUnknown(_check_fromEnvironment_bool(null, null));
3804 }
3805
3806 void test_fromEnvironment_int_default_overridden() {
3807 expect(_assertValidInt(_check_fromEnvironment_int("234", "123")), 234);
3808 }
3809
3810 void test_fromEnvironment_int_default_parseError() {
3811 expect(
3812 _assertValidInt(_check_fromEnvironment_int("parseError", "123")),
3813 123);
3814 }
3815
3816 void test_fromEnvironment_int_default_undeclared() {
3817 expect(_assertValidInt(_check_fromEnvironment_int(null, "123")), 123);
3818 }
3819
3820 void test_fromEnvironment_int_ok() {
3821 expect(_assertValidInt(_check_fromEnvironment_int("234", null)), 234);
3822 }
3823
3824 void test_fromEnvironment_int_parseError() {
3825 _assertValidNull(_check_fromEnvironment_int("parseError", null));
3826 }
3827
3828 void test_fromEnvironment_int_parseError_nullDefault() {
3829 _assertValidNull(_check_fromEnvironment_int("parseError", "null"));
3830 }
3831
3832 void test_fromEnvironment_int_undeclared() {
3833 _assertValidUnknown(_check_fromEnvironment_int(null, null));
3834 }
3835
3836 void test_fromEnvironment_int_undeclared_nullDefault() {
3837 _assertValidNull(_check_fromEnvironment_int(null, "null"));
3838 }
3839
3840 void test_fromEnvironment_string_default_overridden() {
3841 expect(
3842 _assertValidString(_check_fromEnvironment_string("abc", "'def'")),
3843 "abc");
3844 }
3845
3846 void test_fromEnvironment_string_default_undeclared() {
3847 expect(
3848 _assertValidString(_check_fromEnvironment_string(null, "'def'")),
3849 "def");
3850 }
3851
3852 void test_fromEnvironment_string_empty() {
3853 expect(_assertValidString(_check_fromEnvironment_string("", null)), "");
3854 }
3855
3856 void test_fromEnvironment_string_ok() {
3857 expect(
3858 _assertValidString(_check_fromEnvironment_string("abc", null)),
3859 "abc");
3860 }
3861
3862 void test_fromEnvironment_string_undeclared() {
3863 _assertValidUnknown(_check_fromEnvironment_string(null, null));
3864 }
3865
3866 void test_fromEnvironment_string_undeclared_nullDefault() {
3867 _assertValidNull(_check_fromEnvironment_string(null, "null"));
3868 }
3869
3870 void test_instanceCreationExpression_computedField() {
3871 CompilationUnit compilationUnit = resolveSource(r'''
3872 const foo = const A(4, 5);
3873 class A {
3874 const A(int i, int j) : k = 2 * i + j;
3875 final int k;
3876 }''');
3877 EvaluationResultImpl result =
3878 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3879 Map<String, DartObjectImpl> fields = _assertType(result, "A");
3880 expect(fields, hasLength(1));
3881 _assertIntField(fields, "k", 13);
3882 }
3883
3884 void
3885 test_instanceCreationExpression_computedField_namedOptionalWithDefault() {
3886 _checkInstanceCreationOptionalParams(false, true, true);
3887 }
3888
3889 void
3890 test_instanceCreationExpression_computedField_namedOptionalWithoutDefault( ) {
3891 _checkInstanceCreationOptionalParams(false, true, false);
3892 }
3893
3894 void
3895 test_instanceCreationExpression_computedField_unnamedOptionalWithDefault() {
3896 _checkInstanceCreationOptionalParams(false, false, true);
3897 }
3898
3899 void
3900 test_instanceCreationExpression_computedField_unnamedOptionalWithoutDefaul t() {
3901 _checkInstanceCreationOptionalParams(false, false, false);
3902 }
3903
3904 void test_instanceCreationExpression_computedField_usesConstConstructor() {
3905 CompilationUnit compilationUnit = resolveSource(r'''
3906 const foo = const A(3);
3907 class A {
3908 const A(int i) : b = const B(4);
3909 final int b;
3910 }
3911 class B {
3912 const B(this.k);
3913 final int k;
3914 }''');
3915 EvaluationResultImpl result =
3916 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3917 Map<String, DartObjectImpl> fieldsOfA = _assertType(result, "A");
3918 expect(fieldsOfA, hasLength(1));
3919 Map<String, DartObjectImpl> fieldsOfB =
3920 _assertFieldType(fieldsOfA, "b", "B");
3921 expect(fieldsOfB, hasLength(1));
3922 _assertIntField(fieldsOfB, "k", 4);
3923 }
3924
3925 void test_instanceCreationExpression_computedField_usesStaticConst() {
3926 CompilationUnit compilationUnit = resolveSource(r'''
3927 const foo = const A(3);
3928 class A {
3929 const A(int i) : k = i + B.bar;
3930 final int k;
3931 }
3932 class B {
3933 static const bar = 4;
3934 }''');
3935 EvaluationResultImpl result =
3936 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3937 Map<String, DartObjectImpl> fields = _assertType(result, "A");
3938 expect(fields, hasLength(1));
3939 _assertIntField(fields, "k", 7);
3940 }
3941
3942 void test_instanceCreationExpression_computedField_usesToplevelConst() {
3943 CompilationUnit compilationUnit = resolveSource(r'''
3944 const foo = const A(3);
3945 const bar = 4;
3946 class A {
3947 const A(int i) : k = i + bar;
3948 final int k;
3949 }''');
3950 EvaluationResultImpl result =
3951 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3952 Map<String, DartObjectImpl> fields = _assertType(result, "A");
3953 expect(fields, hasLength(1));
3954 _assertIntField(fields, "k", 7);
3955 }
3956
3957 void test_instanceCreationExpression_explicitSuper() {
3958 CompilationUnit compilationUnit = resolveSource(r'''
3959 const foo = const B(4, 5);
3960 class A {
3961 const A(this.x);
3962 final int x;
3963 }
3964 class B extends A {
3965 const B(int x, this.y) : super(x * 2);
3966 final int y;
3967 }''');
3968 EvaluationResultImpl result =
3969 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3970 Map<String, DartObjectImpl> fields = _assertType(result, "B");
3971 expect(fields, hasLength(2));
3972 _assertIntField(fields, "y", 5);
3973 Map<String, DartObjectImpl> superclassFields =
3974 _assertFieldType(fields, GenericState.SUPERCLASS_FIELD, "A");
3975 expect(superclassFields, hasLength(1));
3976 _assertIntField(superclassFields, "x", 8);
3977 }
3978
3979 void test_instanceCreationExpression_fieldFormalParameter() {
3980 CompilationUnit compilationUnit = resolveSource(r'''
3981 const foo = const A(42);
3982 class A {
3983 int x;
3984 const A(this.x)
3985 }''');
3986 EvaluationResultImpl result =
3987 _evaluateInstanceCreationExpression(compilationUnit, "foo");
3988 Map<String, DartObjectImpl> fields = _assertType(result, "A");
3989 expect(fields, hasLength(1));
3990 _assertIntField(fields, "x", 42);
3991 }
3992
3993 void
3994 test_instanceCreationExpression_fieldFormalParameter_namedOptionalWithDefa ult() {
3995 _checkInstanceCreationOptionalParams(true, true, true);
3996 }
3997
3998 void
3999 test_instanceCreationExpression_fieldFormalParameter_namedOptionalWithoutD efault() {
4000 _checkInstanceCreationOptionalParams(true, true, false);
4001 }
4002
4003 void
4004 test_instanceCreationExpression_fieldFormalParameter_unnamedOptionalWithDe fault() {
4005 _checkInstanceCreationOptionalParams(true, false, true);
4006 }
4007
4008 void
4009 test_instanceCreationExpression_fieldFormalParameter_unnamedOptionalWithou tDefault() {
4010 _checkInstanceCreationOptionalParams(true, false, false);
4011 }
4012
4013 void test_instanceCreationExpression_implicitSuper() {
4014 CompilationUnit compilationUnit = resolveSource(r'''
4015 const foo = const B(4);
4016 class A {
4017 const A() : x = 3;
4018 final int x;
4019 }
4020 class B extends A {
4021 const B(this.y);
4022 final int y;
4023 }''');
4024 EvaluationResultImpl result =
4025 _evaluateInstanceCreationExpression(compilationUnit, "foo");
4026 Map<String, DartObjectImpl> fields = _assertType(result, "B");
4027 expect(fields, hasLength(2));
4028 _assertIntField(fields, "y", 4);
4029 Map<String, DartObjectImpl> superclassFields =
4030 _assertFieldType(fields, GenericState.SUPERCLASS_FIELD, "A");
4031 expect(superclassFields, hasLength(1));
4032 _assertIntField(superclassFields, "x", 3);
4033 }
4034
4035 void test_instanceCreationExpression_nonFactoryRedirect() {
4036 CompilationUnit compilationUnit = resolveSource(r'''
4037 const foo = const A.a1();
4038 class A {
4039 const A.a1() : this.a2();
4040 const A.a2() : x = 5;
4041 final int x;
4042 }''');
4043 Map<String, DartObjectImpl> aFields =
4044 _assertType(_evaluateInstanceCreationExpression(compilationUnit, "foo"), "A");
4045 _assertIntField(aFields, 'x', 5);
4046 }
4047
4048 void test_instanceCreationExpression_nonFactoryRedirect_arg() {
4049 CompilationUnit compilationUnit = resolveSource(r'''
4050 const foo = const A.a1(1);
4051 class A {
4052 const A.a1(x) : this.a2(x + 100);
4053 const A.a2(x) : y = x + 10;
4054 final int y;
4055 }''');
4056 Map<String, DartObjectImpl> aFields =
4057 _assertType(_evaluateInstanceCreationExpression(compilationUnit, "foo"), "A");
4058 _assertIntField(aFields, 'y', 111);
4059 }
4060
4061 void test_instanceCreationExpression_nonFactoryRedirect_cycle() {
4062 // It is an error to have a cycle in non-factory redirects; however, we
4063 // need to make sure that even if the error occurs, attempting to evaluate
4064 // the constant will terminate.
4065 CompilationUnit compilationUnit = resolveSource(r'''
4066 const foo = const A();
4067 class A {
4068 const A() : this.b();
4069 const A.b() : this();
4070 }''');
4071 _assertValidUnknown(
4072 _evaluateInstanceCreationExpression(compilationUnit, "foo"));
4073 }
4074
4075 void test_instanceCreationExpression_nonFactoryRedirect_defaultArg() {
4076 CompilationUnit compilationUnit = resolveSource(r'''
4077 const foo = const A.a1();
4078 class A {
4079 const A.a1() : this.a2();
4080 const A.a2([x = 100]) : y = x + 10;
4081 final int y;
4082 }''');
4083 Map<String, DartObjectImpl> aFields =
4084 _assertType(_evaluateInstanceCreationExpression(compilationUnit, "foo"), "A");
4085 _assertIntField(aFields, 'y', 110);
4086 }
4087
4088 void test_instanceCreationExpression_nonFactoryRedirect_toMissing() {
4089 CompilationUnit compilationUnit = resolveSource(r'''
4090 const foo = const A.a1();
4091 class A {
4092 const A.a1() : this.a2();
4093 }''');
4094 // We don't care what value foo evaluates to (since there is a compile
4095 // error), but we shouldn't crash, and we should figure
4096 // out that it evaluates to an instance of class A.
4097 _assertType(
4098 _evaluateInstanceCreationExpression(compilationUnit, "foo"),
4099 "A");
4100 }
4101
4102 void test_instanceCreationExpression_nonFactoryRedirect_toNonConst() {
4103 CompilationUnit compilationUnit = resolveSource(r'''
4104 const foo = const A.a1();
4105 class A {
4106 const A.a1() : this.a2();
4107 A.a2();
4108 }''');
4109 // We don't care what value foo evaluates to (since there is a compile
4110 // error), but we shouldn't crash, and we should figure
4111 // out that it evaluates to an instance of class A.
4112 _assertType(
4113 _evaluateInstanceCreationExpression(compilationUnit, "foo"),
4114 "A");
4115 }
4116
4117 void test_instanceCreationExpression_nonFactoryRedirect_unnamed() {
4118 CompilationUnit compilationUnit = resolveSource(r'''
4119 const foo = const A.a1();
4120 class A {
4121 const A.a1() : this();
4122 const A() : x = 5;
4123 final int x;
4124 }''');
4125 Map<String, DartObjectImpl> aFields =
4126 _assertType(_evaluateInstanceCreationExpression(compilationUnit, "foo"), "A");
4127 _assertIntField(aFields, 'x', 5);
4128 }
4129
4130 void test_instanceCreationExpression_redirect() {
4131 CompilationUnit compilationUnit = resolveSource(r'''
4132 const foo = const A();
4133 class A {
4134 const factory A() = B;
4135 }
4136 class B implements A {
4137 const B();
4138 }''');
4139 _assertType(
4140 _evaluateInstanceCreationExpression(compilationUnit, "foo"),
4141 "B");
4142 }
4143
4144 void test_instanceCreationExpression_redirect_cycle() {
4145 // It is an error to have a cycle in factory redirects; however, we need
4146 // to make sure that even if the error occurs, attempting to evaluate the
4147 // constant will terminate.
4148 CompilationUnit compilationUnit = resolveSource(r'''
4149 const foo = const A();
4150 class A {
4151 const factory A() = A.b;
4152 const factory A.b() = A;
4153 }''');
4154 _assertValidUnknown(
4155 _evaluateInstanceCreationExpression(compilationUnit, "foo"));
4156 }
4157
4158 void test_instanceCreationExpression_redirect_extern() {
4159 CompilationUnit compilationUnit = resolveSource(r'''
4160 const foo = const A();
4161 class A {
4162 external const factory A();
4163 }''');
4164 _assertValidUnknown(
4165 _evaluateInstanceCreationExpression(compilationUnit, "foo"));
4166 }
4167
4168 void test_instanceCreationExpression_redirect_nonConst() {
4169 // It is an error for a const factory constructor redirect to a non-const
4170 // constructor; however, we need to make sure that even if the error
4171 // attempting to evaluate the constant won't cause a crash.
4172 CompilationUnit compilationUnit = resolveSource(r'''
4173 const foo = const A();
4174 class A {
4175 const factory A() = A.b;
4176 A.b();
4177 }''');
4178 _assertValidUnknown(
4179 _evaluateInstanceCreationExpression(compilationUnit, "foo"));
4180 }
4181
4182 void test_instanceCreationExpression_redirectWithTypeParams() {
4183 CompilationUnit compilationUnit = resolveSource(r'''
4184 class A {
4185 const factory A(var a) = B<int>;
4186 }
4187
4188 class B<T> implements A {
4189 final T x;
4190 const B(this.x);
4191 }
4192
4193 const A a = const A(10);''');
4194 EvaluationResultImpl result =
4195 _evaluateInstanceCreationExpression(compilationUnit, "a");
4196 Map<String, DartObjectImpl> fields = _assertType(result, "B<int>");
4197 expect(fields, hasLength(1));
4198 _assertIntField(fields, "x", 10);
4199 }
4200
4201 void test_instanceCreationExpression_redirectWithTypeSubstitution() {
4202 // To evaluate the redirection of A<int>,
4203 // A's template argument (T=int) must be substituted
4204 // into B's template argument (B<U> where U=T) to get B<int>.
4205 CompilationUnit compilationUnit = resolveSource(r'''
4206 class A<T> {
4207 const factory A(var a) = B<T>;
4208 }
4209
4210 class B<U> implements A {
4211 final U x;
4212 const B(this.x);
4213 }
4214
4215 const A<int> a = const A<int>(10);''');
4216 EvaluationResultImpl result =
4217 _evaluateInstanceCreationExpression(compilationUnit, "a");
4218 Map<String, DartObjectImpl> fields = _assertType(result, "B<int>");
4219 expect(fields, hasLength(1));
4220 _assertIntField(fields, "x", 10);
4221 }
4222
4223 void test_instanceCreationExpression_symbol() {
4224 CompilationUnit compilationUnit =
4225 resolveSource("const foo = const Symbol('a');");
4226 EvaluationResultImpl evaluationResult =
4227 _evaluateInstanceCreationExpression(compilationUnit, "foo");
4228 expect(evaluationResult.value, isNotNull);
4229 DartObjectImpl value = evaluationResult.value;
4230 expect(value.type, typeProvider.symbolType);
4231 expect(value.value, "a");
4232 }
4233
4234 void test_instanceCreationExpression_withSupertypeParams_explicit() {
4235 _checkInstanceCreation_withSupertypeParams(true);
4236 }
4237
4238 void test_instanceCreationExpression_withSupertypeParams_implicit() {
4239 _checkInstanceCreation_withSupertypeParams(false);
4240 }
4241
4242 void test_instanceCreationExpression_withTypeParams() {
4243 CompilationUnit compilationUnit = resolveSource(r'''
4244 class C<E> {
4245 const C();
4246 }
4247 const c_int = const C<int>();
4248 const c_num = const C<num>();''');
4249 EvaluationResultImpl c_int =
4250 _evaluateInstanceCreationExpression(compilationUnit, "c_int");
4251 _assertType(c_int, "C<int>");
4252 DartObjectImpl c_int_value = c_int.value;
4253 EvaluationResultImpl c_num =
4254 _evaluateInstanceCreationExpression(compilationUnit, "c_num");
4255 _assertType(c_num, "C<num>");
4256 DartObjectImpl c_num_value = c_num.value;
4257 expect(c_int_value == c_num_value, isFalse);
4258 }
4259
4260 void test_isValidSymbol() {
4261 expect(ConstantValueComputer.isValidPublicSymbol(""), isTrue);
4262 expect(ConstantValueComputer.isValidPublicSymbol("foo"), isTrue);
4263 expect(ConstantValueComputer.isValidPublicSymbol("foo.bar"), isTrue);
4264 expect(ConstantValueComputer.isValidPublicSymbol("foo\$"), isTrue);
4265 expect(ConstantValueComputer.isValidPublicSymbol("foo\$bar"), isTrue);
4266 expect(ConstantValueComputer.isValidPublicSymbol("iff"), isTrue);
4267 expect(ConstantValueComputer.isValidPublicSymbol("gif"), isTrue);
4268 expect(ConstantValueComputer.isValidPublicSymbol("if\$"), isTrue);
4269 expect(ConstantValueComputer.isValidPublicSymbol("\$if"), isTrue);
4270 expect(ConstantValueComputer.isValidPublicSymbol("foo="), isTrue);
4271 expect(ConstantValueComputer.isValidPublicSymbol("foo.bar="), isTrue);
4272 expect(ConstantValueComputer.isValidPublicSymbol("foo.+"), isTrue);
4273 expect(ConstantValueComputer.isValidPublicSymbol("void"), isTrue);
4274 expect(ConstantValueComputer.isValidPublicSymbol("_foo"), isFalse);
4275 expect(ConstantValueComputer.isValidPublicSymbol("_foo.bar"), isFalse);
4276 expect(ConstantValueComputer.isValidPublicSymbol("foo._bar"), isFalse);
4277 expect(ConstantValueComputer.isValidPublicSymbol("if"), isFalse);
4278 expect(ConstantValueComputer.isValidPublicSymbol("if.foo"), isFalse);
4279 expect(ConstantValueComputer.isValidPublicSymbol("foo.if"), isFalse);
4280 expect(ConstantValueComputer.isValidPublicSymbol("foo=.bar"), isFalse);
4281 expect(ConstantValueComputer.isValidPublicSymbol("foo."), isFalse);
4282 expect(ConstantValueComputer.isValidPublicSymbol("+.foo"), isFalse);
4283 expect(ConstantValueComputer.isValidPublicSymbol("void.foo"), isFalse);
4284 expect(ConstantValueComputer.isValidPublicSymbol("foo.void"), isFalse);
4285 }
4286
4287 void test_symbolLiteral_void() {
4288 CompilationUnit compilationUnit =
4289 resolveSource("const voidSymbol = #void;");
4290 VariableDeclaration voidSymbol =
4291 findTopLevelDeclaration(compilationUnit, "voidSymbol");
4292 EvaluationResultImpl voidSymbolResult =
4293 (voidSymbol.element as VariableElementImpl).evaluationResult;
4294 DartObjectImpl value = voidSymbolResult.value;
4295 expect(value.type, typeProvider.symbolType);
4296 expect(value.value, "void");
4297 }
4298
4299 Map<String, DartObjectImpl> _assertFieldType(Map<String,
4300 DartObjectImpl> fields, String fieldName, String expectedType) {
4301 DartObjectImpl field = fields[fieldName];
4302 expect(field.type.displayName, expectedType);
4303 return field.fields;
4304 }
4305
4306 void _assertIntField(Map<String, DartObjectImpl> fields, String fieldName,
4307 int expectedValue) {
4308 DartObjectImpl field = fields[fieldName];
4309 expect(field.type.name, "int");
4310 expect(field.intValue, expectedValue);
4311 }
4312
4313 void _assertNullField(Map<String, DartObjectImpl> fields, String fieldName) {
4314 DartObjectImpl field = fields[fieldName];
4315 expect(field.isNull, isTrue);
4316 }
4317
4318 void _assertProperDependencies(String sourceText,
4319 [List<ErrorCode> expectedErrorCodes = ErrorCode.EMPTY_LIST]) {
4320 Source source = addSource(sourceText);
4321 LibraryElement element = resolve(source);
4322 CompilationUnit unit =
4323 analysisContext.resolveCompilationUnit(source, element);
4324 expect(unit, isNotNull);
4325 ConstantValueComputer computer = _makeConstantValueComputer();
4326 computer.add(unit);
4327 computer.computeValues();
4328 assertErrors(source, expectedErrorCodes);
4329 }
4330
4331 Map<String, DartObjectImpl> _assertType(EvaluationResultImpl result,
4332 String typeName) {
4333 expect(result.value, isNotNull);
4334 DartObjectImpl value = result.value;
4335 expect(value.type.displayName, typeName);
4336 return value.fields;
4337 }
4338
4339 bool _assertValidBool(EvaluationResultImpl result) {
4340 expect(result.value, isNotNull);
4341 DartObjectImpl value = result.value;
4342 expect(value.type, typeProvider.boolType);
4343 bool boolValue = value.boolValue;
4344 expect(boolValue, isNotNull);
4345 return boolValue;
4346 }
4347
4348 int _assertValidInt(EvaluationResultImpl result) {
4349 expect(result.value, isNotNull);
4350 DartObjectImpl value = result.value;
4351 expect(value.type, typeProvider.intType);
4352 return value.intValue;
4353 }
4354
4355 void _assertValidNull(EvaluationResultImpl result) {
4356 expect(result.value, isNotNull);
4357 DartObjectImpl value = result.value;
4358 expect(value.type, typeProvider.nullType);
4359 }
4360
4361 String _assertValidString(EvaluationResultImpl result) {
4362 expect(result.value, isNotNull);
4363 DartObjectImpl value = result.value;
4364 expect(value.type, typeProvider.stringType);
4365 return value.stringValue;
4366 }
4367
4368 void _assertValidUnknown(EvaluationResultImpl result) {
4369 expect(result.value, isNotNull);
4370 DartObjectImpl value = result.value;
4371 expect(value.isUnknown, isTrue);
4372 }
4373
4374 EvaluationResultImpl _check_fromEnvironment_bool(String valueInEnvironment,
4375 String defaultExpr) {
4376 String envVarName = "x";
4377 String varName = "foo";
4378 if (valueInEnvironment != null) {
4379 analysisContext2.declaredVariables.define(envVarName, valueInEnvironment);
4380 }
4381 String defaultArg =
4382 defaultExpr == null ? "" : ", defaultValue: $defaultExpr";
4383 CompilationUnit compilationUnit = resolveSource(
4384 "const $varName = const bool.fromEnvironment('$envVarName'$defaultArg);" );
4385 return _evaluateInstanceCreationExpression(compilationUnit, varName);
4386 }
4387
4388 EvaluationResultImpl _check_fromEnvironment_int(String valueInEnvironment,
4389 String defaultExpr) {
4390 String envVarName = "x";
4391 String varName = "foo";
4392 if (valueInEnvironment != null) {
4393 analysisContext2.declaredVariables.define(envVarName, valueInEnvironment);
4394 }
4395 String defaultArg =
4396 defaultExpr == null ? "" : ", defaultValue: $defaultExpr";
4397 CompilationUnit compilationUnit = resolveSource(
4398 "const $varName = const int.fromEnvironment('$envVarName'$defaultArg);") ;
4399 return _evaluateInstanceCreationExpression(compilationUnit, varName);
4400 }
4401
4402 EvaluationResultImpl _check_fromEnvironment_string(String valueInEnvironment,
4403 String defaultExpr) {
4404 String envVarName = "x";
4405 String varName = "foo";
4406 if (valueInEnvironment != null) {
4407 analysisContext2.declaredVariables.define(envVarName, valueInEnvironment);
4408 }
4409 String defaultArg =
4410 defaultExpr == null ? "" : ", defaultValue: $defaultExpr";
4411 CompilationUnit compilationUnit = resolveSource(
4412 "const $varName = const String.fromEnvironment('$envVarName'$defaultArg) ;");
4413 return _evaluateInstanceCreationExpression(compilationUnit, varName);
4414 }
4415
4416 void _checkInstanceCreation_withSupertypeParams(bool isExplicit) {
4417 String superCall = isExplicit ? " : super()" : "";
4418 CompilationUnit compilationUnit = resolveSource("""
4419 class A<T> {
4420 const A();
4421 }
4422 class B<T, U> extends A<T> {
4423 const B()$superCall;
4424 }
4425 class C<T, U> extends A<U> {
4426 const C()$superCall;
4427 }
4428 const b_int_num = const B<int, num>();
4429 const c_int_num = const C<int, num>();""");
4430 EvaluationResultImpl b_int_num =
4431 _evaluateInstanceCreationExpression(compilationUnit, "b_int_num");
4432 Map<String, DartObjectImpl> b_int_num_fields =
4433 _assertType(b_int_num, "B<int, num>");
4434 _assertFieldType(b_int_num_fields, GenericState.SUPERCLASS_FIELD, "A<int>");
4435 EvaluationResultImpl c_int_num =
4436 _evaluateInstanceCreationExpression(compilationUnit, "c_int_num");
4437 Map<String, DartObjectImpl> c_int_num_fields =
4438 _assertType(c_int_num, "C<int, num>");
4439 _assertFieldType(c_int_num_fields, GenericState.SUPERCLASS_FIELD, "A<num>");
4440 }
4441
4442 void _checkInstanceCreationOptionalParams(bool isFieldFormal, bool isNamed,
4443 bool hasDefault) {
4444 String fieldName = "j";
4445 String paramName = isFieldFormal ? fieldName : "i";
4446 String formalParam =
4447 "${isFieldFormal ? "this." : "int "}$paramName${hasDefault ? " = 3" : "" }";
4448 CompilationUnit compilationUnit = resolveSource("""
4449 const x = const A();
4450 const y = const A(${isNamed ? '$paramName: ' : ''}10);
4451 class A {
4452 const A(${isNamed ? "{$formalParam}" : "[$formalParam]"})${isFieldFormal ? "" : " : $fieldName = $paramName"};
4453 final int $fieldName;
4454 }""");
4455 EvaluationResultImpl x =
4456 _evaluateInstanceCreationExpression(compilationUnit, "x");
4457 Map<String, DartObjectImpl> fieldsOfX = _assertType(x, "A");
4458 expect(fieldsOfX, hasLength(1));
4459 if (hasDefault) {
4460 _assertIntField(fieldsOfX, fieldName, 3);
4461 } else {
4462 _assertNullField(fieldsOfX, fieldName);
4463 }
4464 EvaluationResultImpl y =
4465 _evaluateInstanceCreationExpression(compilationUnit, "y");
4466 Map<String, DartObjectImpl> fieldsOfY = _assertType(y, "A");
4467 expect(fieldsOfY, hasLength(1));
4468 _assertIntField(fieldsOfY, fieldName, 10);
4469 }
4470
4471 EvaluationResultImpl
4472 _evaluateInstanceCreationExpression(CompilationUnit compilationUnit,
4473 String name) {
4474 Expression expression =
4475 findTopLevelConstantExpression(compilationUnit, name);
4476 return (expression as InstanceCreationExpression).evaluationResult;
4477 }
4478
4479 ConstantValueComputer _makeConstantValueComputer() {
4480 return new ValidatingConstantValueComputer(
4481 analysisContext2.typeProvider,
4482 analysisContext2.declaredVariables);
4483 }
4484
4485 void _validate(bool shouldBeValid, VariableDeclarationList declarationList) {
4486 for (VariableDeclaration declaration in declarationList.variables) {
4487 VariableElementImpl element = declaration.element as VariableElementImpl;
4488 expect(element, isNotNull);
4489 EvaluationResultImpl result = element.evaluationResult;
4490 if (shouldBeValid) {
4491 expect(result.value, isNotNull);
4492 } else {
4493 expect(result.value, isNull);
4494 }
4495 }
4496 }
4497 }
4498
4499
4500 class ConstantValueComputerTest_ValidatingConstantVisitor extends
4501 ConstantVisitor {
4502 final DirectedGraph<AstNode> _referenceGraph;
4503 final AstNode _nodeBeingEvaluated;
4504
4505 ConstantValueComputerTest_ValidatingConstantVisitor(TypeProvider typeProvider,
4506 this._referenceGraph, this._nodeBeingEvaluated, ErrorReporter errorReporte r)
4507 : super.con1(typeProvider, errorReporter);
4508
4509 @override
4510 void beforeGetEvaluationResult(AstNode node) {
4511 super.beforeGetEvaluationResult(node);
4512 // If we are getting the evaluation result for a node in the graph,
4513 // make sure we properly recorded the dependency.
4514 if (_referenceGraph.nodes.contains(node)) {
4515 expect(_referenceGraph.containsPath(_nodeBeingEvaluated, node), isTrue);
4516 }
4517 }
4518 }
4519
4520
4521 class ConstantVisitorTest extends ResolverTestCase {
4522 void test_visitConditionalExpression_false() {
4523 Expression thenExpression = AstFactory.integer(1);
4524 Expression elseExpression = AstFactory.integer(0);
4525 ConditionalExpression expression = AstFactory.conditionalExpression(
4526 AstFactory.booleanLiteral(false),
4527 thenExpression,
4528 elseExpression);
4529 GatheringErrorListener errorListener = new GatheringErrorListener();
4530 ErrorReporter errorReporter =
4531 new ErrorReporter(errorListener, _dummySource());
4532 _assertValue(
4533 0,
4534 expression.accept(
4535 new ConstantVisitor.con1(new TestTypeProvider(), errorReporter)));
4536 errorListener.assertNoErrors();
4537 }
4538
4539 void
4540 test_visitConditionalExpression_instanceCreation_invalidFieldInitializer() {
4541 TestTypeProvider typeProvider = new TestTypeProvider();
4542 LibraryElementImpl libraryElement = ElementFactory.library(null, "lib");
4543 String className = "C";
4544 ClassElementImpl classElement = ElementFactory.classElement2(className);
4545 (libraryElement.definingCompilationUnit as CompilationUnitElementImpl).types =
4546 <ClassElement>[classElement];
4547 ConstructorElementImpl constructorElement =
4548 ElementFactory.constructorElement(
4549 classElement,
4550 null,
4551 true,
4552 [typeProvider.intType]);
4553 constructorElement.parameters[0] =
4554 new FieldFormalParameterElementImpl(AstFactory.identifier3("x"));
4555 InstanceCreationExpression expression =
4556 AstFactory.instanceCreationExpression2(
4557 Keyword.CONST,
4558 AstFactory.typeName4(className),
4559 [AstFactory.integer(0)]);
4560 expression.staticElement = constructorElement;
4561 GatheringErrorListener errorListener = new GatheringErrorListener();
4562 ErrorReporter errorReporter =
4563 new ErrorReporter(errorListener, _dummySource());
4564 expression.accept(new ConstantVisitor.con1(typeProvider, errorReporter));
4565 errorListener.assertErrorsWithCodes(
4566 [CompileTimeErrorCode.INVALID_CONSTANT]);
4567 }
4568
4569 void test_visitConditionalExpression_nonBooleanCondition() {
4570 Expression thenExpression = AstFactory.integer(1);
4571 Expression elseExpression = AstFactory.integer(0);
4572 NullLiteral conditionExpression = AstFactory.nullLiteral();
4573 ConditionalExpression expression = AstFactory.conditionalExpression(
4574 conditionExpression,
4575 thenExpression,
4576 elseExpression);
4577 GatheringErrorListener errorListener = new GatheringErrorListener();
4578 ErrorReporter errorReporter =
4579 new ErrorReporter(errorListener, _dummySource());
4580 DartObjectImpl result = expression.accept(
4581 new ConstantVisitor.con1(new TestTypeProvider(), errorReporter));
4582 expect(result, isNull);
4583 errorListener.assertErrorsWithCodes(
4584 [CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL]);
4585 }
4586
4587 void test_visitConditionalExpression_nonConstantElse() {
4588 Expression thenExpression = AstFactory.integer(1);
4589 Expression elseExpression = AstFactory.identifier3("x");
4590 ConditionalExpression expression = AstFactory.conditionalExpression(
4591 AstFactory.booleanLiteral(true),
4592 thenExpression,
4593 elseExpression);
4594 GatheringErrorListener errorListener = new GatheringErrorListener();
4595 ErrorReporter errorReporter =
4596 new ErrorReporter(errorListener, _dummySource());
4597 DartObjectImpl result = expression.accept(
4598 new ConstantVisitor.con1(new TestTypeProvider(), errorReporter));
4599 expect(result, isNull);
4600 errorListener.assertErrorsWithCodes(
4601 [CompileTimeErrorCode.INVALID_CONSTANT]);
4602 }
4603
4604 void test_visitConditionalExpression_nonConstantThen() {
4605 Expression thenExpression = AstFactory.identifier3("x");
4606 Expression elseExpression = AstFactory.integer(0);
4607 ConditionalExpression expression = AstFactory.conditionalExpression(
4608 AstFactory.booleanLiteral(true),
4609 thenExpression,
4610 elseExpression);
4611 GatheringErrorListener errorListener = new GatheringErrorListener();
4612 ErrorReporter errorReporter =
4613 new ErrorReporter(errorListener, _dummySource());
4614 DartObjectImpl result = expression.accept(
4615 new ConstantVisitor.con1(new TestTypeProvider(), errorReporter));
4616 expect(result, isNull);
4617 errorListener.assertErrorsWithCodes(
4618 [CompileTimeErrorCode.INVALID_CONSTANT]);
4619 }
4620
4621 void test_visitConditionalExpression_true() {
4622 Expression thenExpression = AstFactory.integer(1);
4623 Expression elseExpression = AstFactory.integer(0);
4624 ConditionalExpression expression = AstFactory.conditionalExpression(
4625 AstFactory.booleanLiteral(true),
4626 thenExpression,
4627 elseExpression);
4628 GatheringErrorListener errorListener = new GatheringErrorListener();
4629 ErrorReporter errorReporter =
4630 new ErrorReporter(errorListener, _dummySource());
4631 _assertValue(
4632 1,
4633 expression.accept(
4634 new ConstantVisitor.con1(new TestTypeProvider(), errorReporter)));
4635 errorListener.assertNoErrors();
4636 }
4637
4638 void test_visitSimpleIdentifier_inEnvironment() {
4639 CompilationUnit compilationUnit = resolveSource(r'''
4640 const a = b;
4641 const b = 3;''');
4642 Map<String, DartObjectImpl> environment = new Map<String, DartObjectImpl>();
4643 DartObjectImpl six =
4644 new DartObjectImpl(typeProvider.intType, new IntState(6));
4645 environment["b"] = six;
4646 _assertValue(6, _evaluateConstant(compilationUnit, "a", environment));
4647 }
4648
4649 void test_visitSimpleIdentifier_notInEnvironment() {
4650 CompilationUnit compilationUnit = resolveSource(r'''
4651 const a = b;
4652 const b = 3;''');
4653 Map<String, DartObjectImpl> environment = new Map<String, DartObjectImpl>();
4654 DartObjectImpl six =
4655 new DartObjectImpl(typeProvider.intType, new IntState(6));
4656 environment["c"] = six;
4657 _assertValue(3, _evaluateConstant(compilationUnit, "a", environment));
4658 }
4659
4660 void test_visitSimpleIdentifier_withoutEnvironment() {
4661 CompilationUnit compilationUnit = resolveSource(r'''
4662 const a = b;
4663 const b = 3;''');
4664 _assertValue(3, _evaluateConstant(compilationUnit, "a", null));
4665 }
4666
4667 void _assertValue(int expectedValue, DartObjectImpl result) {
4668 expect(result, isNotNull);
4669 expect(result.type.name, "int");
4670 expect(result.intValue, expectedValue);
4671 }
4672
4673 NonExistingSource _dummySource() {
4674 return new NonExistingSource("foo.dart", UriKind.FILE_URI);
4675 }
4676
4677 DartObjectImpl _evaluateConstant(CompilationUnit compilationUnit, String name,
4678 Map<String, DartObjectImpl> lexicalEnvironment) {
4679 Source source = compilationUnit.element.source;
4680 Expression expression =
4681 findTopLevelConstantExpression(compilationUnit, name);
4682 GatheringErrorListener errorListener = new GatheringErrorListener();
4683 ErrorReporter errorReporter = new ErrorReporter(errorListener, source);
4684 DartObjectImpl result = expression.accept(
4685 new ConstantVisitor.con2(typeProvider, lexicalEnvironment, errorReporter ));
4686 errorListener.assertNoErrors();
4687 return result;
4688 }
4689 }
4690
4691
4692 class ContentCacheTest {
4693 void test_setContents() {
4694 Source source = new TestSource();
4695 ContentCache cache = new ContentCache();
4696 expect(cache.getContents(source), isNull);
4697 expect(cache.getModificationStamp(source), isNull);
4698 String contents = "library lib;";
4699 expect(cache.setContents(source, contents), isNull);
4700 expect(cache.getContents(source), contents);
4701 expect(cache.getModificationStamp(source), isNotNull);
4702 expect(cache.setContents(source, contents), contents);
4703 expect(cache.setContents(source, null), contents);
4704 expect(cache.getContents(source), isNull);
4705 expect(cache.getModificationStamp(source), isNull);
4706 expect(cache.setContents(source, null), isNull);
4707 }
4708 }
4709
4710
4711 class DartObjectImplTest extends EngineTestCase {
4712 TypeProvider _typeProvider = new TestTypeProvider();
4713
4714 void fail_add_knownString_knownString() {
4715 fail("New constant semantics are not yet enabled");
4716 _assertAdd(_stringValue("ab"), _stringValue("a"), _stringValue("b"));
4717 }
4718
4719 void fail_add_knownString_unknownString() {
4720 fail("New constant semantics are not yet enabled");
4721 _assertAdd(_stringValue(null), _stringValue("a"), _stringValue(null));
4722 }
4723
4724 void fail_add_unknownString_knownString() {
4725 fail("New constant semantics are not yet enabled");
4726 _assertAdd(_stringValue(null), _stringValue(null), _stringValue("b"));
4727 }
4728 void fail_add_unknownString_unknownString() {
4729 fail("New constant semantics are not yet enabled");
4730 _assertAdd(_stringValue(null), _stringValue(null), _stringValue(null));
4731 }
4732
4733 void test_add_knownDouble_knownDouble() {
4734 _assertAdd(_doubleValue(3.0), _doubleValue(1.0), _doubleValue(2.0));
4735 }
4736
4737 void test_add_knownDouble_knownInt() {
4738 _assertAdd(_doubleValue(3.0), _doubleValue(1.0), _intValue(2));
4739 }
4740
4741 void test_add_knownDouble_unknownDouble() {
4742 _assertAdd(_doubleValue(null), _doubleValue(1.0), _doubleValue(null));
4743 }
4744
4745 void test_add_knownDouble_unknownInt() {
4746 _assertAdd(_doubleValue(null), _doubleValue(1.0), _intValue(null));
4747 }
4748
4749 void test_add_knownInt_knownInt() {
4750 _assertAdd(_intValue(3), _intValue(1), _intValue(2));
4751 }
4752
4753 void test_add_knownInt_knownString() {
4754 _assertAdd(null, _intValue(1), _stringValue("2"));
4755 }
4756
4757 void test_add_knownInt_unknownDouble() {
4758 _assertAdd(_doubleValue(null), _intValue(1), _doubleValue(null));
4759 }
4760
4761 void test_add_knownInt_unknownInt() {
4762 _assertAdd(_intValue(null), _intValue(1), _intValue(null));
4763 }
4764
4765 void test_add_knownString_knownInt() {
4766 _assertAdd(null, _stringValue("1"), _intValue(2));
4767 }
4768
4769 void test_add_unknownDouble_knownDouble() {
4770 _assertAdd(_doubleValue(null), _doubleValue(null), _doubleValue(2.0));
4771 }
4772
4773 void test_add_unknownDouble_knownInt() {
4774 _assertAdd(_doubleValue(null), _doubleValue(null), _intValue(2));
4775 }
4776
4777 void test_add_unknownInt_knownDouble() {
4778 _assertAdd(_doubleValue(null), _intValue(null), _doubleValue(2.0));
4779 }
4780
4781 void test_add_unknownInt_knownInt() {
4782 _assertAdd(_intValue(null), _intValue(null), _intValue(2));
4783 }
4784 void test_bitAnd_knownInt_knownInt() {
4785 _assertBitAnd(_intValue(2), _intValue(6), _intValue(3));
4786 }
4787
4788 void test_bitAnd_knownInt_knownString() {
4789 _assertBitAnd(null, _intValue(6), _stringValue("3"));
4790 }
4791
4792 void test_bitAnd_knownInt_unknownInt() {
4793 _assertBitAnd(_intValue(null), _intValue(6), _intValue(null));
4794 }
4795
4796 void test_bitAnd_knownString_knownInt() {
4797 _assertBitAnd(null, _stringValue("6"), _intValue(3));
4798 }
4799
4800 void test_bitAnd_unknownInt_knownInt() {
4801 _assertBitAnd(_intValue(null), _intValue(null), _intValue(3));
4802 }
4803
4804 void test_bitAnd_unknownInt_unknownInt() {
4805 _assertBitAnd(_intValue(null), _intValue(null), _intValue(null));
4806 }
4807
4808 void test_bitNot_knownInt() {
4809 _assertBitNot(_intValue(-4), _intValue(3));
4810 }
4811
4812 void test_bitNot_knownString() {
4813 _assertBitNot(null, _stringValue("6"));
4814 }
4815
4816 void test_bitNot_unknownInt() {
4817 _assertBitNot(_intValue(null), _intValue(null));
4818 }
4819
4820 void test_bitOr_knownInt_knownInt() {
4821 _assertBitOr(_intValue(7), _intValue(6), _intValue(3));
4822 }
4823
4824 void test_bitOr_knownInt_knownString() {
4825 _assertBitOr(null, _intValue(6), _stringValue("3"));
4826 }
4827
4828 void test_bitOr_knownInt_unknownInt() {
4829 _assertBitOr(_intValue(null), _intValue(6), _intValue(null));
4830 }
4831
4832 void test_bitOr_knownString_knownInt() {
4833 _assertBitOr(null, _stringValue("6"), _intValue(3));
4834 }
4835
4836 void test_bitOr_unknownInt_knownInt() {
4837 _assertBitOr(_intValue(null), _intValue(null), _intValue(3));
4838 }
4839
4840 void test_bitOr_unknownInt_unknownInt() {
4841 _assertBitOr(_intValue(null), _intValue(null), _intValue(null));
4842 }
4843
4844 void test_bitXor_knownInt_knownInt() {
4845 _assertBitXor(_intValue(5), _intValue(6), _intValue(3));
4846 }
4847
4848 void test_bitXor_knownInt_knownString() {
4849 _assertBitXor(null, _intValue(6), _stringValue("3"));
4850 }
4851
4852 void test_bitXor_knownInt_unknownInt() {
4853 _assertBitXor(_intValue(null), _intValue(6), _intValue(null));
4854 }
4855
4856 void test_bitXor_knownString_knownInt() {
4857 _assertBitXor(null, _stringValue("6"), _intValue(3));
4858 }
4859
4860 void test_bitXor_unknownInt_knownInt() {
4861 _assertBitXor(_intValue(null), _intValue(null), _intValue(3));
4862 }
4863
4864 void test_bitXor_unknownInt_unknownInt() {
4865 _assertBitXor(_intValue(null), _intValue(null), _intValue(null));
4866 }
4867
4868 void test_concatenate_knownInt_knownString() {
4869 _assertConcatenate(null, _intValue(2), _stringValue("def"));
4870 }
4871
4872 void test_concatenate_knownString_knownInt() {
4873 _assertConcatenate(null, _stringValue("abc"), _intValue(3));
4874 }
4875
4876 void test_concatenate_knownString_knownString() {
4877 _assertConcatenate(
4878 _stringValue("abcdef"),
4879 _stringValue("abc"),
4880 _stringValue("def"));
4881 }
4882
4883 void test_concatenate_knownString_unknownString() {
4884 _assertConcatenate(
4885 _stringValue(null),
4886 _stringValue("abc"),
4887 _stringValue(null));
4888 }
4889
4890 void test_concatenate_unknownString_knownString() {
4891 _assertConcatenate(
4892 _stringValue(null),
4893 _stringValue(null),
4894 _stringValue("def"));
4895 }
4896
4897 void test_divide_knownDouble_knownDouble() {
4898 _assertDivide(_doubleValue(3.0), _doubleValue(6.0), _doubleValue(2.0));
4899 }
4900
4901 void test_divide_knownDouble_knownInt() {
4902 _assertDivide(_doubleValue(3.0), _doubleValue(6.0), _intValue(2));
4903 }
4904
4905 void test_divide_knownDouble_unknownDouble() {
4906 _assertDivide(_doubleValue(null), _doubleValue(6.0), _doubleValue(null));
4907 }
4908
4909 void test_divide_knownDouble_unknownInt() {
4910 _assertDivide(_doubleValue(null), _doubleValue(6.0), _intValue(null));
4911 }
4912
4913 void test_divide_knownInt_knownInt() {
4914 _assertDivide(_intValue(3), _intValue(6), _intValue(2));
4915 }
4916
4917 void test_divide_knownInt_knownString() {
4918 _assertDivide(null, _intValue(6), _stringValue("2"));
4919 }
4920
4921 void test_divide_knownInt_unknownDouble() {
4922 _assertDivide(_doubleValue(null), _intValue(6), _doubleValue(null));
4923 }
4924
4925 void test_divide_knownInt_unknownInt() {
4926 _assertDivide(_intValue(null), _intValue(6), _intValue(null));
4927 }
4928
4929 void test_divide_knownString_knownInt() {
4930 _assertDivide(null, _stringValue("6"), _intValue(2));
4931 }
4932
4933 void test_divide_unknownDouble_knownDouble() {
4934 _assertDivide(_doubleValue(null), _doubleValue(null), _doubleValue(2.0));
4935 }
4936
4937 void test_divide_unknownDouble_knownInt() {
4938 _assertDivide(_doubleValue(null), _doubleValue(null), _intValue(2));
4939 }
4940
4941 void test_divide_unknownInt_knownDouble() {
4942 _assertDivide(_doubleValue(null), _intValue(null), _doubleValue(2.0));
4943 }
4944
4945 void test_divide_unknownInt_knownInt() {
4946 _assertDivide(_intValue(null), _intValue(null), _intValue(2));
4947 }
4948
4949 void test_equalEqual_bool_false() {
4950 _assertEqualEqual(_boolValue(false), _boolValue(false), _boolValue(true));
4951 }
4952
4953 void test_equalEqual_bool_true() {
4954 _assertEqualEqual(_boolValue(true), _boolValue(true), _boolValue(true));
4955 }
4956
4957 void test_equalEqual_bool_unknown() {
4958 _assertEqualEqual(_boolValue(null), _boolValue(null), _boolValue(false));
4959 }
4960
4961 void test_equalEqual_double_false() {
4962 _assertEqualEqual(_boolValue(false), _doubleValue(2.0), _doubleValue(4.0));
4963 }
4964
4965 void test_equalEqual_double_true() {
4966 _assertEqualEqual(_boolValue(true), _doubleValue(2.0), _doubleValue(2.0));
4967 }
4968
4969 void test_equalEqual_double_unknown() {
4970 _assertEqualEqual(_boolValue(null), _doubleValue(1.0), _doubleValue(null));
4971 }
4972
4973 void test_equalEqual_int_false() {
4974 _assertEqualEqual(_boolValue(false), _intValue(-5), _intValue(5));
4975 }
4976
4977 void test_equalEqual_int_true() {
4978 _assertEqualEqual(_boolValue(true), _intValue(5), _intValue(5));
4979 }
4980
4981 void test_equalEqual_int_unknown() {
4982 _assertEqualEqual(_boolValue(null), _intValue(null), _intValue(3));
4983 }
4984
4985 void test_equalEqual_list_empty() {
4986 _assertEqualEqual(null, _listValue(), _listValue());
4987 }
4988
4989 void test_equalEqual_list_false() {
4990 _assertEqualEqual(null, _listValue(), _listValue());
4991 }
4992
4993 void test_equalEqual_map_empty() {
4994 _assertEqualEqual(null, _mapValue(), _mapValue());
4995 }
4996
4997 void test_equalEqual_map_false() {
4998 _assertEqualEqual(null, _mapValue(), _mapValue());
4999 }
5000
5001 void test_equalEqual_null() {
5002 _assertEqualEqual(_boolValue(true), _nullValue(), _nullValue());
5003 }
5004
5005 void test_equalEqual_string_false() {
5006 _assertEqualEqual(
5007 _boolValue(false),
5008 _stringValue("abc"),
5009 _stringValue("def"));
5010 }
5011
5012 void test_equalEqual_string_true() {
5013 _assertEqualEqual(
5014 _boolValue(true),
5015 _stringValue("abc"),
5016 _stringValue("abc"));
5017 }
5018
5019 void test_equalEqual_string_unknown() {
5020 _assertEqualEqual(
5021 _boolValue(null),
5022 _stringValue(null),
5023 _stringValue("def"));
5024 }
5025
5026 void test_equals_list_false_differentSizes() {
5027 expect(
5028 _listValue([_boolValue(true)]) ==
5029 _listValue([_boolValue(true), _boolValue(false)]),
5030 isFalse);
5031 }
5032
5033 void test_equals_list_false_sameSize() {
5034 expect(
5035 _listValue([_boolValue(true)]) == _listValue([_boolValue(false)]),
5036 isFalse);
5037 }
5038
5039 void test_equals_list_true_empty() {
5040 expect(_listValue(), _listValue());
5041 }
5042
5043 void test_equals_list_true_nonEmpty() {
5044 expect(_listValue([_boolValue(true)]), _listValue([_boolValue(true)]));
5045 }
5046
5047 void test_equals_map_true_empty() {
5048 expect(_mapValue(), _mapValue());
5049 }
5050
5051 void test_equals_symbol_false() {
5052 expect(_symbolValue("a") == _symbolValue("b"), isFalse);
5053 }
5054
5055 void test_equals_symbol_true() {
5056 expect(_symbolValue("a"), _symbolValue("a"));
5057 }
5058
5059 void test_getValue_bool_false() {
5060 expect(_boolValue(false).value, false);
5061 }
5062
5063 void test_getValue_bool_true() {
5064 expect(_boolValue(true).value, true);
5065 }
5066
5067 void test_getValue_bool_unknown() {
5068 expect(_boolValue(null).value, isNull);
5069 }
5070
5071 void test_getValue_double_known() {
5072 double value = 2.3;
5073 expect(_doubleValue(value).value, value);
5074 }
5075
5076 void test_getValue_double_unknown() {
5077 expect(_doubleValue(null).value, isNull);
5078 }
5079
5080 void test_getValue_int_known() {
5081 int value = 23;
5082 expect(_intValue(value).value, value);
5083 }
5084
5085 void test_getValue_int_unknown() {
5086 expect(_intValue(null).value, isNull);
5087 }
5088
5089 void test_getValue_list_empty() {
5090 Object result = _listValue().value;
5091 _assertInstanceOfObjectArray(result);
5092 List<Object> array = result as List<Object>;
5093 expect(array, hasLength(0));
5094 }
5095
5096 void test_getValue_list_valid() {
5097 Object result = _listValue([_intValue(23)]).value;
5098 _assertInstanceOfObjectArray(result);
5099 List<Object> array = result as List<Object>;
5100 expect(array, hasLength(1));
5101 }
5102
5103 void test_getValue_map_empty() {
5104 Object result = _mapValue().value;
5105 EngineTestCase.assertInstanceOf((obj) => obj is Map, Map, result);
5106 Map map = result as Map;
5107 expect(map, hasLength(0));
5108 }
5109
5110 void test_getValue_map_valid() {
5111 Object result =
5112 _mapValue([_stringValue("key"), _stringValue("value")]).value;
5113 EngineTestCase.assertInstanceOf((obj) => obj is Map, Map, result);
5114 Map map = result as Map;
5115 expect(map, hasLength(1));
5116 }
5117
5118 void test_getValue_null() {
5119 expect(_nullValue().value, isNull);
5120 }
5121
5122 void test_getValue_string_known() {
5123 String value = "twenty-three";
5124 expect(_stringValue(value).value, value);
5125 }
5126
5127 void test_getValue_string_unknown() {
5128 expect(_stringValue(null).value, isNull);
5129 }
5130
5131 void test_greaterThan_knownDouble_knownDouble_false() {
5132 _assertGreaterThan(_boolValue(false), _doubleValue(1.0), _doubleValue(2.0));
5133 }
5134
5135 void test_greaterThan_knownDouble_knownDouble_true() {
5136 _assertGreaterThan(_boolValue(true), _doubleValue(2.0), _doubleValue(1.0));
5137 }
5138
5139 void test_greaterThan_knownDouble_knownInt_false() {
5140 _assertGreaterThan(_boolValue(false), _doubleValue(1.0), _intValue(2));
5141 }
5142
5143 void test_greaterThan_knownDouble_knownInt_true() {
5144 _assertGreaterThan(_boolValue(true), _doubleValue(2.0), _intValue(1));
5145 }
5146
5147 void test_greaterThan_knownDouble_unknownDouble() {
5148 _assertGreaterThan(_boolValue(null), _doubleValue(1.0), _doubleValue(null));
5149 }
5150
5151 void test_greaterThan_knownDouble_unknownInt() {
5152 _assertGreaterThan(_boolValue(null), _doubleValue(1.0), _intValue(null));
5153 }
5154
5155 void test_greaterThan_knownInt_knownInt_false() {
5156 _assertGreaterThan(_boolValue(false), _intValue(1), _intValue(2));
5157 }
5158
5159 void test_greaterThan_knownInt_knownInt_true() {
5160 _assertGreaterThan(_boolValue(true), _intValue(2), _intValue(1));
5161 }
5162
5163 void test_greaterThan_knownInt_knownString() {
5164 _assertGreaterThan(null, _intValue(1), _stringValue("2"));
5165 }
5166
5167 void test_greaterThan_knownInt_unknownDouble() {
5168 _assertGreaterThan(_boolValue(null), _intValue(1), _doubleValue(null));
5169 }
5170
5171 void test_greaterThan_knownInt_unknownInt() {
5172 _assertGreaterThan(_boolValue(null), _intValue(1), _intValue(null));
5173 }
5174
5175 void test_greaterThan_knownString_knownInt() {
5176 _assertGreaterThan(null, _stringValue("1"), _intValue(2));
5177 }
5178
5179 void test_greaterThan_unknownDouble_knownDouble() {
5180 _assertGreaterThan(_boolValue(null), _doubleValue(null), _doubleValue(2.0));
5181 }
5182
5183 void test_greaterThan_unknownDouble_knownInt() {
5184 _assertGreaterThan(_boolValue(null), _doubleValue(null), _intValue(2));
5185 }
5186
5187 void test_greaterThan_unknownInt_knownDouble() {
5188 _assertGreaterThan(_boolValue(null), _intValue(null), _doubleValue(2.0));
5189 }
5190
5191 void test_greaterThan_unknownInt_knownInt() {
5192 _assertGreaterThan(_boolValue(null), _intValue(null), _intValue(2));
5193 }
5194
5195 void test_greaterThanOrEqual_knownDouble_knownDouble_false() {
5196 _assertGreaterThanOrEqual(
5197 _boolValue(false),
5198 _doubleValue(1.0),
5199 _doubleValue(2.0));
5200 }
5201
5202 void test_greaterThanOrEqual_knownDouble_knownDouble_true() {
5203 _assertGreaterThanOrEqual(
5204 _boolValue(true),
5205 _doubleValue(2.0),
5206 _doubleValue(1.0));
5207 }
5208
5209 void test_greaterThanOrEqual_knownDouble_knownInt_false() {
5210 _assertGreaterThanOrEqual(
5211 _boolValue(false),
5212 _doubleValue(1.0),
5213 _intValue(2));
5214 }
5215
5216 void test_greaterThanOrEqual_knownDouble_knownInt_true() {
5217 _assertGreaterThanOrEqual(
5218 _boolValue(true),
5219 _doubleValue(2.0),
5220 _intValue(1));
5221 }
5222
5223 void test_greaterThanOrEqual_knownDouble_unknownDouble() {
5224 _assertGreaterThanOrEqual(
5225 _boolValue(null),
5226 _doubleValue(1.0),
5227 _doubleValue(null));
5228 }
5229
5230 void test_greaterThanOrEqual_knownDouble_unknownInt() {
5231 _assertGreaterThanOrEqual(
5232 _boolValue(null),
5233 _doubleValue(1.0),
5234 _intValue(null));
5235 }
5236
5237 void test_greaterThanOrEqual_knownInt_knownInt_false() {
5238 _assertGreaterThanOrEqual(_boolValue(false), _intValue(1), _intValue(2));
5239 }
5240
5241 void test_greaterThanOrEqual_knownInt_knownInt_true() {
5242 _assertGreaterThanOrEqual(_boolValue(true), _intValue(2), _intValue(2));
5243 }
5244
5245 void test_greaterThanOrEqual_knownInt_knownString() {
5246 _assertGreaterThanOrEqual(null, _intValue(1), _stringValue("2"));
5247 }
5248
5249 void test_greaterThanOrEqual_knownInt_unknownDouble() {
5250 _assertGreaterThanOrEqual(
5251 _boolValue(null),
5252 _intValue(1),
5253 _doubleValue(null));
5254 }
5255
5256 void test_greaterThanOrEqual_knownInt_unknownInt() {
5257 _assertGreaterThanOrEqual(_boolValue(null), _intValue(1), _intValue(null));
5258 }
5259
5260 void test_greaterThanOrEqual_knownString_knownInt() {
5261 _assertGreaterThanOrEqual(null, _stringValue("1"), _intValue(2));
5262 }
5263
5264 void test_greaterThanOrEqual_unknownDouble_knownDouble() {
5265 _assertGreaterThanOrEqual(
5266 _boolValue(null),
5267 _doubleValue(null),
5268 _doubleValue(2.0));
5269 }
5270
5271 void test_greaterThanOrEqual_unknownDouble_knownInt() {
5272 _assertGreaterThanOrEqual(
5273 _boolValue(null),
5274 _doubleValue(null),
5275 _intValue(2));
5276 }
5277
5278 void test_greaterThanOrEqual_unknownInt_knownDouble() {
5279 _assertGreaterThanOrEqual(
5280 _boolValue(null),
5281 _intValue(null),
5282 _doubleValue(2.0));
5283 }
5284
5285 void test_greaterThanOrEqual_unknownInt_knownInt() {
5286 _assertGreaterThanOrEqual(_boolValue(null), _intValue(null), _intValue(2));
5287 }
5288
5289 void test_hasExactValue_bool_false() {
5290 expect(_boolValue(false).hasExactValue, isTrue);
5291 }
5292
5293 void test_hasExactValue_bool_true() {
5294 expect(_boolValue(true).hasExactValue, isTrue);
5295 }
5296
5297 void test_hasExactValue_bool_unknown() {
5298 expect(_boolValue(null).hasExactValue, isTrue);
5299 }
5300
5301 void test_hasExactValue_double_known() {
5302 expect(_doubleValue(2.3).hasExactValue, isTrue);
5303 }
5304
5305 void test_hasExactValue_double_unknown() {
5306 expect(_doubleValue(null).hasExactValue, isTrue);
5307 }
5308
5309 void test_hasExactValue_dynamic() {
5310 expect(_dynamicValue().hasExactValue, isFalse);
5311 }
5312
5313 void test_hasExactValue_int_known() {
5314 expect(_intValue(23).hasExactValue, isTrue);
5315 }
5316
5317 void test_hasExactValue_int_unknown() {
5318 expect(_intValue(null).hasExactValue, isTrue);
5319 }
5320
5321 void test_hasExactValue_list_empty() {
5322 expect(_listValue().hasExactValue, isTrue);
5323 }
5324
5325 void test_hasExactValue_list_invalid() {
5326 expect(_dynamicValue().hasExactValue, isFalse);
5327 }
5328
5329 void test_hasExactValue_list_valid() {
5330 expect(_listValue([_intValue(23)]).hasExactValue, isTrue);
5331 }
5332
5333 void test_hasExactValue_map_empty() {
5334 expect(_mapValue().hasExactValue, isTrue);
5335 }
5336
5337 void test_hasExactValue_map_invalidKey() {
5338 expect(
5339 _mapValue([_dynamicValue(), _stringValue("value")]).hasExactValue,
5340 isFalse);
5341 }
5342
5343 void test_hasExactValue_map_invalidValue() {
5344 expect(
5345 _mapValue([_stringValue("key"), _dynamicValue()]).hasExactValue,
5346 isFalse);
5347 }
5348
5349 void test_hasExactValue_map_valid() {
5350 expect(
5351 _mapValue([_stringValue("key"), _stringValue("value")]).hasExactValue,
5352 isTrue);
5353 }
5354
5355 void test_hasExactValue_null() {
5356 expect(_nullValue().hasExactValue, isTrue);
5357 }
5358
5359 void test_hasExactValue_num() {
5360 expect(_numValue().hasExactValue, isFalse);
5361 }
5362
5363 void test_hasExactValue_string_known() {
5364 expect(_stringValue("twenty-three").hasExactValue, isTrue);
5365 }
5366
5367 void test_hasExactValue_string_unknown() {
5368 expect(_stringValue(null).hasExactValue, isTrue);
5369 }
5370
5371 void test_identical_bool_false() {
5372 _assertIdentical(_boolValue(false), _boolValue(false), _boolValue(true));
5373 }
5374
5375 void test_identical_bool_true() {
5376 _assertIdentical(_boolValue(true), _boolValue(true), _boolValue(true));
5377 }
5378
5379 void test_identical_bool_unknown() {
5380 _assertIdentical(_boolValue(null), _boolValue(null), _boolValue(false));
5381 }
5382
5383 void test_identical_double_false() {
5384 _assertIdentical(_boolValue(false), _doubleValue(2.0), _doubleValue(4.0));
5385 }
5386
5387 void test_identical_double_true() {
5388 _assertIdentical(_boolValue(true), _doubleValue(2.0), _doubleValue(2.0));
5389 }
5390
5391 void test_identical_double_unknown() {
5392 _assertIdentical(_boolValue(null), _doubleValue(1.0), _doubleValue(null));
5393 }
5394
5395 void test_identical_int_false() {
5396 _assertIdentical(_boolValue(false), _intValue(-5), _intValue(5));
5397 }
5398
5399 void test_identical_int_true() {
5400 _assertIdentical(_boolValue(true), _intValue(5), _intValue(5));
5401 }
5402
5403 void test_identical_int_unknown() {
5404 _assertIdentical(_boolValue(null), _intValue(null), _intValue(3));
5405 }
5406
5407 void test_identical_list_empty() {
5408 _assertIdentical(_boolValue(true), _listValue(), _listValue());
5409 }
5410
5411 void test_identical_list_false() {
5412 _assertIdentical(
5413 _boolValue(false),
5414 _listValue(),
5415 _listValue([_intValue(3)]));
5416 }
5417
5418 void test_identical_map_empty() {
5419 _assertIdentical(_boolValue(true), _mapValue(), _mapValue());
5420 }
5421
5422 void test_identical_map_false() {
5423 _assertIdentical(
5424 _boolValue(false),
5425 _mapValue(),
5426 _mapValue([_intValue(1), _intValue(2)]));
5427 }
5428
5429 void test_identical_null() {
5430 _assertIdentical(_boolValue(true), _nullValue(), _nullValue());
5431 }
5432
5433 void test_identical_string_false() {
5434 _assertIdentical(
5435 _boolValue(false),
5436 _stringValue("abc"),
5437 _stringValue("def"));
5438 }
5439
5440 void test_identical_string_true() {
5441 _assertIdentical(
5442 _boolValue(true),
5443 _stringValue("abc"),
5444 _stringValue("abc"));
5445 }
5446
5447 void test_identical_string_unknown() {
5448 _assertIdentical(_boolValue(null), _stringValue(null), _stringValue("def"));
5449 }
5450
5451 void test_integerDivide_knownDouble_knownDouble() {
5452 _assertIntegerDivide(_intValue(3), _doubleValue(6.0), _doubleValue(2.0));
5453 }
5454
5455 void test_integerDivide_knownDouble_knownInt() {
5456 _assertIntegerDivide(_intValue(3), _doubleValue(6.0), _intValue(2));
5457 }
5458
5459 void test_integerDivide_knownDouble_unknownDouble() {
5460 _assertIntegerDivide(
5461 _intValue(null),
5462 _doubleValue(6.0),
5463 _doubleValue(null));
5464 }
5465
5466 void test_integerDivide_knownDouble_unknownInt() {
5467 _assertIntegerDivide(_intValue(null), _doubleValue(6.0), _intValue(null));
5468 }
5469
5470 void test_integerDivide_knownInt_knownInt() {
5471 _assertIntegerDivide(_intValue(3), _intValue(6), _intValue(2));
5472 }
5473
5474 void test_integerDivide_knownInt_knownString() {
5475 _assertIntegerDivide(null, _intValue(6), _stringValue("2"));
5476 }
5477
5478 void test_integerDivide_knownInt_unknownDouble() {
5479 _assertIntegerDivide(_intValue(null), _intValue(6), _doubleValue(null));
5480 }
5481
5482 void test_integerDivide_knownInt_unknownInt() {
5483 _assertIntegerDivide(_intValue(null), _intValue(6), _intValue(null));
5484 }
5485
5486 void test_integerDivide_knownString_knownInt() {
5487 _assertIntegerDivide(null, _stringValue("6"), _intValue(2));
5488 }
5489
5490 void test_integerDivide_unknownDouble_knownDouble() {
5491 _assertIntegerDivide(
5492 _intValue(null),
5493 _doubleValue(null),
5494 _doubleValue(2.0));
5495 }
5496
5497 void test_integerDivide_unknownDouble_knownInt() {
5498 _assertIntegerDivide(_intValue(null), _doubleValue(null), _intValue(2));
5499 }
5500
5501 void test_integerDivide_unknownInt_knownDouble() {
5502 _assertIntegerDivide(_intValue(null), _intValue(null), _doubleValue(2.0));
5503 }
5504
5505 void test_integerDivide_unknownInt_knownInt() {
5506 _assertIntegerDivide(_intValue(null), _intValue(null), _intValue(2));
5507 }
5508
5509 void test_isBoolNumStringOrNull_bool_false() {
5510 expect(_boolValue(false).isBoolNumStringOrNull, isTrue);
5511 }
5512
5513 void test_isBoolNumStringOrNull_bool_true() {
5514 expect(_boolValue(true).isBoolNumStringOrNull, isTrue);
5515 }
5516
5517 void test_isBoolNumStringOrNull_bool_unknown() {
5518 expect(_boolValue(null).isBoolNumStringOrNull, isTrue);
5519 }
5520
5521 void test_isBoolNumStringOrNull_double_known() {
5522 expect(_doubleValue(2.3).isBoolNumStringOrNull, isTrue);
5523 }
5524
5525 void test_isBoolNumStringOrNull_double_unknown() {
5526 expect(_doubleValue(null).isBoolNumStringOrNull, isTrue);
5527 }
5528
5529 void test_isBoolNumStringOrNull_dynamic() {
5530 expect(_dynamicValue().isBoolNumStringOrNull, isTrue);
5531 }
5532
5533 void test_isBoolNumStringOrNull_int_known() {
5534 expect(_intValue(23).isBoolNumStringOrNull, isTrue);
5535 }
5536
5537 void test_isBoolNumStringOrNull_int_unknown() {
5538 expect(_intValue(null).isBoolNumStringOrNull, isTrue);
5539 }
5540
5541 void test_isBoolNumStringOrNull_list() {
5542 expect(_listValue().isBoolNumStringOrNull, isFalse);
5543 }
5544
5545 void test_isBoolNumStringOrNull_null() {
5546 expect(_nullValue().isBoolNumStringOrNull, isTrue);
5547 }
5548
5549 void test_isBoolNumStringOrNull_num() {
5550 expect(_numValue().isBoolNumStringOrNull, isTrue);
5551 }
5552
5553 void test_isBoolNumStringOrNull_string_known() {
5554 expect(_stringValue("twenty-three").isBoolNumStringOrNull, isTrue);
5555 }
5556
5557 void test_isBoolNumStringOrNull_string_unknown() {
5558 expect(_stringValue(null).isBoolNumStringOrNull, isTrue);
5559 }
5560
5561 void test_lessThan_knownDouble_knownDouble_false() {
5562 _assertLessThan(_boolValue(false), _doubleValue(2.0), _doubleValue(1.0));
5563 }
5564
5565 void test_lessThan_knownDouble_knownDouble_true() {
5566 _assertLessThan(_boolValue(true), _doubleValue(1.0), _doubleValue(2.0));
5567 }
5568
5569 void test_lessThan_knownDouble_knownInt_false() {
5570 _assertLessThan(_boolValue(false), _doubleValue(2.0), _intValue(1));
5571 }
5572
5573 void test_lessThan_knownDouble_knownInt_true() {
5574 _assertLessThan(_boolValue(true), _doubleValue(1.0), _intValue(2));
5575 }
5576
5577 void test_lessThan_knownDouble_unknownDouble() {
5578 _assertLessThan(_boolValue(null), _doubleValue(1.0), _doubleValue(null));
5579 }
5580
5581 void test_lessThan_knownDouble_unknownInt() {
5582 _assertLessThan(_boolValue(null), _doubleValue(1.0), _intValue(null));
5583 }
5584
5585 void test_lessThan_knownInt_knownInt_false() {
5586 _assertLessThan(_boolValue(false), _intValue(2), _intValue(1));
5587 }
5588
5589 void test_lessThan_knownInt_knownInt_true() {
5590 _assertLessThan(_boolValue(true), _intValue(1), _intValue(2));
5591 }
5592
5593 void test_lessThan_knownInt_knownString() {
5594 _assertLessThan(null, _intValue(1), _stringValue("2"));
5595 }
5596
5597 void test_lessThan_knownInt_unknownDouble() {
5598 _assertLessThan(_boolValue(null), _intValue(1), _doubleValue(null));
5599 }
5600
5601 void test_lessThan_knownInt_unknownInt() {
5602 _assertLessThan(_boolValue(null), _intValue(1), _intValue(null));
5603 }
5604
5605 void test_lessThan_knownString_knownInt() {
5606 _assertLessThan(null, _stringValue("1"), _intValue(2));
5607 }
5608
5609 void test_lessThan_unknownDouble_knownDouble() {
5610 _assertLessThan(_boolValue(null), _doubleValue(null), _doubleValue(2.0));
5611 }
5612
5613 void test_lessThan_unknownDouble_knownInt() {
5614 _assertLessThan(_boolValue(null), _doubleValue(null), _intValue(2));
5615 }
5616
5617 void test_lessThan_unknownInt_knownDouble() {
5618 _assertLessThan(_boolValue(null), _intValue(null), _doubleValue(2.0));
5619 }
5620
5621 void test_lessThan_unknownInt_knownInt() {
5622 _assertLessThan(_boolValue(null), _intValue(null), _intValue(2));
5623 }
5624
5625 void test_lessThanOrEqual_knownDouble_knownDouble_false() {
5626 _assertLessThanOrEqual(
5627 _boolValue(false),
5628 _doubleValue(2.0),
5629 _doubleValue(1.0));
5630 }
5631
5632 void test_lessThanOrEqual_knownDouble_knownDouble_true() {
5633 _assertLessThanOrEqual(
5634 _boolValue(true),
5635 _doubleValue(1.0),
5636 _doubleValue(2.0));
5637 }
5638
5639 void test_lessThanOrEqual_knownDouble_knownInt_false() {
5640 _assertLessThanOrEqual(_boolValue(false), _doubleValue(2.0), _intValue(1));
5641 }
5642
5643 void test_lessThanOrEqual_knownDouble_knownInt_true() {
5644 _assertLessThanOrEqual(_boolValue(true), _doubleValue(1.0), _intValue(2));
5645 }
5646
5647 void test_lessThanOrEqual_knownDouble_unknownDouble() {
5648 _assertLessThanOrEqual(
5649 _boolValue(null),
5650 _doubleValue(1.0),
5651 _doubleValue(null));
5652 }
5653
5654 void test_lessThanOrEqual_knownDouble_unknownInt() {
5655 _assertLessThanOrEqual(
5656 _boolValue(null),
5657 _doubleValue(1.0),
5658 _intValue(null));
5659 }
5660
5661 void test_lessThanOrEqual_knownInt_knownInt_false() {
5662 _assertLessThanOrEqual(_boolValue(false), _intValue(2), _intValue(1));
5663 }
5664
5665 void test_lessThanOrEqual_knownInt_knownInt_true() {
5666 _assertLessThanOrEqual(_boolValue(true), _intValue(1), _intValue(2));
5667 }
5668
5669 void test_lessThanOrEqual_knownInt_knownString() {
5670 _assertLessThanOrEqual(null, _intValue(1), _stringValue("2"));
5671 }
5672
5673 void test_lessThanOrEqual_knownInt_unknownDouble() {
5674 _assertLessThanOrEqual(_boolValue(null), _intValue(1), _doubleValue(null));
5675 }
5676
5677 void test_lessThanOrEqual_knownInt_unknownInt() {
5678 _assertLessThanOrEqual(_boolValue(null), _intValue(1), _intValue(null));
5679 }
5680
5681 void test_lessThanOrEqual_knownString_knownInt() {
5682 _assertLessThanOrEqual(null, _stringValue("1"), _intValue(2));
5683 }
5684
5685 void test_lessThanOrEqual_unknownDouble_knownDouble() {
5686 _assertLessThanOrEqual(
5687 _boolValue(null),
5688 _doubleValue(null),
5689 _doubleValue(2.0));
5690 }
5691
5692 void test_lessThanOrEqual_unknownDouble_knownInt() {
5693 _assertLessThanOrEqual(_boolValue(null), _doubleValue(null), _intValue(2));
5694 }
5695
5696 void test_lessThanOrEqual_unknownInt_knownDouble() {
5697 _assertLessThanOrEqual(
5698 _boolValue(null),
5699 _intValue(null),
5700 _doubleValue(2.0));
5701 }
5702
5703 void test_lessThanOrEqual_unknownInt_knownInt() {
5704 _assertLessThanOrEqual(_boolValue(null), _intValue(null), _intValue(2));
5705 }
5706
5707 void test_logicalAnd_false_false() {
5708 _assertLogicalAnd(_boolValue(false), _boolValue(false), _boolValue(false));
5709 }
5710
5711 void test_logicalAnd_false_null() {
5712 try {
5713 _assertLogicalAnd(_boolValue(false), _boolValue(false), _nullValue());
5714 fail("Expected EvaluationException");
5715 } on EvaluationException catch (exception) {
5716 }
5717 }
5718
5719 void test_logicalAnd_false_string() {
5720 try {
5721 _assertLogicalAnd(
5722 _boolValue(false),
5723 _boolValue(false),
5724 _stringValue("false"));
5725 fail("Expected EvaluationException");
5726 } on EvaluationException catch (exception) {
5727 }
5728 }
5729
5730 void test_logicalAnd_false_true() {
5731 _assertLogicalAnd(_boolValue(false), _boolValue(false), _boolValue(true));
5732 }
5733
5734 void test_logicalAnd_null_false() {
5735 try {
5736 _assertLogicalAnd(_boolValue(false), _nullValue(), _boolValue(false));
5737 fail("Expected EvaluationException");
5738 } on EvaluationException catch (exception) {
5739 }
5740 }
5741
5742 void test_logicalAnd_null_true() {
5743 try {
5744 _assertLogicalAnd(_boolValue(false), _nullValue(), _boolValue(true));
5745 fail("Expected EvaluationException");
5746 } on EvaluationException catch (exception) {
5747 }
5748 }
5749
5750 void test_logicalAnd_string_false() {
5751 try {
5752 _assertLogicalAnd(
5753 _boolValue(false),
5754 _stringValue("true"),
5755 _boolValue(false));
5756 fail("Expected EvaluationException");
5757 } on EvaluationException catch (exception) {
5758 }
5759 }
5760
5761 void test_logicalAnd_string_true() {
5762 try {
5763 _assertLogicalAnd(
5764 _boolValue(false),
5765 _stringValue("false"),
5766 _boolValue(true));
5767 fail("Expected EvaluationException");
5768 } on EvaluationException catch (exception) {
5769 }
5770 }
5771
5772 void test_logicalAnd_true_false() {
5773 _assertLogicalAnd(_boolValue(false), _boolValue(true), _boolValue(false));
5774 }
5775
5776 void test_logicalAnd_true_null() {
5777 _assertLogicalAnd(null, _boolValue(true), _nullValue());
5778 }
5779
5780 void test_logicalAnd_true_string() {
5781 try {
5782 _assertLogicalAnd(
5783 _boolValue(false),
5784 _boolValue(true),
5785 _stringValue("true"));
5786 fail("Expected EvaluationException");
5787 } on EvaluationException catch (exception) {
5788 }
5789 }
5790
5791 void test_logicalAnd_true_true() {
5792 _assertLogicalAnd(_boolValue(true), _boolValue(true), _boolValue(true));
5793 }
5794
5795 void test_logicalNot_false() {
5796 _assertLogicalNot(_boolValue(true), _boolValue(false));
5797 }
5798
5799 void test_logicalNot_null() {
5800 _assertLogicalNot(null, _nullValue());
5801 }
5802
5803 void test_logicalNot_string() {
5804 try {
5805 _assertLogicalNot(_boolValue(true), _stringValue(null));
5806 fail("Expected EvaluationException");
5807 } on EvaluationException catch (exception) {
5808 }
5809 }
5810
5811 void test_logicalNot_true() {
5812 _assertLogicalNot(_boolValue(false), _boolValue(true));
5813 }
5814
5815 void test_logicalNot_unknown() {
5816 _assertLogicalNot(_boolValue(null), _boolValue(null));
5817 }
5818
5819 void test_logicalOr_false_false() {
5820 _assertLogicalOr(_boolValue(false), _boolValue(false), _boolValue(false));
5821 }
5822
5823 void test_logicalOr_false_null() {
5824 _assertLogicalOr(null, _boolValue(false), _nullValue());
5825 }
5826
5827 void test_logicalOr_false_string() {
5828 try {
5829 _assertLogicalOr(
5830 _boolValue(false),
5831 _boolValue(false),
5832 _stringValue("false"));
5833 fail("Expected EvaluationException");
5834 } on EvaluationException catch (exception) {
5835 }
5836 }
5837
5838 void test_logicalOr_false_true() {
5839 _assertLogicalOr(_boolValue(true), _boolValue(false), _boolValue(true));
5840 }
5841
5842 void test_logicalOr_null_false() {
5843 try {
5844 _assertLogicalOr(_boolValue(false), _nullValue(), _boolValue(false));
5845 fail("Expected EvaluationException");
5846 } on EvaluationException catch (exception) {
5847 }
5848 }
5849
5850 void test_logicalOr_null_true() {
5851 try {
5852 _assertLogicalOr(_boolValue(true), _nullValue(), _boolValue(true));
5853 fail("Expected EvaluationException");
5854 } on EvaluationException catch (exception) {
5855 }
5856 }
5857
5858 void test_logicalOr_string_false() {
5859 try {
5860 _assertLogicalOr(
5861 _boolValue(false),
5862 _stringValue("true"),
5863 _boolValue(false));
5864 fail("Expected EvaluationException");
5865 } on EvaluationException catch (exception) {
5866 }
5867 }
5868
5869 void test_logicalOr_string_true() {
5870 try {
5871 _assertLogicalOr(
5872 _boolValue(true),
5873 _stringValue("false"),
5874 _boolValue(true));
5875 fail("Expected EvaluationException");
5876 } on EvaluationException catch (exception) {
5877 }
5878 }
5879
5880 void test_logicalOr_true_false() {
5881 _assertLogicalOr(_boolValue(true), _boolValue(true), _boolValue(false));
5882 }
5883
5884 void test_logicalOr_true_null() {
5885 try {
5886 _assertLogicalOr(_boolValue(true), _boolValue(true), _nullValue());
5887 fail("Expected EvaluationException");
5888 } on EvaluationException catch (exception) {
5889 }
5890 }
5891
5892 void test_logicalOr_true_string() {
5893 try {
5894 _assertLogicalOr(
5895 _boolValue(true),
5896 _boolValue(true),
5897 _stringValue("true"));
5898 fail("Expected EvaluationException");
5899 } on EvaluationException catch (exception) {
5900 }
5901 }
5902
5903 void test_logicalOr_true_true() {
5904 _assertLogicalOr(_boolValue(true), _boolValue(true), _boolValue(true));
5905 }
5906
5907 void test_minus_knownDouble_knownDouble() {
5908 _assertMinus(_doubleValue(1.0), _doubleValue(4.0), _doubleValue(3.0));
5909 }
5910
5911 void test_minus_knownDouble_knownInt() {
5912 _assertMinus(_doubleValue(1.0), _doubleValue(4.0), _intValue(3));
5913 }
5914
5915 void test_minus_knownDouble_unknownDouble() {
5916 _assertMinus(_doubleValue(null), _doubleValue(4.0), _doubleValue(null));
5917 }
5918
5919 void test_minus_knownDouble_unknownInt() {
5920 _assertMinus(_doubleValue(null), _doubleValue(4.0), _intValue(null));
5921 }
5922
5923 void test_minus_knownInt_knownInt() {
5924 _assertMinus(_intValue(1), _intValue(4), _intValue(3));
5925 }
5926
5927 void test_minus_knownInt_knownString() {
5928 _assertMinus(null, _intValue(4), _stringValue("3"));
5929 }
5930
5931 void test_minus_knownInt_unknownDouble() {
5932 _assertMinus(_doubleValue(null), _intValue(4), _doubleValue(null));
5933 }
5934
5935 void test_minus_knownInt_unknownInt() {
5936 _assertMinus(_intValue(null), _intValue(4), _intValue(null));
5937 }
5938
5939 void test_minus_knownString_knownInt() {
5940 _assertMinus(null, _stringValue("4"), _intValue(3));
5941 }
5942
5943 void test_minus_unknownDouble_knownDouble() {
5944 _assertMinus(_doubleValue(null), _doubleValue(null), _doubleValue(3.0));
5945 }
5946
5947 void test_minus_unknownDouble_knownInt() {
5948 _assertMinus(_doubleValue(null), _doubleValue(null), _intValue(3));
5949 }
5950
5951 void test_minus_unknownInt_knownDouble() {
5952 _assertMinus(_doubleValue(null), _intValue(null), _doubleValue(3.0));
5953 }
5954
5955 void test_minus_unknownInt_knownInt() {
5956 _assertMinus(_intValue(null), _intValue(null), _intValue(3));
5957 }
5958
5959 void test_negated_double_known() {
5960 _assertNegated(_doubleValue(2.0), _doubleValue(-2.0));
5961 }
5962
5963 void test_negated_double_unknown() {
5964 _assertNegated(_doubleValue(null), _doubleValue(null));
5965 }
5966
5967 void test_negated_int_known() {
5968 _assertNegated(_intValue(-3), _intValue(3));
5969 }
5970
5971 void test_negated_int_unknown() {
5972 _assertNegated(_intValue(null), _intValue(null));
5973 }
5974
5975 void test_negated_string() {
5976 _assertNegated(null, _stringValue(null));
5977 }
5978
5979 void test_notEqual_bool_false() {
5980 _assertNotEqual(_boolValue(false), _boolValue(true), _boolValue(true));
5981 }
5982
5983 void test_notEqual_bool_true() {
5984 _assertNotEqual(_boolValue(true), _boolValue(false), _boolValue(true));
5985 }
5986
5987 void test_notEqual_bool_unknown() {
5988 _assertNotEqual(_boolValue(null), _boolValue(null), _boolValue(false));
5989 }
5990
5991 void test_notEqual_double_false() {
5992 _assertNotEqual(_boolValue(false), _doubleValue(2.0), _doubleValue(2.0));
5993 }
5994
5995 void test_notEqual_double_true() {
5996 _assertNotEqual(_boolValue(true), _doubleValue(2.0), _doubleValue(4.0));
5997 }
5998
5999 void test_notEqual_double_unknown() {
6000 _assertNotEqual(_boolValue(null), _doubleValue(1.0), _doubleValue(null));
6001 }
6002
6003 void test_notEqual_int_false() {
6004 _assertNotEqual(_boolValue(false), _intValue(5), _intValue(5));
6005 }
6006
6007 void test_notEqual_int_true() {
6008 _assertNotEqual(_boolValue(true), _intValue(-5), _intValue(5));
6009 }
6010
6011 void test_notEqual_int_unknown() {
6012 _assertNotEqual(_boolValue(null), _intValue(null), _intValue(3));
6013 }
6014
6015 void test_notEqual_null() {
6016 _assertNotEqual(_boolValue(false), _nullValue(), _nullValue());
6017 }
6018
6019 void test_notEqual_string_false() {
6020 _assertNotEqual(
6021 _boolValue(false),
6022 _stringValue("abc"),
6023 _stringValue("abc"));
6024 }
6025
6026 void test_notEqual_string_true() {
6027 _assertNotEqual(_boolValue(true), _stringValue("abc"), _stringValue("def"));
6028 }
6029
6030 void test_notEqual_string_unknown() {
6031 _assertNotEqual(_boolValue(null), _stringValue(null), _stringValue("def"));
6032 }
6033
6034 void test_performToString_bool_false() {
6035 _assertPerformToString(_stringValue("false"), _boolValue(false));
6036 }
6037
6038 void test_performToString_bool_true() {
6039 _assertPerformToString(_stringValue("true"), _boolValue(true));
6040 }
6041
6042 void test_performToString_bool_unknown() {
6043 _assertPerformToString(_stringValue(null), _boolValue(null));
6044 }
6045
6046 void test_performToString_double_known() {
6047 _assertPerformToString(_stringValue("2.0"), _doubleValue(2.0));
6048 }
6049
6050 void test_performToString_double_unknown() {
6051 _assertPerformToString(_stringValue(null), _doubleValue(null));
6052 }
6053
6054 void test_performToString_int_known() {
6055 _assertPerformToString(_stringValue("5"), _intValue(5));
6056 }
6057
6058 void test_performToString_int_unknown() {
6059 _assertPerformToString(_stringValue(null), _intValue(null));
6060 }
6061
6062 void test_performToString_null() {
6063 _assertPerformToString(_stringValue("null"), _nullValue());
6064 }
6065
6066 void test_performToString_string_known() {
6067 _assertPerformToString(_stringValue("abc"), _stringValue("abc"));
6068 }
6069
6070 void test_performToString_string_unknown() {
6071 _assertPerformToString(_stringValue(null), _stringValue(null));
6072 }
6073
6074 void test_remainder_knownDouble_knownDouble() {
6075 _assertRemainder(_doubleValue(1.0), _doubleValue(7.0), _doubleValue(2.0));
6076 }
6077
6078 void test_remainder_knownDouble_knownInt() {
6079 _assertRemainder(_doubleValue(1.0), _doubleValue(7.0), _intValue(2));
6080 }
6081
6082 void test_remainder_knownDouble_unknownDouble() {
6083 _assertRemainder(_doubleValue(null), _doubleValue(7.0), _doubleValue(null));
6084 }
6085
6086 void test_remainder_knownDouble_unknownInt() {
6087 _assertRemainder(_doubleValue(null), _doubleValue(6.0), _intValue(null));
6088 }
6089
6090 void test_remainder_knownInt_knownInt() {
6091 _assertRemainder(_intValue(1), _intValue(7), _intValue(2));
6092 }
6093
6094 void test_remainder_knownInt_knownString() {
6095 _assertRemainder(null, _intValue(7), _stringValue("2"));
6096 }
6097
6098 void test_remainder_knownInt_unknownDouble() {
6099 _assertRemainder(_doubleValue(null), _intValue(7), _doubleValue(null));
6100 }
6101
6102 void test_remainder_knownInt_unknownInt() {
6103 _assertRemainder(_intValue(null), _intValue(7), _intValue(null));
6104 }
6105
6106 void test_remainder_knownString_knownInt() {
6107 _assertRemainder(null, _stringValue("7"), _intValue(2));
6108 }
6109
6110 void test_remainder_unknownDouble_knownDouble() {
6111 _assertRemainder(_doubleValue(null), _doubleValue(null), _doubleValue(2.0));
6112 }
6113
6114 void test_remainder_unknownDouble_knownInt() {
6115 _assertRemainder(_doubleValue(null), _doubleValue(null), _intValue(2));
6116 }
6117
6118 void test_remainder_unknownInt_knownDouble() {
6119 _assertRemainder(_doubleValue(null), _intValue(null), _doubleValue(2.0));
6120 }
6121
6122 void test_remainder_unknownInt_knownInt() {
6123 _assertRemainder(_intValue(null), _intValue(null), _intValue(2));
6124 }
6125
6126 void test_shiftLeft_knownInt_knownInt() {
6127 _assertShiftLeft(_intValue(48), _intValue(6), _intValue(3));
6128 }
6129
6130 void test_shiftLeft_knownInt_knownString() {
6131 _assertShiftLeft(null, _intValue(6), _stringValue(null));
6132 }
6133
6134 void test_shiftLeft_knownInt_tooLarge() {
6135 _assertShiftLeft(
6136 _intValue(null),
6137 _intValue(6),
6138 new DartObjectImpl(_typeProvider.intType, new IntState(LONG_MAX_VALUE))) ;
6139 }
6140
6141 void test_shiftLeft_knownInt_unknownInt() {
6142 _assertShiftLeft(_intValue(null), _intValue(6), _intValue(null));
6143 }
6144
6145 void test_shiftLeft_knownString_knownInt() {
6146 _assertShiftLeft(null, _stringValue(null), _intValue(3));
6147 }
6148
6149 void test_shiftLeft_unknownInt_knownInt() {
6150 _assertShiftLeft(_intValue(null), _intValue(null), _intValue(3));
6151 }
6152
6153 void test_shiftLeft_unknownInt_unknownInt() {
6154 _assertShiftLeft(_intValue(null), _intValue(null), _intValue(null));
6155 }
6156
6157 void test_shiftRight_knownInt_knownInt() {
6158 _assertShiftRight(_intValue(6), _intValue(48), _intValue(3));
6159 }
6160
6161 void test_shiftRight_knownInt_knownString() {
6162 _assertShiftRight(null, _intValue(48), _stringValue(null));
6163 }
6164
6165 void test_shiftRight_knownInt_tooLarge() {
6166 _assertShiftRight(
6167 _intValue(null),
6168 _intValue(48),
6169 new DartObjectImpl(_typeProvider.intType, new IntState(LONG_MAX_VALUE))) ;
6170 }
6171
6172 void test_shiftRight_knownInt_unknownInt() {
6173 _assertShiftRight(_intValue(null), _intValue(48), _intValue(null));
6174 }
6175
6176 void test_shiftRight_knownString_knownInt() {
6177 _assertShiftRight(null, _stringValue(null), _intValue(3));
6178 }
6179
6180 void test_shiftRight_unknownInt_knownInt() {
6181 _assertShiftRight(_intValue(null), _intValue(null), _intValue(3));
6182 }
6183
6184 void test_shiftRight_unknownInt_unknownInt() {
6185 _assertShiftRight(_intValue(null), _intValue(null), _intValue(null));
6186 }
6187
6188 void test_stringLength_int() {
6189 try {
6190 _assertStringLength(_intValue(null), _intValue(0));
6191 fail("Expected EvaluationException");
6192 } on EvaluationException catch (exception) {
6193 }
6194 }
6195
6196 void test_stringLength_knownString() {
6197 _assertStringLength(_intValue(3), _stringValue("abc"));
6198 }
6199
6200 void test_stringLength_unknownString() {
6201 _assertStringLength(_intValue(null), _stringValue(null));
6202 }
6203
6204 void test_times_knownDouble_knownDouble() {
6205 _assertTimes(_doubleValue(6.0), _doubleValue(2.0), _doubleValue(3.0));
6206 }
6207
6208 void test_times_knownDouble_knownInt() {
6209 _assertTimes(_doubleValue(6.0), _doubleValue(2.0), _intValue(3));
6210 }
6211
6212 void test_times_knownDouble_unknownDouble() {
6213 _assertTimes(_doubleValue(null), _doubleValue(2.0), _doubleValue(null));
6214 }
6215
6216 void test_times_knownDouble_unknownInt() {
6217 _assertTimes(_doubleValue(null), _doubleValue(2.0), _intValue(null));
6218 }
6219
6220 void test_times_knownInt_knownInt() {
6221 _assertTimes(_intValue(6), _intValue(2), _intValue(3));
6222 }
6223
6224 void test_times_knownInt_knownString() {
6225 _assertTimes(null, _intValue(2), _stringValue("3"));
6226 }
6227
6228 void test_times_knownInt_unknownDouble() {
6229 _assertTimes(_doubleValue(null), _intValue(2), _doubleValue(null));
6230 }
6231
6232 void test_times_knownInt_unknownInt() {
6233 _assertTimes(_intValue(null), _intValue(2), _intValue(null));
6234 }
6235
6236 void test_times_knownString_knownInt() {
6237 _assertTimes(null, _stringValue("2"), _intValue(3));
6238 }
6239
6240 void test_times_unknownDouble_knownDouble() {
6241 _assertTimes(_doubleValue(null), _doubleValue(null), _doubleValue(3.0));
6242 }
6243
6244 void test_times_unknownDouble_knownInt() {
6245 _assertTimes(_doubleValue(null), _doubleValue(null), _intValue(3));
6246 }
6247
6248 void test_times_unknownInt_knownDouble() {
6249 _assertTimes(_doubleValue(null), _intValue(null), _doubleValue(3.0));
6250 }
6251
6252 void test_times_unknownInt_knownInt() {
6253 _assertTimes(_intValue(null), _intValue(null), _intValue(3));
6254 }
6255
6256 /**
6257 * Assert that the result of adding the left and right operands is the expecte d value, or that the
6258 * operation throws an exception if the expected value is `null`.
6259 *
6260 * @param expected the expected result of the operation
6261 * @param leftOperand the left operand to the operation
6262 * @param rightOperand the left operand to the operation
6263 * @throws EvaluationException if the result is an exception when it should no t be
6264 */
6265 void _assertAdd(DartObjectImpl expected, DartObjectImpl leftOperand,
6266 DartObjectImpl rightOperand) {
6267 if (expected == null) {
6268 try {
6269 leftOperand.add(_typeProvider, rightOperand);
6270 fail("Expected an EvaluationException");
6271 } on EvaluationException catch (exception) {
6272 }
6273 } else {
6274 DartObjectImpl result = leftOperand.add(_typeProvider, rightOperand);
6275 expect(result, isNotNull);
6276 expect(result, expected);
6277 }
6278 }
6279
6280 /**
6281 * Assert that the result of bit-anding the left and right operands is the exp ected value, or that
6282 * the operation throws an exception if the expected value is `null`.
6283 *
6284 * @param expected the expected result of the operation
6285 * @param leftOperand the left operand to the operation
6286 * @param rightOperand the left operand to the operation
6287 * @throws EvaluationException if the result is an exception when it should no t be
6288 */
6289 void _assertBitAnd(DartObjectImpl expected, DartObjectImpl leftOperand,
6290 DartObjectImpl rightOperand) {
6291 if (expected == null) {
6292 try {
6293 leftOperand.bitAnd(_typeProvider, rightOperand);
6294 fail("Expected an EvaluationException");
6295 } on EvaluationException catch (exception) {
6296 }
6297 } else {
6298 DartObjectImpl result = leftOperand.bitAnd(_typeProvider, rightOperand);
6299 expect(result, isNotNull);
6300 expect(result, expected);
6301 }
6302 }
6303
6304 /**
6305 * Assert that the bit-not of the operand is the expected value, or that the o peration throws an
6306 * exception if the expected value is `null`.
6307 *
6308 * @param expected the expected result of the operation
6309 * @param operand the operand to the operation
6310 * @throws EvaluationException if the result is an exception when it should no t be
6311 */
6312 void _assertBitNot(DartObjectImpl expected, DartObjectImpl operand) {
6313 if (expected == null) {
6314 try {
6315 operand.bitNot(_typeProvider);
6316 fail("Expected an EvaluationException");
6317 } on EvaluationException catch (exception) {
6318 }
6319 } else {
6320 DartObjectImpl result = operand.bitNot(_typeProvider);
6321 expect(result, isNotNull);
6322 expect(result, expected);
6323 }
6324 }
6325
6326 /**
6327 * Assert that the result of bit-oring the left and right operands is the expe cted value, or that
6328 * the operation throws an exception if the expected value is `null`.
6329 *
6330 * @param expected the expected result of the operation
6331 * @param leftOperand the left operand to the operation
6332 * @param rightOperand the left operand to the operation
6333 * @throws EvaluationException if the result is an exception when it should no t be
6334 */
6335 void _assertBitOr(DartObjectImpl expected, DartObjectImpl leftOperand,
6336 DartObjectImpl rightOperand) {
6337 if (expected == null) {
6338 try {
6339 leftOperand.bitOr(_typeProvider, rightOperand);
6340 fail("Expected an EvaluationException");
6341 } on EvaluationException catch (exception) {
6342 }
6343 } else {
6344 DartObjectImpl result = leftOperand.bitOr(_typeProvider, rightOperand);
6345 expect(result, isNotNull);
6346 expect(result, expected);
6347 }
6348 }
6349
6350 /**
6351 * Assert that the result of bit-xoring the left and right operands is the exp ected value, or that
6352 * the operation throws an exception if the expected value is `null`.
6353 *
6354 * @param expected the expected result of the operation
6355 * @param leftOperand the left operand to the operation
6356 * @param rightOperand the left operand to the operation
6357 * @throws EvaluationException if the result is an exception when it should no t be
6358 */
6359 void _assertBitXor(DartObjectImpl expected, DartObjectImpl leftOperand,
6360 DartObjectImpl rightOperand) {
6361 if (expected == null) {
6362 try {
6363 leftOperand.bitXor(_typeProvider, rightOperand);
6364 fail("Expected an EvaluationException");
6365 } on EvaluationException catch (exception) {
6366 }
6367 } else {
6368 DartObjectImpl result = leftOperand.bitXor(_typeProvider, rightOperand);
6369 expect(result, isNotNull);
6370 expect(result, expected);
6371 }
6372 }
6373
6374 /**
6375 * Assert that the result of concatenating the left and right operands is the expected value, or
6376 * that the operation throws an exception if the expected value is `null`.
6377 *
6378 * @param expected the expected result of the operation
6379 * @param leftOperand the left operand to the operation
6380 * @param rightOperand the left operand to the operation
6381 * @throws EvaluationException if the result is an exception when it should no t be
6382 */
6383 void _assertConcatenate(DartObjectImpl expected, DartObjectImpl leftOperand,
6384 DartObjectImpl rightOperand) {
6385 if (expected == null) {
6386 try {
6387 leftOperand.concatenate(_typeProvider, rightOperand);
6388 fail("Expected an EvaluationException");
6389 } on EvaluationException catch (exception) {
6390 }
6391 } else {
6392 DartObjectImpl result =
6393 leftOperand.concatenate(_typeProvider, rightOperand);
6394 expect(result, isNotNull);
6395 expect(result, expected);
6396 }
6397 }
6398
6399 /**
6400 * Assert that the result of dividing the left and right operands is the expec ted value, or that
6401 * the operation throws an exception if the expected value is `null`.
6402 *
6403 * @param expected the expected result of the operation
6404 * @param leftOperand the left operand to the operation
6405 * @param rightOperand the left operand to the operation
6406 * @throws EvaluationException if the result is an exception when it should no t be
6407 */
6408 void _assertDivide(DartObjectImpl expected, DartObjectImpl leftOperand,
6409 DartObjectImpl rightOperand) {
6410 if (expected == null) {
6411 try {
6412 leftOperand.divide(_typeProvider, rightOperand);
6413 fail("Expected an EvaluationException");
6414 } on EvaluationException catch (exception) {
6415 }
6416 } else {
6417 DartObjectImpl result = leftOperand.divide(_typeProvider, rightOperand);
6418 expect(result, isNotNull);
6419 expect(result, expected);
6420 }
6421 }
6422
6423 /**
6424 * Assert that the result of comparing the left and right operands for equalit y is the expected
6425 * value, or that the operation throws an exception if the expected value is ` null`.
6426 *
6427 * @param expected the expected result of the operation
6428 * @param leftOperand the left operand to the operation
6429 * @param rightOperand the left operand to the operation
6430 * @throws EvaluationException if the result is an exception when it should no t be
6431 */
6432 void _assertEqualEqual(DartObjectImpl expected, DartObjectImpl leftOperand,
6433 DartObjectImpl rightOperand) {
6434 if (expected == null) {
6435 try {
6436 leftOperand.equalEqual(_typeProvider, rightOperand);
6437 fail("Expected an EvaluationException");
6438 } on EvaluationException catch (exception) {
6439 }
6440 } else {
6441 DartObjectImpl result =
6442 leftOperand.equalEqual(_typeProvider, rightOperand);
6443 expect(result, isNotNull);
6444 expect(result, expected);
6445 }
6446 }
6447
6448 /**
6449 * Assert that the result of comparing the left and right operands is the expe cted value, or that
6450 * the operation throws an exception if the expected value is `null`.
6451 *
6452 * @param expected the expected result of the operation
6453 * @param leftOperand the left operand to the operation
6454 * @param rightOperand the left operand to the operation
6455 * @throws EvaluationException if the result is an exception when it should no t be
6456 */
6457 void _assertGreaterThan(DartObjectImpl expected, DartObjectImpl leftOperand,
6458 DartObjectImpl rightOperand) {
6459 if (expected == null) {
6460 try {
6461 leftOperand.greaterThan(_typeProvider, rightOperand);
6462 fail("Expected an EvaluationException");
6463 } on EvaluationException catch (exception) {
6464 }
6465 } else {
6466 DartObjectImpl result =
6467 leftOperand.greaterThan(_typeProvider, rightOperand);
6468 expect(result, isNotNull);
6469 expect(result, expected);
6470 }
6471 }
6472
6473 /**
6474 * Assert that the result of comparing the left and right operands is the expe cted value, or that
6475 * the operation throws an exception if the expected value is `null`.
6476 *
6477 * @param expected the expected result of the operation
6478 * @param leftOperand the left operand to the operation
6479 * @param rightOperand the left operand to the operation
6480 * @throws EvaluationException if the result is an exception when it should no t be
6481 */
6482 void _assertGreaterThanOrEqual(DartObjectImpl expected,
6483 DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
6484 if (expected == null) {
6485 try {
6486 leftOperand.greaterThanOrEqual(_typeProvider, rightOperand);
6487 fail("Expected an EvaluationException");
6488 } on EvaluationException catch (exception) {
6489 }
6490 } else {
6491 DartObjectImpl result =
6492 leftOperand.greaterThanOrEqual(_typeProvider, rightOperand);
6493 expect(result, isNotNull);
6494 expect(result, expected);
6495 }
6496 }
6497
6498 /**
6499 * Assert that the result of comparing the left and right operands using
6500 * identical() is the expected value.
6501 *
6502 * @param expected the expected result of the operation
6503 * @param leftOperand the left operand to the operation
6504 * @param rightOperand the left operand to the operation
6505 */
6506 void _assertIdentical(DartObjectImpl expected, DartObjectImpl leftOperand,
6507 DartObjectImpl rightOperand) {
6508 DartObjectImpl result =
6509 leftOperand.isIdentical(_typeProvider, rightOperand);
6510 expect(result, isNotNull);
6511 expect(result, expected);
6512 }
6513
6514 void _assertInstanceOfObjectArray(Object result) {
6515 // TODO(scheglov) implement
6516 }
6517
6518 /**
6519 * Assert that the result of dividing the left and right operands as integers is the expected
6520 * value, or that the operation throws an exception if the expected value is ` null`.
6521 *
6522 * @param expected the expected result of the operation
6523 * @param leftOperand the left operand to the operation
6524 * @param rightOperand the left operand to the operation
6525 * @throws EvaluationException if the result is an exception when it should no t be
6526 */
6527 void _assertIntegerDivide(DartObjectImpl expected, DartObjectImpl leftOperand,
6528 DartObjectImpl rightOperand) {
6529 if (expected == null) {
6530 try {
6531 leftOperand.integerDivide(_typeProvider, rightOperand);
6532 fail("Expected an EvaluationException");
6533 } on EvaluationException catch (exception) {
6534 }
6535 } else {
6536 DartObjectImpl result =
6537 leftOperand.integerDivide(_typeProvider, rightOperand);
6538 expect(result, isNotNull);
6539 expect(result, expected);
6540 }
6541 }
6542
6543 /**
6544 * Assert that the result of comparing the left and right operands is the expe cted value, or that
6545 * the operation throws an exception if the expected value is `null`.
6546 *
6547 * @param expected the expected result of the operation
6548 * @param leftOperand the left operand to the operation
6549 * @param rightOperand the left operand to the operation
6550 * @throws EvaluationException if the result is an exception when it should no t be
6551 */
6552 void _assertLessThan(DartObjectImpl expected, DartObjectImpl leftOperand,
6553 DartObjectImpl rightOperand) {
6554 if (expected == null) {
6555 try {
6556 leftOperand.lessThan(_typeProvider, rightOperand);
6557 fail("Expected an EvaluationException");
6558 } on EvaluationException catch (exception) {
6559 }
6560 } else {
6561 DartObjectImpl result = leftOperand.lessThan(_typeProvider, rightOperand);
6562 expect(result, isNotNull);
6563 expect(result, expected);
6564 }
6565 }
6566
6567 /**
6568 * Assert that the result of comparing the left and right operands is the expe cted value, or that
6569 * the operation throws an exception if the expected value is `null`.
6570 *
6571 * @param expected the expected result of the operation
6572 * @param leftOperand the left operand to the operation
6573 * @param rightOperand the left operand to the operation
6574 * @throws EvaluationException if the result is an exception when it should no t be
6575 */
6576 void _assertLessThanOrEqual(DartObjectImpl expected,
6577 DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
6578 if (expected == null) {
6579 try {
6580 leftOperand.lessThanOrEqual(_typeProvider, rightOperand);
6581 fail("Expected an EvaluationException");
6582 } on EvaluationException catch (exception) {
6583 }
6584 } else {
6585 DartObjectImpl result =
6586 leftOperand.lessThanOrEqual(_typeProvider, rightOperand);
6587 expect(result, isNotNull);
6588 expect(result, expected);
6589 }
6590 }
6591
6592 /**
6593 * Assert that the result of logical-anding the left and right operands is the expected value, or
6594 * that the operation throws an exception if the expected value is `null`.
6595 *
6596 * @param expected the expected result of the operation
6597 * @param leftOperand the left operand to the operation
6598 * @param rightOperand the left operand to the operation
6599 * @throws EvaluationException if the result is an exception when it should no t be
6600 */
6601 void _assertLogicalAnd(DartObjectImpl expected, DartObjectImpl leftOperand,
6602 DartObjectImpl rightOperand) {
6603 if (expected == null) {
6604 try {
6605 leftOperand.logicalAnd(_typeProvider, rightOperand);
6606 fail("Expected an EvaluationException");
6607 } on EvaluationException catch (exception) {
6608 }
6609 } else {
6610 DartObjectImpl result =
6611 leftOperand.logicalAnd(_typeProvider, rightOperand);
6612 expect(result, isNotNull);
6613 expect(result, expected);
6614 }
6615 }
6616
6617 /**
6618 * Assert that the logical-not of the operand is the expected value, or that t he operation throws
6619 * an exception if the expected value is `null`.
6620 *
6621 * @param expected the expected result of the operation
6622 * @param operand the operand to the operation
6623 * @throws EvaluationException if the result is an exception when it should no t be
6624 */
6625 void _assertLogicalNot(DartObjectImpl expected, DartObjectImpl operand) {
6626 if (expected == null) {
6627 try {
6628 operand.logicalNot(_typeProvider);
6629 fail("Expected an EvaluationException");
6630 } on EvaluationException catch (exception) {
6631 }
6632 } else {
6633 DartObjectImpl result = operand.logicalNot(_typeProvider);
6634 expect(result, isNotNull);
6635 expect(result, expected);
6636 }
6637 }
6638
6639 /**
6640 * Assert that the result of logical-oring the left and right operands is the expected value, or
6641 * that the operation throws an exception if the expected value is `null`.
6642 *
6643 * @param expected the expected result of the operation
6644 * @param leftOperand the left operand to the operation
6645 * @param rightOperand the left operand to the operation
6646 * @throws EvaluationException if the result is an exception when it should no t be
6647 */
6648 void _assertLogicalOr(DartObjectImpl expected, DartObjectImpl leftOperand,
6649 DartObjectImpl rightOperand) {
6650 if (expected == null) {
6651 try {
6652 leftOperand.logicalOr(_typeProvider, rightOperand);
6653 fail("Expected an EvaluationException");
6654 } on EvaluationException catch (exception) {
6655 }
6656 } else {
6657 DartObjectImpl result =
6658 leftOperand.logicalOr(_typeProvider, rightOperand);
6659 expect(result, isNotNull);
6660 expect(result, expected);
6661 }
6662 }
6663
6664 /**
6665 * Assert that the result of subtracting the left and right operands is the ex pected value, or
6666 * that the operation throws an exception if the expected value is `null`.
6667 *
6668 * @param expected the expected result of the operation
6669 * @param leftOperand the left operand to the operation
6670 * @param rightOperand the left operand to the operation
6671 * @throws EvaluationException if the result is an exception when it should no t be
6672 */
6673 void _assertMinus(DartObjectImpl expected, DartObjectImpl leftOperand,
6674 DartObjectImpl rightOperand) {
6675 if (expected == null) {
6676 try {
6677 leftOperand.minus(_typeProvider, rightOperand);
6678 fail("Expected an EvaluationException");
6679 } on EvaluationException catch (exception) {
6680 }
6681 } else {
6682 DartObjectImpl result = leftOperand.minus(_typeProvider, rightOperand);
6683 expect(result, isNotNull);
6684 expect(result, expected);
6685 }
6686 }
6687
6688 /**
6689 * Assert that the negation of the operand is the expected value, or that the operation throws an
6690 * exception if the expected value is `null`.
6691 *
6692 * @param expected the expected result of the operation
6693 * @param operand the operand to the operation
6694 * @throws EvaluationException if the result is an exception when it should no t be
6695 */
6696 void _assertNegated(DartObjectImpl expected, DartObjectImpl operand) {
6697 if (expected == null) {
6698 try {
6699 operand.negated(_typeProvider);
6700 fail("Expected an EvaluationException");
6701 } on EvaluationException catch (exception) {
6702 }
6703 } else {
6704 DartObjectImpl result = operand.negated(_typeProvider);
6705 expect(result, isNotNull);
6706 expect(result, expected);
6707 }
6708 }
6709
6710 /**
6711 * Assert that the result of comparing the left and right operands for inequal ity is the expected
6712 * value, or that the operation throws an exception if the expected value is ` null`.
6713 *
6714 * @param expected the expected result of the operation
6715 * @param leftOperand the left operand to the operation
6716 * @param rightOperand the left operand to the operation
6717 * @throws EvaluationException if the result is an exception when it should no t be
6718 */
6719 void _assertNotEqual(DartObjectImpl expected, DartObjectImpl leftOperand,
6720 DartObjectImpl rightOperand) {
6721 if (expected == null) {
6722 try {
6723 leftOperand.notEqual(_typeProvider, rightOperand);
6724 fail("Expected an EvaluationException");
6725 } on EvaluationException catch (exception) {
6726 }
6727 } else {
6728 DartObjectImpl result = leftOperand.notEqual(_typeProvider, rightOperand);
6729 expect(result, isNotNull);
6730 expect(result, expected);
6731 }
6732 }
6733
6734 /**
6735 * Assert that converting the operand to a string is the expected value, or th at the operation
6736 * throws an exception if the expected value is `null`.
6737 *
6738 * @param expected the expected result of the operation
6739 * @param operand the operand to the operation
6740 * @throws EvaluationException if the result is an exception when it should no t be
6741 */
6742 void _assertPerformToString(DartObjectImpl expected, DartObjectImpl operand) {
6743 if (expected == null) {
6744 try {
6745 operand.performToString(_typeProvider);
6746 fail("Expected an EvaluationException");
6747 } on EvaluationException catch (exception) {
6748 }
6749 } else {
6750 DartObjectImpl result = operand.performToString(_typeProvider);
6751 expect(result, isNotNull);
6752 expect(result, expected);
6753 }
6754 }
6755
6756 /**
6757 * Assert that the result of taking the remainder of the left and right operan ds is the expected
6758 * value, or that the operation throws an exception if the expected value is ` null`.
6759 *
6760 * @param expected the expected result of the operation
6761 * @param leftOperand the left operand to the operation
6762 * @param rightOperand the left operand to the operation
6763 * @throws EvaluationException if the result is an exception when it should no t be
6764 */
6765 void _assertRemainder(DartObjectImpl expected, DartObjectImpl leftOperand,
6766 DartObjectImpl rightOperand) {
6767 if (expected == null) {
6768 try {
6769 leftOperand.remainder(_typeProvider, rightOperand);
6770 fail("Expected an EvaluationException");
6771 } on EvaluationException catch (exception) {
6772 }
6773 } else {
6774 DartObjectImpl result =
6775 leftOperand.remainder(_typeProvider, rightOperand);
6776 expect(result, isNotNull);
6777 expect(result, expected);
6778 }
6779 }
6780
6781 /**
6782 * Assert that the result of multiplying the left and right operands is the ex pected value, or
6783 * that the operation throws an exception if the expected value is `null`.
6784 *
6785 * @param expected the expected result of the operation
6786 * @param leftOperand the left operand to the operation
6787 * @param rightOperand the left operand to the operation
6788 * @throws EvaluationException if the result is an exception when it should no t be
6789 */
6790 void _assertShiftLeft(DartObjectImpl expected, DartObjectImpl leftOperand,
6791 DartObjectImpl rightOperand) {
6792 if (expected == null) {
6793 try {
6794 leftOperand.shiftLeft(_typeProvider, rightOperand);
6795 fail("Expected an EvaluationException");
6796 } on EvaluationException catch (exception) {
6797 }
6798 } else {
6799 DartObjectImpl result =
6800 leftOperand.shiftLeft(_typeProvider, rightOperand);
6801 expect(result, isNotNull);
6802 expect(result, expected);
6803 }
6804 }
6805
6806 /**
6807 * Assert that the result of multiplying the left and right operands is the ex pected value, or
6808 * that the operation throws an exception if the expected value is `null`.
6809 *
6810 * @param expected the expected result of the operation
6811 * @param leftOperand the left operand to the operation
6812 * @param rightOperand the left operand to the operation
6813 * @throws EvaluationException if the result is an exception when it should no t be
6814 */
6815 void _assertShiftRight(DartObjectImpl expected, DartObjectImpl leftOperand,
6816 DartObjectImpl rightOperand) {
6817 if (expected == null) {
6818 try {
6819 leftOperand.shiftRight(_typeProvider, rightOperand);
6820 fail("Expected an EvaluationException");
6821 } on EvaluationException catch (exception) {
6822 }
6823 } else {
6824 DartObjectImpl result =
6825 leftOperand.shiftRight(_typeProvider, rightOperand);
6826 expect(result, isNotNull);
6827 expect(result, expected);
6828 }
6829 }
6830
6831 /**
6832 * Assert that the length of the operand is the expected value, or that the op eration throws an
6833 * exception if the expected value is `null`.
6834 *
6835 * @param expected the expected result of the operation
6836 * @param operand the operand to the operation
6837 * @throws EvaluationException if the result is an exception when it should no t be
6838 */
6839 void _assertStringLength(DartObjectImpl expected, DartObjectImpl operand) {
6840 if (expected == null) {
6841 try {
6842 operand.stringLength(_typeProvider);
6843 fail("Expected an EvaluationException");
6844 } on EvaluationException catch (exception) {
6845 }
6846 } else {
6847 DartObjectImpl result = operand.stringLength(_typeProvider);
6848 expect(result, isNotNull);
6849 expect(result, expected);
6850 }
6851 }
6852
6853 /**
6854 * Assert that the result of multiplying the left and right operands is the ex pected value, or
6855 * that the operation throws an exception if the expected value is `null`.
6856 *
6857 * @param expected the expected result of the operation
6858 * @param leftOperand the left operand to the operation
6859 * @param rightOperand the left operand to the operation
6860 * @throws EvaluationException if the result is an exception when it should no t be
6861 */
6862 void _assertTimes(DartObjectImpl expected, DartObjectImpl leftOperand,
6863 DartObjectImpl rightOperand) {
6864 if (expected == null) {
6865 try {
6866 leftOperand.times(_typeProvider, rightOperand);
6867 fail("Expected an EvaluationException");
6868 } on EvaluationException catch (exception) {
6869 }
6870 } else {
6871 DartObjectImpl result = leftOperand.times(_typeProvider, rightOperand);
6872 expect(result, isNotNull);
6873 expect(result, expected);
6874 }
6875 }
6876
6877 DartObjectImpl _boolValue(bool value) {
6878 if (value == null) {
6879 return new DartObjectImpl(
6880 _typeProvider.boolType,
6881 BoolState.UNKNOWN_VALUE);
6882 } else if (identical(value, false)) {
6883 return new DartObjectImpl(_typeProvider.boolType, BoolState.FALSE_STATE);
6884 } else if (identical(value, true)) {
6885 return new DartObjectImpl(_typeProvider.boolType, BoolState.TRUE_STATE);
6886 }
6887 fail("Invalid boolean value used in test");
6888 return null;
6889 }
6890
6891 DartObjectImpl _doubleValue(double value) {
6892 if (value == null) {
6893 return new DartObjectImpl(
6894 _typeProvider.doubleType,
6895 DoubleState.UNKNOWN_VALUE);
6896 } else {
6897 return new DartObjectImpl(
6898 _typeProvider.doubleType,
6899 new DoubleState(value));
6900 }
6901 }
6902
6903 DartObjectImpl _dynamicValue() {
6904 return new DartObjectImpl(
6905 _typeProvider.nullType,
6906 DynamicState.DYNAMIC_STATE);
6907 }
6908
6909 DartObjectImpl _intValue(int value) {
6910 if (value == null) {
6911 return new DartObjectImpl(_typeProvider.intType, IntState.UNKNOWN_VALUE);
6912 } else {
6913 return new DartObjectImpl(_typeProvider.intType, new IntState(value));
6914 }
6915 }
6916
6917 DartObjectImpl _listValue([List<DartObjectImpl> elements =
6918 DartObjectImpl.EMPTY_LIST]) {
6919 return new DartObjectImpl(_typeProvider.listType, new ListState(elements));
6920 }
6921
6922 DartObjectImpl _mapValue([List<DartObjectImpl> keyElementPairs =
6923 DartObjectImpl.EMPTY_LIST]) {
6924 Map<DartObjectImpl, DartObjectImpl> map =
6925 new Map<DartObjectImpl, DartObjectImpl>();
6926 int count = keyElementPairs.length;
6927 for (int i = 0; i < count; ) {
6928 map[keyElementPairs[i++]] = keyElementPairs[i++];
6929 }
6930 return new DartObjectImpl(_typeProvider.mapType, new MapState(map));
6931 }
6932
6933 DartObjectImpl _nullValue() {
6934 return new DartObjectImpl(_typeProvider.nullType, NullState.NULL_STATE);
6935 }
6936
6937 DartObjectImpl _numValue() {
6938 return new DartObjectImpl(_typeProvider.nullType, NumState.UNKNOWN_VALUE);
6939 }
6940
6941 DartObjectImpl _stringValue(String value) {
6942 if (value == null) {
6943 return new DartObjectImpl(
6944 _typeProvider.stringType,
6945 StringState.UNKNOWN_VALUE);
6946 } else {
6947 return new DartObjectImpl(
6948 _typeProvider.stringType,
6949 new StringState(value));
6950 }
6951 }
6952
6953 DartObjectImpl _symbolValue(String value) {
6954 return new DartObjectImpl(_typeProvider.symbolType, new SymbolState(value));
6955 }
6956 }
6957
6958
6959 class DartUriResolverTest {
6960 void test_creation() {
6961 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
6962 expect(sdkDirectory, isNotNull);
6963 DartSdk sdk = new DirectoryBasedDartSdk(sdkDirectory);
6964 expect(new DartUriResolver(sdk), isNotNull);
6965 }
6966
6967 void test_isDartUri_null_scheme() {
6968 Uri uri = parseUriWithException("foo.dart");
6969 expect('', uri.scheme);
6970 expect(DartUriResolver.isDartUri(uri), isFalse);
6971 }
6972
6973 void test_resolve_dart() {
6974 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
6975 expect(sdkDirectory, isNotNull);
6976 DartSdk sdk = new DirectoryBasedDartSdk(sdkDirectory);
6977 UriResolver resolver = new DartUriResolver(sdk);
6978 Source result =
6979 resolver.resolveAbsolute(parseUriWithException("dart:core"));
6980 expect(result, isNotNull);
6981 }
6982
6983 void test_resolve_dart_nonExistingLibrary() {
6984 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
6985 expect(sdkDirectory, isNotNull);
6986 DartSdk sdk = new DirectoryBasedDartSdk(sdkDirectory);
6987 UriResolver resolver = new DartUriResolver(sdk);
6988 Source result = resolver.resolveAbsolute(parseUriWithException("dart:cor"));
6989 expect(result, isNull);
6990 }
6991
6992 void test_resolve_nonDart() {
6993 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
6994 expect(sdkDirectory, isNotNull);
6995 DartSdk sdk = new DirectoryBasedDartSdk(sdkDirectory);
6996 UriResolver resolver = new DartUriResolver(sdk);
6997 Source result =
6998 resolver.resolveAbsolute(parseUriWithException("package:some/file.dart") );
6999 expect(result, isNull);
7000 }
7001 }
7002
7003
7004 class DeclaredVariablesTest extends EngineTestCase {
7005 void test_getBool_false() {
7006 TestTypeProvider typeProvider = new TestTypeProvider();
7007 String variableName = "var";
7008 DeclaredVariables variables = new DeclaredVariables();
7009 variables.define(variableName, "false");
7010 DartObject object = variables.getBool(typeProvider, variableName);
7011 expect(object, isNotNull);
7012 expect(object.boolValue, false);
7013 }
7014
7015 void test_getBool_invalid() {
7016 TestTypeProvider typeProvider = new TestTypeProvider();
7017 String variableName = "var";
7018 DeclaredVariables variables = new DeclaredVariables();
7019 variables.define(variableName, "not true");
7020 _assertNullDartObject(
7021 typeProvider,
7022 variables.getBool(typeProvider, variableName));
7023 }
7024
7025 void test_getBool_true() {
7026 TestTypeProvider typeProvider = new TestTypeProvider();
7027 String variableName = "var";
7028 DeclaredVariables variables = new DeclaredVariables();
7029 variables.define(variableName, "true");
7030 DartObject object = variables.getBool(typeProvider, variableName);
7031 expect(object, isNotNull);
7032 expect(object.boolValue, true);
7033 }
7034
7035 void test_getBool_undefined() {
7036 TestTypeProvider typeProvider = new TestTypeProvider();
7037 String variableName = "var";
7038 DeclaredVariables variables = new DeclaredVariables();
7039 _assertUnknownDartObject(
7040 typeProvider.boolType,
7041 variables.getBool(typeProvider, variableName));
7042 }
7043
7044 void test_getInt_invalid() {
7045 TestTypeProvider typeProvider = new TestTypeProvider();
7046 String variableName = "var";
7047 DeclaredVariables variables = new DeclaredVariables();
7048 variables.define(variableName, "four score and seven years");
7049 _assertNullDartObject(
7050 typeProvider,
7051 variables.getInt(typeProvider, variableName));
7052 }
7053
7054 void test_getInt_undefined() {
7055 TestTypeProvider typeProvider = new TestTypeProvider();
7056 String variableName = "var";
7057 DeclaredVariables variables = new DeclaredVariables();
7058 _assertUnknownDartObject(
7059 typeProvider.intType,
7060 variables.getInt(typeProvider, variableName));
7061 }
7062
7063 void test_getInt_valid() {
7064 TestTypeProvider typeProvider = new TestTypeProvider();
7065 String variableName = "var";
7066 DeclaredVariables variables = new DeclaredVariables();
7067 variables.define(variableName, "23");
7068 DartObject object = variables.getInt(typeProvider, variableName);
7069 expect(object, isNotNull);
7070 expect(object.intValue, 23);
7071 }
7072
7073 void test_getString_defined() {
7074 TestTypeProvider typeProvider = new TestTypeProvider();
7075 String variableName = "var";
7076 String value = "value";
7077 DeclaredVariables variables = new DeclaredVariables();
7078 variables.define(variableName, value);
7079 DartObject object = variables.getString(typeProvider, variableName);
7080 expect(object, isNotNull);
7081 expect(object.stringValue, value);
7082 }
7083
7084 void test_getString_undefined() {
7085 TestTypeProvider typeProvider = new TestTypeProvider();
7086 String variableName = "var";
7087 DeclaredVariables variables = new DeclaredVariables();
7088 _assertUnknownDartObject(
7089 typeProvider.stringType,
7090 variables.getString(typeProvider, variableName));
7091 }
7092
7093 void _assertNullDartObject(TestTypeProvider typeProvider, DartObject result) {
7094 expect(result.type, typeProvider.nullType);
7095 }
7096
7097 void _assertUnknownDartObject(ParameterizedType expectedType,
7098 DartObject result) {
7099 expect((result as DartObjectImpl).isUnknown, isTrue);
7100 expect(result.type, expectedType);
7101 }
7102 }
7103
7104
7105 class DirectoryBasedDartSdkTest {
7106 void fail_getDocFileFor() {
7107 DirectoryBasedDartSdk sdk = _createDartSdk();
7108 JavaFile docFile = sdk.getDocFileFor("html");
7109 expect(docFile, isNotNull);
7110 }
7111
7112 void test_creation() {
7113 DirectoryBasedDartSdk sdk = _createDartSdk();
7114 expect(sdk, isNotNull);
7115 }
7116
7117 void test_fromFile_invalid() {
7118 DirectoryBasedDartSdk sdk = _createDartSdk();
7119 expect(
7120 sdk.fromFileUri(new JavaFile("/not/in/the/sdk.dart").toURI()),
7121 isNull);
7122 }
7123
7124 void test_fromFile_library() {
7125 DirectoryBasedDartSdk sdk = _createDartSdk();
7126 Source source = sdk.fromFileUri(
7127 new JavaFile.relative(
7128 new JavaFile.relative(sdk.libraryDirectory, "core"),
7129 "core.dart").toURI());
7130 expect(source, isNotNull);
7131 expect(source.isInSystemLibrary, isTrue);
7132 expect(source.uri.toString(), "dart:core");
7133 }
7134
7135 void test_fromFile_part() {
7136 DirectoryBasedDartSdk sdk = _createDartSdk();
7137 Source source = sdk.fromFileUri(
7138 new JavaFile.relative(
7139 new JavaFile.relative(sdk.libraryDirectory, "core"),
7140 "num.dart").toURI());
7141 expect(source, isNotNull);
7142 expect(source.isInSystemLibrary, isTrue);
7143 expect(source.uri.toString(), "dart:core/num.dart");
7144 }
7145
7146 void test_getDart2JsExecutable() {
7147 DirectoryBasedDartSdk sdk = _createDartSdk();
7148 JavaFile executable = sdk.dart2JsExecutable;
7149 expect(executable, isNotNull);
7150 expect(executable.exists(), isTrue);
7151 expect(executable.isExecutable(), isTrue);
7152 }
7153
7154 void test_getDartFmtExecutable() {
7155 DirectoryBasedDartSdk sdk = _createDartSdk();
7156 JavaFile executable = sdk.dartFmtExecutable;
7157 expect(executable, isNotNull);
7158 expect(executable.exists(), isTrue);
7159 expect(executable.isExecutable(), isTrue);
7160 }
7161
7162 void test_getDirectory() {
7163 DirectoryBasedDartSdk sdk = _createDartSdk();
7164 JavaFile directory = sdk.directory;
7165 expect(directory, isNotNull);
7166 expect(directory.exists(), isTrue);
7167 }
7168
7169 void test_getDocDirectory() {
7170 DirectoryBasedDartSdk sdk = _createDartSdk();
7171 JavaFile directory = sdk.docDirectory;
7172 expect(directory, isNotNull);
7173 }
7174
7175 void test_getLibraryDirectory() {
7176 DirectoryBasedDartSdk sdk = _createDartSdk();
7177 JavaFile directory = sdk.libraryDirectory;
7178 expect(directory, isNotNull);
7179 expect(directory.exists(), isTrue);
7180 }
7181
7182 void test_getPubExecutable() {
7183 DirectoryBasedDartSdk sdk = _createDartSdk();
7184 JavaFile executable = sdk.pubExecutable;
7185 expect(executable, isNotNull);
7186 expect(executable.exists(), isTrue);
7187 expect(executable.isExecutable(), isTrue);
7188 }
7189
7190 void test_getSdkVersion() {
7191 DirectoryBasedDartSdk sdk = _createDartSdk();
7192 String version = sdk.sdkVersion;
7193 expect(version, isNotNull);
7194 expect(version.length > 0, isTrue);
7195 }
7196
7197 void test_getVmExecutable() {
7198 DirectoryBasedDartSdk sdk = _createDartSdk();
7199 JavaFile executable = sdk.vmExecutable;
7200 expect(executable, isNotNull);
7201 expect(executable.exists(), isTrue);
7202 expect(executable.isExecutable(), isTrue);
7203 }
7204
7205 DirectoryBasedDartSdk _createDartSdk() {
7206 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
7207 expect(
7208 sdkDirectory,
7209 isNotNull,
7210 reason:
7211 "No SDK configured; set the property 'com.google.dart.sdk' on the co mmand line");
7212 return new DirectoryBasedDartSdk(sdkDirectory);
7213 }
7214 }
7215
7216
7217 class DirectoryBasedSourceContainerTest {
7218 void test_contains() {
7219 JavaFile dir = FileUtilities2.createFile("/does/not/exist");
7220 JavaFile file1 = FileUtilities2.createFile("/does/not/exist/some.dart");
7221 JavaFile file2 =
7222 FileUtilities2.createFile("/does/not/exist/folder/some2.dart");
7223 JavaFile file3 = FileUtilities2.createFile("/does/not/exist3/some3.dart");
7224 FileBasedSource source1 = new FileBasedSource.con1(file1);
7225 FileBasedSource source2 = new FileBasedSource.con1(file2);
7226 FileBasedSource source3 = new FileBasedSource.con1(file3);
7227 DirectoryBasedSourceContainer container =
7228 new DirectoryBasedSourceContainer.con1(dir);
7229 expect(container.contains(source1), isTrue);
7230 expect(container.contains(source2), isTrue);
7231 expect(container.contains(source3), isFalse);
7232 }
7233 }
7234
7235
7236 class ElementBuilderTest extends EngineTestCase {
7237 void test_visitCatchClause() {
7238 ElementHolder holder = new ElementHolder();
7239 ElementBuilder builder = new ElementBuilder(holder);
7240 String exceptionParameterName = "e";
7241 String stackParameterName = "s";
7242 CatchClause clause =
7243 AstFactory.catchClause2(exceptionParameterName, stackParameterName);
7244 clause.accept(builder);
7245 List<LocalVariableElement> variables = holder.localVariables;
7246 expect(variables, hasLength(2));
7247 VariableElement exceptionVariable = variables[0];
7248 expect(exceptionVariable, isNotNull);
7249 expect(exceptionVariable.name, exceptionParameterName);
7250 expect(exceptionVariable.isSynthetic, isFalse);
7251 expect(exceptionVariable.isConst, isFalse);
7252 expect(exceptionVariable.isFinal, isFalse);
7253 expect(exceptionVariable.initializer, isNull);
7254 VariableElement stackVariable = variables[1];
7255 expect(stackVariable, isNotNull);
7256 expect(stackVariable.name, stackParameterName);
7257 expect(stackVariable.isSynthetic, isFalse);
7258 expect(stackVariable.isConst, isFalse);
7259 expect(stackVariable.isFinal, isFalse);
7260 expect(stackVariable.initializer, isNull);
7261 }
7262
7263 void test_visitClassDeclaration_abstract() {
7264 ElementHolder holder = new ElementHolder();
7265 ElementBuilder builder = new ElementBuilder(holder);
7266 String className = "C";
7267 ClassDeclaration classDeclaration = AstFactory.classDeclaration(
7268 Keyword.ABSTRACT,
7269 className,
7270 null,
7271 null,
7272 null,
7273 null);
7274 classDeclaration.accept(builder);
7275 List<ClassElement> types = holder.types;
7276 expect(types, hasLength(1));
7277 ClassElement type = types[0];
7278 expect(type, isNotNull);
7279 expect(type.name, className);
7280 List<TypeParameterElement> typeParameters = type.typeParameters;
7281 expect(typeParameters, hasLength(0));
7282 expect(type.isAbstract, isTrue);
7283 expect(type.isSynthetic, isFalse);
7284 }
7285
7286 void test_visitClassDeclaration_minimal() {
7287 ElementHolder holder = new ElementHolder();
7288 ElementBuilder builder = new ElementBuilder(holder);
7289 String className = "C";
7290 ClassDeclaration classDeclaration =
7291 AstFactory.classDeclaration(null, className, null, null, null, null);
7292 classDeclaration.accept(builder);
7293 List<ClassElement> types = holder.types;
7294 expect(types, hasLength(1));
7295 ClassElement type = types[0];
7296 expect(type, isNotNull);
7297 expect(type.name, className);
7298 List<TypeParameterElement> typeParameters = type.typeParameters;
7299 expect(typeParameters, hasLength(0));
7300 expect(type.isAbstract, isFalse);
7301 expect(type.isSynthetic, isFalse);
7302 }
7303
7304 void test_visitClassDeclaration_parameterized() {
7305 ElementHolder holder = new ElementHolder();
7306 ElementBuilder builder = new ElementBuilder(holder);
7307 String className = "C";
7308 String firstVariableName = "E";
7309 String secondVariableName = "F";
7310 ClassDeclaration classDeclaration = AstFactory.classDeclaration(
7311 null,
7312 className,
7313 AstFactory.typeParameterList([firstVariableName, secondVariableName]),
7314 null,
7315 null,
7316 null);
7317 classDeclaration.accept(builder);
7318 List<ClassElement> types = holder.types;
7319 expect(types, hasLength(1));
7320 ClassElement type = types[0];
7321 expect(type, isNotNull);
7322 expect(type.name, className);
7323 List<TypeParameterElement> typeParameters = type.typeParameters;
7324 expect(typeParameters, hasLength(2));
7325 expect(typeParameters[0].name, firstVariableName);
7326 expect(typeParameters[1].name, secondVariableName);
7327 expect(type.isAbstract, isFalse);
7328 expect(type.isSynthetic, isFalse);
7329 }
7330
7331 void test_visitClassDeclaration_withMembers() {
7332 ElementHolder holder = new ElementHolder();
7333 ElementBuilder builder = new ElementBuilder(holder);
7334 String className = "C";
7335 String typeParameterName = "E";
7336 String fieldName = "f";
7337 String methodName = "m";
7338 ClassDeclaration classDeclaration = AstFactory.classDeclaration(
7339 null,
7340 className,
7341 AstFactory.typeParameterList([typeParameterName]),
7342 null,
7343 null,
7344 null,
7345 [
7346 AstFactory.fieldDeclaration2(
7347 false,
7348 null,
7349 [AstFactory.variableDeclaration(fieldName)]),
7350 AstFactory.methodDeclaration2(
7351 null,
7352 null,
7353 null,
7354 null,
7355 AstFactory.identifier3(methodName),
7356 AstFactory.formalParameterList(),
7357 AstFactory.blockFunctionBody2())]);
7358 classDeclaration.accept(builder);
7359 List<ClassElement> types = holder.types;
7360 expect(types, hasLength(1));
7361 ClassElement type = types[0];
7362 expect(type, isNotNull);
7363 expect(type.name, className);
7364 expect(type.isAbstract, isFalse);
7365 expect(type.isSynthetic, isFalse);
7366 List<TypeParameterElement> typeParameters = type.typeParameters;
7367 expect(typeParameters, hasLength(1));
7368 TypeParameterElement typeParameter = typeParameters[0];
7369 expect(typeParameter, isNotNull);
7370 expect(typeParameter.name, typeParameterName);
7371 List<FieldElement> fields = type.fields;
7372 expect(fields, hasLength(1));
7373 FieldElement field = fields[0];
7374 expect(field, isNotNull);
7375 expect(field.name, fieldName);
7376 List<MethodElement> methods = type.methods;
7377 expect(methods, hasLength(1));
7378 MethodElement method = methods[0];
7379 expect(method, isNotNull);
7380 expect(method.name, methodName);
7381 }
7382
7383 void test_visitClassTypeAlias() {
7384 // class B {}
7385 // class M {}
7386 // class C = B with M
7387 ElementHolder holder = new ElementHolder();
7388 ElementBuilder builder = new ElementBuilder(holder);
7389 ClassElementImpl classB = ElementFactory.classElement2('B', []);
7390 ConstructorElementImpl constructorB =
7391 ElementFactory.constructorElement2(classB, '', []);
7392 constructorB.setModifier(Modifier.SYNTHETIC, true);
7393 classB.constructors = [constructorB];
7394 ClassElement classM = ElementFactory.classElement2('M', []);
7395 WithClause withClause =
7396 AstFactory.withClause([AstFactory.typeName(classM, [])]);
7397 ClassTypeAlias alias = AstFactory.classTypeAlias(
7398 'C',
7399 null,
7400 null,
7401 AstFactory.typeName(classB, []),
7402 withClause,
7403 null);
7404 alias.accept(builder);
7405 List<ClassElement> types = holder.types;
7406 expect(types, hasLength(1));
7407 ClassElement type = types[0];
7408 expect(alias.element, same(type));
7409 expect(type.name, equals('C'));
7410 expect(type.isAbstract, isFalse);
7411 expect(type.isSynthetic, isFalse);
7412 expect(type.typeParameters, isEmpty);
7413 expect(type.fields, isEmpty);
7414 expect(type.methods, isEmpty);
7415 }
7416
7417 void test_visitClassTypeAlias_abstract() {
7418 // class B {}
7419 // class M {}
7420 // abstract class C = B with M
7421 ElementHolder holder = new ElementHolder();
7422 ElementBuilder builder = new ElementBuilder(holder);
7423 ClassElementImpl classB = ElementFactory.classElement2('B', []);
7424 ConstructorElementImpl constructorB =
7425 ElementFactory.constructorElement2(classB, '', []);
7426 constructorB.setModifier(Modifier.SYNTHETIC, true);
7427 classB.constructors = [constructorB];
7428 ClassElement classM = ElementFactory.classElement2('M', []);
7429 WithClause withClause =
7430 AstFactory.withClause([AstFactory.typeName(classM, [])]);
7431 ClassTypeAlias classCAst = AstFactory.classTypeAlias(
7432 'C',
7433 null,
7434 Keyword.ABSTRACT,
7435 AstFactory.typeName(classB, []),
7436 withClause,
7437 null);
7438 classCAst.accept(builder);
7439 List<ClassElement> types = holder.types;
7440 expect(types, hasLength(1));
7441 ClassElement type = types[0];
7442 expect(type.isAbstract, isTrue);
7443 }
7444
7445 void test_visitClassTypeAlias_typeParams() {
7446 // class B {}
7447 // class M {}
7448 // class C<T> = B with M
7449 ElementHolder holder = new ElementHolder();
7450 ElementBuilder builder = new ElementBuilder(holder);
7451 ClassElementImpl classB = ElementFactory.classElement2('B', []);
7452 ConstructorElementImpl constructorB =
7453 ElementFactory.constructorElement2(classB, '', []);
7454 constructorB.setModifier(Modifier.SYNTHETIC, true);
7455 classB.constructors = [constructorB];
7456 ClassElementImpl classM = ElementFactory.classElement2('M', []);
7457 WithClause withClause =
7458 AstFactory.withClause([AstFactory.typeName(classM, [])]);
7459 ClassTypeAlias classCAst = AstFactory.classTypeAlias(
7460 'C',
7461 AstFactory.typeParameterList(['T']),
7462 null,
7463 AstFactory.typeName(classB, []),
7464 withClause,
7465 null);
7466 classCAst.accept(builder);
7467 List<ClassElement> types = holder.types;
7468 expect(types, hasLength(1));
7469 ClassElement type = types[0];
7470 expect(type.typeParameters, hasLength(1));
7471 expect(type.typeParameters[0].name, equals('T'));
7472 }
7473
7474 void test_visitConstructorDeclaration_factory() {
7475 ElementHolder holder = new ElementHolder();
7476 ElementBuilder builder = new ElementBuilder(holder);
7477 String className = "A";
7478 ConstructorDeclaration constructorDeclaration =
7479 AstFactory.constructorDeclaration2(
7480 null,
7481 Keyword.FACTORY,
7482 AstFactory.identifier3(className),
7483 null,
7484 AstFactory.formalParameterList(),
7485 null,
7486 AstFactory.blockFunctionBody2());
7487 constructorDeclaration.accept(builder);
7488 List<ConstructorElement> constructors = holder.constructors;
7489 expect(constructors, hasLength(1));
7490 ConstructorElement constructor = constructors[0];
7491 expect(constructor, isNotNull);
7492 expect(constructor.isFactory, isTrue);
7493 expect(constructor.name, "");
7494 expect(constructor.functions, hasLength(0));
7495 expect(constructor.labels, hasLength(0));
7496 expect(constructor.localVariables, hasLength(0));
7497 expect(constructor.parameters, hasLength(0));
7498 }
7499
7500 void test_visitConstructorDeclaration_minimal() {
7501 ElementHolder holder = new ElementHolder();
7502 ElementBuilder builder = new ElementBuilder(holder);
7503 String className = "A";
7504 ConstructorDeclaration constructorDeclaration =
7505 AstFactory.constructorDeclaration2(
7506 null,
7507 null,
7508 AstFactory.identifier3(className),
7509 null,
7510 AstFactory.formalParameterList(),
7511 null,
7512 AstFactory.blockFunctionBody2());
7513 constructorDeclaration.accept(builder);
7514 List<ConstructorElement> constructors = holder.constructors;
7515 expect(constructors, hasLength(1));
7516 ConstructorElement constructor = constructors[0];
7517 expect(constructor, isNotNull);
7518 expect(constructor.isFactory, isFalse);
7519 expect(constructor.name, "");
7520 expect(constructor.functions, hasLength(0));
7521 expect(constructor.labels, hasLength(0));
7522 expect(constructor.localVariables, hasLength(0));
7523 expect(constructor.parameters, hasLength(0));
7524 }
7525
7526 void test_visitConstructorDeclaration_named() {
7527 ElementHolder holder = new ElementHolder();
7528 ElementBuilder builder = new ElementBuilder(holder);
7529 String className = "A";
7530 String constructorName = "c";
7531 ConstructorDeclaration constructorDeclaration =
7532 AstFactory.constructorDeclaration2(
7533 null,
7534 null,
7535 AstFactory.identifier3(className),
7536 constructorName,
7537 AstFactory.formalParameterList(),
7538 null,
7539 AstFactory.blockFunctionBody2());
7540 constructorDeclaration.accept(builder);
7541 List<ConstructorElement> constructors = holder.constructors;
7542 expect(constructors, hasLength(1));
7543 ConstructorElement constructor = constructors[0];
7544 expect(constructor, isNotNull);
7545 expect(constructor.isFactory, isFalse);
7546 expect(constructor.name, constructorName);
7547 expect(constructor.functions, hasLength(0));
7548 expect(constructor.labels, hasLength(0));
7549 expect(constructor.localVariables, hasLength(0));
7550 expect(constructor.parameters, hasLength(0));
7551 expect(constructorDeclaration.name.staticElement, same(constructor));
7552 expect(constructorDeclaration.element, same(constructor));
7553 }
7554
7555 void test_visitConstructorDeclaration_unnamed() {
7556 ElementHolder holder = new ElementHolder();
7557 ElementBuilder builder = new ElementBuilder(holder);
7558 String className = "A";
7559 ConstructorDeclaration constructorDeclaration =
7560 AstFactory.constructorDeclaration2(
7561 null,
7562 null,
7563 AstFactory.identifier3(className),
7564 null,
7565 AstFactory.formalParameterList(),
7566 null,
7567 AstFactory.blockFunctionBody2());
7568 constructorDeclaration.accept(builder);
7569 List<ConstructorElement> constructors = holder.constructors;
7570 expect(constructors, hasLength(1));
7571 ConstructorElement constructor = constructors[0];
7572 expect(constructor, isNotNull);
7573 expect(constructor.isFactory, isFalse);
7574 expect(constructor.name, "");
7575 expect(constructor.functions, hasLength(0));
7576 expect(constructor.labels, hasLength(0));
7577 expect(constructor.localVariables, hasLength(0));
7578 expect(constructor.parameters, hasLength(0));
7579 expect(constructorDeclaration.element, same(constructor));
7580 }
7581
7582 void test_visitEnumDeclaration() {
7583 ElementHolder holder = new ElementHolder();
7584 ElementBuilder builder = new ElementBuilder(holder);
7585 String enumName = "E";
7586 EnumDeclaration enumDeclaration =
7587 AstFactory.enumDeclaration2(enumName, ["ONE"]);
7588 enumDeclaration.accept(builder);
7589 List<ClassElement> enums = holder.enums;
7590 expect(enums, hasLength(1));
7591 ClassElement enumElement = enums[0];
7592 expect(enumElement, isNotNull);
7593 expect(enumElement.name, enumName);
7594 }
7595
7596 void test_visitFieldDeclaration() {
7597 ElementHolder holder = new ElementHolder();
7598 ElementBuilder builder = new ElementBuilder(holder);
7599 String firstFieldName = "x";
7600 String secondFieldName = "y";
7601 FieldDeclaration fieldDeclaration = AstFactory.fieldDeclaration2(
7602 false,
7603 null,
7604 [
7605 AstFactory.variableDeclaration(firstFieldName),
7606 AstFactory.variableDeclaration(secondFieldName)]);
7607 fieldDeclaration.accept(builder);
7608 List<FieldElement> fields = holder.fields;
7609 expect(fields, hasLength(2));
7610 FieldElement firstField = fields[0];
7611 expect(firstField, isNotNull);
7612 expect(firstField.name, firstFieldName);
7613 expect(firstField.initializer, isNull);
7614 expect(firstField.isConst, isFalse);
7615 expect(firstField.isFinal, isFalse);
7616 expect(firstField.isSynthetic, isFalse);
7617 FieldElement secondField = fields[1];
7618 expect(secondField, isNotNull);
7619 expect(secondField.name, secondFieldName);
7620 expect(secondField.initializer, isNull);
7621 expect(secondField.isConst, isFalse);
7622 expect(secondField.isFinal, isFalse);
7623 expect(secondField.isSynthetic, isFalse);
7624 }
7625
7626 void test_visitFieldFormalParameter() {
7627 ElementHolder holder = new ElementHolder();
7628 ElementBuilder builder = new ElementBuilder(holder);
7629 String parameterName = "p";
7630 FieldFormalParameter formalParameter =
7631 AstFactory.fieldFormalParameter(null, null, parameterName);
7632 formalParameter.accept(builder);
7633 List<ParameterElement> parameters = holder.parameters;
7634 expect(parameters, hasLength(1));
7635 ParameterElement parameter = parameters[0];
7636 expect(parameter, isNotNull);
7637 expect(parameter.name, parameterName);
7638 expect(parameter.initializer, isNull);
7639 expect(parameter.isConst, isFalse);
7640 expect(parameter.isFinal, isFalse);
7641 expect(parameter.isSynthetic, isFalse);
7642 expect(parameter.parameterKind, ParameterKind.REQUIRED);
7643 expect(parameter.parameters, hasLength(0));
7644 }
7645
7646 void test_visitFieldFormalParameter_funtionTyped() {
7647 ElementHolder holder = new ElementHolder();
7648 ElementBuilder builder = new ElementBuilder(holder);
7649 String parameterName = "p";
7650 FieldFormalParameter formalParameter = AstFactory.fieldFormalParameter(
7651 null,
7652 null,
7653 parameterName,
7654 AstFactory.formalParameterList([AstFactory.simpleFormalParameter3("a")]) );
7655 formalParameter.accept(builder);
7656 List<ParameterElement> parameters = holder.parameters;
7657 expect(parameters, hasLength(1));
7658 ParameterElement parameter = parameters[0];
7659 expect(parameter, isNotNull);
7660 expect(parameter.name, parameterName);
7661 expect(parameter.initializer, isNull);
7662 expect(parameter.isConst, isFalse);
7663 expect(parameter.isFinal, isFalse);
7664 expect(parameter.isSynthetic, isFalse);
7665 expect(parameter.parameterKind, ParameterKind.REQUIRED);
7666 expect(parameter.parameters, hasLength(1));
7667 }
7668
7669 void test_visitFormalParameterList() {
7670 ElementHolder holder = new ElementHolder();
7671 ElementBuilder builder = new ElementBuilder(holder);
7672 String firstParameterName = "a";
7673 String secondParameterName = "b";
7674 FormalParameterList parameterList = AstFactory.formalParameterList(
7675 [
7676 AstFactory.simpleFormalParameter3(firstParameterName),
7677 AstFactory.simpleFormalParameter3(secondParameterName)]);
7678 parameterList.accept(builder);
7679 List<ParameterElement> parameters = holder.parameters;
7680 expect(parameters, hasLength(2));
7681 expect(parameters[0].name, firstParameterName);
7682 expect(parameters[1].name, secondParameterName);
7683 }
7684
7685 void test_visitFunctionDeclaration_getter() {
7686 ElementHolder holder = new ElementHolder();
7687 ElementBuilder builder = new ElementBuilder(holder);
7688 String functionName = "f";
7689 FunctionDeclaration declaration = AstFactory.functionDeclaration(
7690 null,
7691 Keyword.GET,
7692 functionName,
7693 AstFactory.functionExpression2(
7694 AstFactory.formalParameterList(),
7695 AstFactory.blockFunctionBody2()));
7696 declaration.accept(builder);
7697 List<PropertyAccessorElement> accessors = holder.accessors;
7698 expect(accessors, hasLength(1));
7699 PropertyAccessorElement accessor = accessors[0];
7700 expect(accessor, isNotNull);
7701 expect(accessor.name, functionName);
7702 expect(declaration.element, same(accessor));
7703 expect(declaration.functionExpression.element, same(accessor));
7704 expect(accessor.isGetter, isTrue);
7705 expect(accessor.isSetter, isFalse);
7706 expect(accessor.isSynthetic, isFalse);
7707 PropertyInducingElement variable = accessor.variable;
7708 EngineTestCase.assertInstanceOf(
7709 (obj) => obj is TopLevelVariableElement,
7710 TopLevelVariableElement,
7711 variable);
7712 expect(variable.isSynthetic, isTrue);
7713 }
7714
7715 void test_visitFunctionDeclaration_plain() {
7716 ElementHolder holder = new ElementHolder();
7717 ElementBuilder builder = new ElementBuilder(holder);
7718 String functionName = "f";
7719 FunctionDeclaration declaration = AstFactory.functionDeclaration(
7720 null,
7721 null,
7722 functionName,
7723 AstFactory.functionExpression2(
7724 AstFactory.formalParameterList(),
7725 AstFactory.blockFunctionBody2()));
7726 declaration.accept(builder);
7727 List<FunctionElement> functions = holder.functions;
7728 expect(functions, hasLength(1));
7729 FunctionElement function = functions[0];
7730 expect(function, isNotNull);
7731 expect(function.name, functionName);
7732 expect(declaration.element, same(function));
7733 expect(declaration.functionExpression.element, same(function));
7734 expect(function.isSynthetic, isFalse);
7735 }
7736
7737 void test_visitFunctionDeclaration_setter() {
7738 ElementHolder holder = new ElementHolder();
7739 ElementBuilder builder = new ElementBuilder(holder);
7740 String functionName = "f";
7741 FunctionDeclaration declaration = AstFactory.functionDeclaration(
7742 null,
7743 Keyword.SET,
7744 functionName,
7745 AstFactory.functionExpression2(
7746 AstFactory.formalParameterList(),
7747 AstFactory.blockFunctionBody2()));
7748 declaration.accept(builder);
7749 List<PropertyAccessorElement> accessors = holder.accessors;
7750 expect(accessors, hasLength(1));
7751 PropertyAccessorElement accessor = accessors[0];
7752 expect(accessor, isNotNull);
7753 expect(accessor.name, "$functionName=");
7754 expect(declaration.element, same(accessor));
7755 expect(declaration.functionExpression.element, same(accessor));
7756 expect(accessor.isGetter, isFalse);
7757 expect(accessor.isSetter, isTrue);
7758 expect(accessor.isSynthetic, isFalse);
7759 PropertyInducingElement variable = accessor.variable;
7760 EngineTestCase.assertInstanceOf(
7761 (obj) => obj is TopLevelVariableElement,
7762 TopLevelVariableElement,
7763 variable);
7764 expect(variable.isSynthetic, isTrue);
7765 }
7766
7767 void test_visitFunctionExpression() {
7768 ElementHolder holder = new ElementHolder();
7769 ElementBuilder builder = new ElementBuilder(holder);
7770 FunctionExpression expression = AstFactory.functionExpression2(
7771 AstFactory.formalParameterList(),
7772 AstFactory.blockFunctionBody2());
7773 expression.accept(builder);
7774 List<FunctionElement> functions = holder.functions;
7775 expect(functions, hasLength(1));
7776 FunctionElement function = functions[0];
7777 expect(function, isNotNull);
7778 expect(expression.element, same(function));
7779 expect(function.isSynthetic, isFalse);
7780 }
7781
7782 void test_visitFunctionTypeAlias() {
7783 ElementHolder holder = new ElementHolder();
7784 ElementBuilder builder = new ElementBuilder(holder);
7785 String aliasName = "F";
7786 String parameterName = "E";
7787 FunctionTypeAlias aliasNode = AstFactory.typeAlias(
7788 null,
7789 aliasName,
7790 AstFactory.typeParameterList([parameterName]),
7791 null);
7792 aliasNode.accept(builder);
7793 List<FunctionTypeAliasElement> aliases = holder.typeAliases;
7794 expect(aliases, hasLength(1));
7795 FunctionTypeAliasElement alias = aliases[0];
7796 expect(alias, isNotNull);
7797 expect(alias.name, aliasName);
7798 expect(alias.parameters, hasLength(0));
7799 List<TypeParameterElement> typeParameters = alias.typeParameters;
7800 expect(typeParameters, hasLength(1));
7801 TypeParameterElement typeParameter = typeParameters[0];
7802 expect(typeParameter, isNotNull);
7803 expect(typeParameter.name, parameterName);
7804 }
7805
7806 void test_visitFunctionTypedFormalParameter() {
7807 ElementHolder holder = new ElementHolder();
7808 ElementBuilder builder = new ElementBuilder(holder);
7809 String parameterName = "p";
7810 FunctionTypedFormalParameter formalParameter =
7811 AstFactory.functionTypedFormalParameter(null, parameterName);
7812 _useParameterInMethod(formalParameter, 100, 110);
7813 formalParameter.accept(builder);
7814 List<ParameterElement> parameters = holder.parameters;
7815 expect(parameters, hasLength(1));
7816 ParameterElement parameter = parameters[0];
7817 expect(parameter, isNotNull);
7818 expect(parameter.name, parameterName);
7819 expect(parameter.initializer, isNull);
7820 expect(parameter.isConst, isFalse);
7821 expect(parameter.isFinal, isFalse);
7822 expect(parameter.isSynthetic, isFalse);
7823 expect(parameter.parameterKind, ParameterKind.REQUIRED);
7824 {
7825 SourceRange visibleRange = parameter.visibleRange;
7826 expect(100, visibleRange.offset);
7827 expect(110, visibleRange.end);
7828 }
7829 }
7830
7831 void test_visitLabeledStatement() {
7832 ElementHolder holder = new ElementHolder();
7833 ElementBuilder builder = new ElementBuilder(holder);
7834 String labelName = "l";
7835 LabeledStatement statement = AstFactory.labeledStatement(
7836 [AstFactory.label2(labelName)],
7837 AstFactory.breakStatement());
7838 statement.accept(builder);
7839 List<LabelElement> labels = holder.labels;
7840 expect(labels, hasLength(1));
7841 LabelElement label = labels[0];
7842 expect(label, isNotNull);
7843 expect(label.name, labelName);
7844 expect(label.isSynthetic, isFalse);
7845 }
7846
7847 void test_visitMethodDeclaration_abstract() {
7848 ElementHolder holder = new ElementHolder();
7849 ElementBuilder builder = new ElementBuilder(holder);
7850 String methodName = "m";
7851 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
7852 null,
7853 null,
7854 null,
7855 null,
7856 AstFactory.identifier3(methodName),
7857 AstFactory.formalParameterList(),
7858 AstFactory.emptyFunctionBody());
7859 methodDeclaration.accept(builder);
7860 List<MethodElement> methods = holder.methods;
7861 expect(methods, hasLength(1));
7862 MethodElement method = methods[0];
7863 expect(method, isNotNull);
7864 expect(method.name, methodName);
7865 expect(method.functions, hasLength(0));
7866 expect(method.labels, hasLength(0));
7867 expect(method.localVariables, hasLength(0));
7868 expect(method.parameters, hasLength(0));
7869 expect(method.isAbstract, isTrue);
7870 expect(method.isStatic, isFalse);
7871 expect(method.isSynthetic, isFalse);
7872 }
7873
7874 void test_visitMethodDeclaration_getter() {
7875 ElementHolder holder = new ElementHolder();
7876 ElementBuilder builder = new ElementBuilder(holder);
7877 String methodName = "m";
7878 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
7879 null,
7880 null,
7881 Keyword.GET,
7882 null,
7883 AstFactory.identifier3(methodName),
7884 AstFactory.formalParameterList(),
7885 AstFactory.blockFunctionBody2());
7886 methodDeclaration.accept(builder);
7887 List<FieldElement> fields = holder.fields;
7888 expect(fields, hasLength(1));
7889 FieldElement field = fields[0];
7890 expect(field, isNotNull);
7891 expect(field.name, methodName);
7892 expect(field.isSynthetic, isTrue);
7893 expect(field.setter, isNull);
7894 PropertyAccessorElement getter = field.getter;
7895 expect(getter, isNotNull);
7896 expect(getter.isAbstract, isFalse);
7897 expect(getter.isGetter, isTrue);
7898 expect(getter.isSynthetic, isFalse);
7899 expect(getter.name, methodName);
7900 expect(getter.variable, field);
7901 expect(getter.functions, hasLength(0));
7902 expect(getter.labels, hasLength(0));
7903 expect(getter.localVariables, hasLength(0));
7904 expect(getter.parameters, hasLength(0));
7905 }
7906
7907 void test_visitMethodDeclaration_getter_abstract() {
7908 ElementHolder holder = new ElementHolder();
7909 ElementBuilder builder = new ElementBuilder(holder);
7910 String methodName = "m";
7911 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
7912 null,
7913 null,
7914 Keyword.GET,
7915 null,
7916 AstFactory.identifier3(methodName),
7917 AstFactory.formalParameterList(),
7918 AstFactory.emptyFunctionBody());
7919 methodDeclaration.accept(builder);
7920 List<FieldElement> fields = holder.fields;
7921 expect(fields, hasLength(1));
7922 FieldElement field = fields[0];
7923 expect(field, isNotNull);
7924 expect(field.name, methodName);
7925 expect(field.isSynthetic, isTrue);
7926 expect(field.setter, isNull);
7927 PropertyAccessorElement getter = field.getter;
7928 expect(getter, isNotNull);
7929 expect(getter.isAbstract, isTrue);
7930 expect(getter.isGetter, isTrue);
7931 expect(getter.isSynthetic, isFalse);
7932 expect(getter.name, methodName);
7933 expect(getter.variable, field);
7934 expect(getter.functions, hasLength(0));
7935 expect(getter.labels, hasLength(0));
7936 expect(getter.localVariables, hasLength(0));
7937 expect(getter.parameters, hasLength(0));
7938 }
7939
7940 void test_visitMethodDeclaration_getter_external() {
7941 ElementHolder holder = new ElementHolder();
7942 ElementBuilder builder = new ElementBuilder(holder);
7943 String methodName = "m";
7944 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
7945 null,
7946 null,
7947 Keyword.GET,
7948 null,
7949 AstFactory.identifier3(methodName),
7950 AstFactory.formalParameterList());
7951 methodDeclaration.accept(builder);
7952 List<FieldElement> fields = holder.fields;
7953 expect(fields, hasLength(1));
7954 FieldElement field = fields[0];
7955 expect(field, isNotNull);
7956 expect(field.name, methodName);
7957 expect(field.isSynthetic, isTrue);
7958 expect(field.setter, isNull);
7959 PropertyAccessorElement getter = field.getter;
7960 expect(getter, isNotNull);
7961 expect(getter.isAbstract, isFalse);
7962 expect(getter.isGetter, isTrue);
7963 expect(getter.isSynthetic, isFalse);
7964 expect(getter.name, methodName);
7965 expect(getter.variable, field);
7966 expect(getter.functions, hasLength(0));
7967 expect(getter.labels, hasLength(0));
7968 expect(getter.localVariables, hasLength(0));
7969 expect(getter.parameters, hasLength(0));
7970 }
7971
7972 void test_visitMethodDeclaration_minimal() {
7973 ElementHolder holder = new ElementHolder();
7974 ElementBuilder builder = new ElementBuilder(holder);
7975 String methodName = "m";
7976 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
7977 null,
7978 null,
7979 null,
7980 null,
7981 AstFactory.identifier3(methodName),
7982 AstFactory.formalParameterList(),
7983 AstFactory.blockFunctionBody2());
7984 methodDeclaration.accept(builder);
7985 List<MethodElement> methods = holder.methods;
7986 expect(methods, hasLength(1));
7987 MethodElement method = methods[0];
7988 expect(method, isNotNull);
7989 expect(method.name, methodName);
7990 expect(method.functions, hasLength(0));
7991 expect(method.labels, hasLength(0));
7992 expect(method.localVariables, hasLength(0));
7993 expect(method.parameters, hasLength(0));
7994 expect(method.isAbstract, isFalse);
7995 expect(method.isStatic, isFalse);
7996 expect(method.isSynthetic, isFalse);
7997 }
7998
7999 void test_visitMethodDeclaration_operator() {
8000 ElementHolder holder = new ElementHolder();
8001 ElementBuilder builder = new ElementBuilder(holder);
8002 String methodName = "+";
8003 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
8004 null,
8005 null,
8006 null,
8007 Keyword.OPERATOR,
8008 AstFactory.identifier3(methodName),
8009 AstFactory.formalParameterList([AstFactory.simpleFormalParameter3("adden d")]),
8010 AstFactory.blockFunctionBody2());
8011 methodDeclaration.accept(builder);
8012 List<MethodElement> methods = holder.methods;
8013 expect(methods, hasLength(1));
8014 MethodElement method = methods[0];
8015 expect(method, isNotNull);
8016 expect(method.name, methodName);
8017 expect(method.functions, hasLength(0));
8018 expect(method.labels, hasLength(0));
8019 expect(method.localVariables, hasLength(0));
8020 expect(method.parameters, hasLength(1));
8021 expect(method.isAbstract, isFalse);
8022 expect(method.isStatic, isFalse);
8023 expect(method.isSynthetic, isFalse);
8024 }
8025
8026 void test_visitMethodDeclaration_setter() {
8027 ElementHolder holder = new ElementHolder();
8028 ElementBuilder builder = new ElementBuilder(holder);
8029 String methodName = "m";
8030 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
8031 null,
8032 null,
8033 Keyword.SET,
8034 null,
8035 AstFactory.identifier3(methodName),
8036 AstFactory.formalParameterList(),
8037 AstFactory.blockFunctionBody2());
8038 methodDeclaration.accept(builder);
8039 List<FieldElement> fields = holder.fields;
8040 expect(fields, hasLength(1));
8041 FieldElement field = fields[0];
8042 expect(field, isNotNull);
8043 expect(field.name, methodName);
8044 expect(field.isSynthetic, isTrue);
8045 expect(field.getter, isNull);
8046 PropertyAccessorElement setter = field.setter;
8047 expect(setter, isNotNull);
8048 expect(setter.isAbstract, isFalse);
8049 expect(setter.isSetter, isTrue);
8050 expect(setter.isSynthetic, isFalse);
8051 expect(setter.name, "$methodName=");
8052 expect(setter.displayName, methodName);
8053 expect(setter.variable, field);
8054 expect(setter.functions, hasLength(0));
8055 expect(setter.labels, hasLength(0));
8056 expect(setter.localVariables, hasLength(0));
8057 expect(setter.parameters, hasLength(0));
8058 }
8059
8060 void test_visitMethodDeclaration_setter_abstract() {
8061 ElementHolder holder = new ElementHolder();
8062 ElementBuilder builder = new ElementBuilder(holder);
8063 String methodName = "m";
8064 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
8065 null,
8066 null,
8067 Keyword.SET,
8068 null,
8069 AstFactory.identifier3(methodName),
8070 AstFactory.formalParameterList(),
8071 AstFactory.emptyFunctionBody());
8072 methodDeclaration.accept(builder);
8073 List<FieldElement> fields = holder.fields;
8074 expect(fields, hasLength(1));
8075 FieldElement field = fields[0];
8076 expect(field, isNotNull);
8077 expect(field.name, methodName);
8078 expect(field.isSynthetic, isTrue);
8079 expect(field.getter, isNull);
8080 PropertyAccessorElement setter = field.setter;
8081 expect(setter, isNotNull);
8082 expect(setter.isAbstract, isTrue);
8083 expect(setter.isSetter, isTrue);
8084 expect(setter.isSynthetic, isFalse);
8085 expect(setter.name, "$methodName=");
8086 expect(setter.displayName, methodName);
8087 expect(setter.variable, field);
8088 expect(setter.functions, hasLength(0));
8089 expect(setter.labels, hasLength(0));
8090 expect(setter.localVariables, hasLength(0));
8091 expect(setter.parameters, hasLength(0));
8092 }
8093
8094 void test_visitMethodDeclaration_setter_external() {
8095 ElementHolder holder = new ElementHolder();
8096 ElementBuilder builder = new ElementBuilder(holder);
8097 String methodName = "m";
8098 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
8099 null,
8100 null,
8101 Keyword.SET,
8102 null,
8103 AstFactory.identifier3(methodName),
8104 AstFactory.formalParameterList());
8105 methodDeclaration.accept(builder);
8106 List<FieldElement> fields = holder.fields;
8107 expect(fields, hasLength(1));
8108 FieldElement field = fields[0];
8109 expect(field, isNotNull);
8110 expect(field.name, methodName);
8111 expect(field.isSynthetic, isTrue);
8112 expect(field.getter, isNull);
8113 PropertyAccessorElement setter = field.setter;
8114 expect(setter, isNotNull);
8115 expect(setter.isAbstract, isFalse);
8116 expect(setter.isSetter, isTrue);
8117 expect(setter.isSynthetic, isFalse);
8118 expect(setter.name, "$methodName=");
8119 expect(setter.displayName, methodName);
8120 expect(setter.variable, field);
8121 expect(setter.functions, hasLength(0));
8122 expect(setter.labels, hasLength(0));
8123 expect(setter.localVariables, hasLength(0));
8124 expect(setter.parameters, hasLength(0));
8125 }
8126
8127 void test_visitMethodDeclaration_static() {
8128 ElementHolder holder = new ElementHolder();
8129 ElementBuilder builder = new ElementBuilder(holder);
8130 String methodName = "m";
8131 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
8132 Keyword.STATIC,
8133 null,
8134 null,
8135 null,
8136 AstFactory.identifier3(methodName),
8137 AstFactory.formalParameterList(),
8138 AstFactory.blockFunctionBody2());
8139 methodDeclaration.accept(builder);
8140 List<MethodElement> methods = holder.methods;
8141 expect(methods, hasLength(1));
8142 MethodElement method = methods[0];
8143 expect(method, isNotNull);
8144 expect(method.name, methodName);
8145 expect(method.functions, hasLength(0));
8146 expect(method.labels, hasLength(0));
8147 expect(method.localVariables, hasLength(0));
8148 expect(method.parameters, hasLength(0));
8149 expect(method.isAbstract, isFalse);
8150 expect(method.isStatic, isTrue);
8151 expect(method.isSynthetic, isFalse);
8152 }
8153
8154 void test_visitMethodDeclaration_withMembers() {
8155 ElementHolder holder = new ElementHolder();
8156 ElementBuilder builder = new ElementBuilder(holder);
8157 String methodName = "m";
8158 String parameterName = "p";
8159 String localVariableName = "v";
8160 String labelName = "l";
8161 String exceptionParameterName = "e";
8162 MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
8163 null,
8164 null,
8165 null,
8166 null,
8167 AstFactory.identifier3(methodName),
8168 AstFactory.formalParameterList(
8169 [AstFactory.simpleFormalParameter3(parameterName)]),
8170 AstFactory.blockFunctionBody2(
8171 [
8172 AstFactory.variableDeclarationStatement2(
8173 Keyword.VAR,
8174 [AstFactory.variableDeclaration(localVariableName)]),
8175 AstFactory.tryStatement2(
8176 AstFactory.block(
8177 [
8178 AstFactory.labeledStatement(
8179 [AstFactory.label2(labelName)],
8180 AstFactory.returnStatement())]),
8181 [AstFactory.catchClause(exceptionParameterName)])]));
8182 methodDeclaration.accept(builder);
8183 List<MethodElement> methods = holder.methods;
8184 expect(methods, hasLength(1));
8185 MethodElement method = methods[0];
8186 expect(method, isNotNull);
8187 expect(method.name, methodName);
8188 expect(method.isAbstract, isFalse);
8189 expect(method.isStatic, isFalse);
8190 expect(method.isSynthetic, isFalse);
8191 List<VariableElement> parameters = method.parameters;
8192 expect(parameters, hasLength(1));
8193 VariableElement parameter = parameters[0];
8194 expect(parameter, isNotNull);
8195 expect(parameter.name, parameterName);
8196 List<VariableElement> localVariables = method.localVariables;
8197 expect(localVariables, hasLength(2));
8198 VariableElement firstVariable = localVariables[0];
8199 VariableElement secondVariable = localVariables[1];
8200 expect(firstVariable, isNotNull);
8201 expect(secondVariable, isNotNull);
8202 expect(
8203 (firstVariable.name == localVariableName &&
8204 secondVariable.name == exceptionParameterName) ||
8205 (firstVariable.name == exceptionParameterName &&
8206 secondVariable.name == localVariableName),
8207 isTrue);
8208 List<LabelElement> labels = method.labels;
8209 expect(labels, hasLength(1));
8210 LabelElement label = labels[0];
8211 expect(label, isNotNull);
8212 expect(label.name, labelName);
8213 }
8214
8215 void test_visitNamedFormalParameter() {
8216 ElementHolder holder = new ElementHolder();
8217 ElementBuilder builder = new ElementBuilder(holder);
8218 String parameterName = "p";
8219 DefaultFormalParameter formalParameter = AstFactory.namedFormalParameter(
8220 AstFactory.simpleFormalParameter3(parameterName),
8221 AstFactory.identifier3("42"));
8222 _useParameterInMethod(formalParameter, 100, 110);
8223 formalParameter.accept(builder);
8224 List<ParameterElement> parameters = holder.parameters;
8225 expect(parameters, hasLength(1));
8226 ParameterElement parameter = parameters[0];
8227 expect(parameter, isNotNull);
8228 expect(parameter.name, parameterName);
8229 expect(parameter.isConst, isFalse);
8230 expect(parameter.isFinal, isFalse);
8231 expect(parameter.isSynthetic, isFalse);
8232 expect(parameter.parameterKind, ParameterKind.NAMED);
8233 {
8234 SourceRange visibleRange = parameter.visibleRange;
8235 expect(100, visibleRange.offset);
8236 expect(110, visibleRange.end);
8237 }
8238 expect(parameter.defaultValueCode, "42");
8239 FunctionElement initializer = parameter.initializer;
8240 expect(initializer, isNotNull);
8241 expect(initializer.isSynthetic, isTrue);
8242 }
8243
8244 void test_visitSimpleFormalParameter() {
8245 ElementHolder holder = new ElementHolder();
8246 ElementBuilder builder = new ElementBuilder(holder);
8247 String parameterName = "p";
8248 SimpleFormalParameter formalParameter =
8249 AstFactory.simpleFormalParameter3(parameterName);
8250 _useParameterInMethod(formalParameter, 100, 110);
8251 formalParameter.accept(builder);
8252 List<ParameterElement> parameters = holder.parameters;
8253 expect(parameters, hasLength(1));
8254 ParameterElement parameter = parameters[0];
8255 expect(parameter, isNotNull);
8256 expect(parameter.name, parameterName);
8257 expect(parameter.initializer, isNull);
8258 expect(parameter.isConst, isFalse);
8259 expect(parameter.isFinal, isFalse);
8260 expect(parameter.isSynthetic, isFalse);
8261 expect(parameter.parameterKind, ParameterKind.REQUIRED);
8262 {
8263 SourceRange visibleRange = parameter.visibleRange;
8264 expect(100, visibleRange.offset);
8265 expect(110, visibleRange.end);
8266 }
8267 }
8268
8269 void test_visitTypeAlias_minimal() {
8270 ElementHolder holder = new ElementHolder();
8271 ElementBuilder builder = new ElementBuilder(holder);
8272 String aliasName = "F";
8273 TypeAlias typeAlias = AstFactory.typeAlias(null, aliasName, null, null);
8274 typeAlias.accept(builder);
8275 List<FunctionTypeAliasElement> aliases = holder.typeAliases;
8276 expect(aliases, hasLength(1));
8277 FunctionTypeAliasElement alias = aliases[0];
8278 expect(alias, isNotNull);
8279 expect(alias.name, aliasName);
8280 expect(alias.type, isNotNull);
8281 expect(alias.isSynthetic, isFalse);
8282 }
8283
8284 void test_visitTypeAlias_withFormalParameters() {
8285 ElementHolder holder = new ElementHolder();
8286 ElementBuilder builder = new ElementBuilder(holder);
8287 String aliasName = "F";
8288 String firstParameterName = "x";
8289 String secondParameterName = "y";
8290 TypeAlias typeAlias = AstFactory.typeAlias(
8291 null,
8292 aliasName,
8293 AstFactory.typeParameterList(),
8294 AstFactory.formalParameterList(
8295 [
8296 AstFactory.simpleFormalParameter3(firstParameterName),
8297 AstFactory.simpleFormalParameter3(secondParameterName)]));
8298 typeAlias.accept(builder);
8299 List<FunctionTypeAliasElement> aliases = holder.typeAliases;
8300 expect(aliases, hasLength(1));
8301 FunctionTypeAliasElement alias = aliases[0];
8302 expect(alias, isNotNull);
8303 expect(alias.name, aliasName);
8304 expect(alias.type, isNotNull);
8305 expect(alias.isSynthetic, isFalse);
8306 List<VariableElement> parameters = alias.parameters;
8307 expect(parameters, hasLength(2));
8308 expect(parameters[0].name, firstParameterName);
8309 expect(parameters[1].name, secondParameterName);
8310 List<TypeParameterElement> typeParameters = alias.typeParameters;
8311 expect(typeParameters, isNotNull);
8312 expect(typeParameters, hasLength(0));
8313 }
8314
8315 void test_visitTypeAlias_withTypeParameters() {
8316 ElementHolder holder = new ElementHolder();
8317 ElementBuilder builder = new ElementBuilder(holder);
8318 String aliasName = "F";
8319 String firstTypeParameterName = "A";
8320 String secondTypeParameterName = "B";
8321 TypeAlias typeAlias = AstFactory.typeAlias(
8322 null,
8323 aliasName,
8324 AstFactory.typeParameterList([firstTypeParameterName, secondTypeParamete rName]),
8325 AstFactory.formalParameterList());
8326 typeAlias.accept(builder);
8327 List<FunctionTypeAliasElement> aliases = holder.typeAliases;
8328 expect(aliases, hasLength(1));
8329 FunctionTypeAliasElement alias = aliases[0];
8330 expect(alias, isNotNull);
8331 expect(alias.name, aliasName);
8332 expect(alias.type, isNotNull);
8333 expect(alias.isSynthetic, isFalse);
8334 List<VariableElement> parameters = alias.parameters;
8335 expect(parameters, isNotNull);
8336 expect(parameters, hasLength(0));
8337 List<TypeParameterElement> typeParameters = alias.typeParameters;
8338 expect(typeParameters, hasLength(2));
8339 expect(typeParameters[0].name, firstTypeParameterName);
8340 expect(typeParameters[1].name, secondTypeParameterName);
8341 }
8342
8343 void test_visitTypeParameter() {
8344 ElementHolder holder = new ElementHolder();
8345 ElementBuilder builder = new ElementBuilder(holder);
8346 String parameterName = "E";
8347 TypeParameter typeParameter = AstFactory.typeParameter(parameterName);
8348 typeParameter.accept(builder);
8349 List<TypeParameterElement> typeParameters = holder.typeParameters;
8350 expect(typeParameters, hasLength(1));
8351 TypeParameterElement typeParameterElement = typeParameters[0];
8352 expect(typeParameterElement, isNotNull);
8353 expect(typeParameterElement.name, parameterName);
8354 expect(typeParameterElement.bound, isNull);
8355 expect(typeParameterElement.isSynthetic, isFalse);
8356 }
8357
8358 void test_visitVariableDeclaration_inConstructor() {
8359 ElementHolder holder = new ElementHolder();
8360 ElementBuilder builder = new ElementBuilder(holder);
8361 //
8362 // C() {var v;}
8363 //
8364 String variableName = "v";
8365 VariableDeclaration variable =
8366 AstFactory.variableDeclaration2(variableName, null);
8367 Statement statement =
8368 AstFactory.variableDeclarationStatement2(null, [variable]);
8369 ConstructorDeclaration constructor = AstFactory.constructorDeclaration2(
8370 null,
8371 null,
8372 AstFactory.identifier3("C"),
8373 "C",
8374 AstFactory.formalParameterList(),
8375 null,
8376 AstFactory.blockFunctionBody2([statement]));
8377 constructor.accept(builder);
8378 List<ConstructorElement> constructors = holder.constructors;
8379 expect(constructors, hasLength(1));
8380 List<LocalVariableElement> variableElements =
8381 constructors[0].localVariables;
8382 expect(variableElements, hasLength(1));
8383 LocalVariableElement variableElement = variableElements[0];
8384 expect(variableElement.name, variableName);
8385 }
8386
8387 void test_visitVariableDeclaration_inMethod() {
8388 ElementHolder holder = new ElementHolder();
8389 ElementBuilder builder = new ElementBuilder(holder);
8390 //
8391 // m() {var v;}
8392 //
8393 String variableName = "v";
8394 VariableDeclaration variable =
8395 AstFactory.variableDeclaration2(variableName, null);
8396 Statement statement =
8397 AstFactory.variableDeclarationStatement2(null, [variable]);
8398 MethodDeclaration constructor = AstFactory.methodDeclaration2(
8399 null,
8400 null,
8401 null,
8402 null,
8403 AstFactory.identifier3("m"),
8404 AstFactory.formalParameterList(),
8405 AstFactory.blockFunctionBody2([statement]));
8406 constructor.accept(builder);
8407 List<MethodElement> methods = holder.methods;
8408 expect(methods, hasLength(1));
8409 List<LocalVariableElement> variableElements = methods[0].localVariables;
8410 expect(variableElements, hasLength(1));
8411 LocalVariableElement variableElement = variableElements[0];
8412 expect(variableElement.name, variableName);
8413 }
8414
8415 void test_visitVariableDeclaration_localNestedInField() {
8416 ElementHolder holder = new ElementHolder();
8417 ElementBuilder builder = new ElementBuilder(holder);
8418 //
8419 // var f = () {var v;}
8420 //
8421 String variableName = "v";
8422 VariableDeclaration variable =
8423 AstFactory.variableDeclaration2(variableName, null);
8424 Statement statement =
8425 AstFactory.variableDeclarationStatement2(null, [variable]);
8426 Expression initializer = AstFactory.functionExpression2(
8427 AstFactory.formalParameterList(),
8428 AstFactory.blockFunctionBody2([statement]));
8429 String fieldName = "f";
8430 VariableDeclaration field =
8431 AstFactory.variableDeclaration2(fieldName, initializer);
8432 FieldDeclaration fieldDeclaration =
8433 AstFactory.fieldDeclaration2(false, null, [field]);
8434 fieldDeclaration.accept(builder);
8435 List<FieldElement> variables = holder.fields;
8436 expect(variables, hasLength(1));
8437 FieldElement fieldElement = variables[0];
8438 expect(fieldElement, isNotNull);
8439 FunctionElement initializerElement = fieldElement.initializer;
8440 expect(initializerElement, isNotNull);
8441 List<FunctionElement> functionElements = initializerElement.functions;
8442 expect(functionElements, hasLength(1));
8443 List<LocalVariableElement> variableElements =
8444 functionElements[0].localVariables;
8445 expect(variableElements, hasLength(1));
8446 LocalVariableElement variableElement = variableElements[0];
8447 expect(variableElement.name, variableName);
8448 expect(variableElement.isConst, isFalse);
8449 expect(variableElement.isFinal, isFalse);
8450 expect(variableElement.isSynthetic, isFalse);
8451 }
8452
8453 void test_visitVariableDeclaration_noInitializer() {
8454 ElementHolder holder = new ElementHolder();
8455 ElementBuilder builder = new ElementBuilder(holder);
8456 String variableName = "v";
8457 VariableDeclaration variableDeclaration =
8458 AstFactory.variableDeclaration2(variableName, null);
8459 AstFactory.variableDeclarationList2(null, [variableDeclaration]);
8460 variableDeclaration.accept(builder);
8461 List<TopLevelVariableElement> variables = holder.topLevelVariables;
8462 expect(variables, hasLength(1));
8463 TopLevelVariableElement variable = variables[0];
8464 expect(variable, isNotNull);
8465 expect(variable.initializer, isNull);
8466 expect(variable.name, variableName);
8467 expect(variable.isConst, isFalse);
8468 expect(variable.isFinal, isFalse);
8469 expect(variable.isSynthetic, isFalse);
8470 expect(variable.getter, isNotNull);
8471 expect(variable.setter, isNotNull);
8472 }
8473
8474 void _useParameterInMethod(FormalParameter formalParameter, int blockOffset,
8475 int blockEnd) {
8476 Block block = AstFactory.block();
8477 block.leftBracket.offset = blockOffset;
8478 block.rightBracket.offset = blockEnd - 1;
8479 BlockFunctionBody body = AstFactory.blockFunctionBody(block);
8480 AstFactory.methodDeclaration2(
8481 null,
8482 null,
8483 null,
8484 null,
8485 AstFactory.identifier3("main"),
8486 AstFactory.formalParameterList([formalParameter]),
8487 body);
8488 }
8489 }
8490
8491
8492 class ElementLocatorTest extends ResolverTestCase {
8493 void fail_locate_ExportDirective() {
8494 AstNode id = _findNodeIn("export", "export 'dart:core';");
8495 Element element = ElementLocator.locate(id);
8496 EngineTestCase.assertInstanceOf(
8497 (obj) => obj is ImportElement,
8498 ImportElement,
8499 element);
8500 }
8501
8502 void fail_locate_Identifier_libraryDirective() {
8503 AstNode id = _findNodeIn("foo", "library foo.bar;");
8504 Element element = ElementLocator.locate(id);
8505 EngineTestCase.assertInstanceOf(
8506 (obj) => obj is LibraryElement,
8507 LibraryElement,
8508 element);
8509 }
8510
8511 void fail_locate_Identifier_partOfDirective() {
8512 // Can't resolve the library element without the library declaration.
8513 // AstNode id = findNodeIn("foo", "part of foo.bar;");
8514 // Element element = ElementLocator.locate(id);
8515 // assertInstanceOf(LibraryElement.class, element);
8516 fail("Test this case");
8517 }
8518
8519 @override
8520 void reset() {
8521 AnalysisOptionsImpl analysisOptions = new AnalysisOptionsImpl();
8522 analysisOptions.hint = false;
8523 resetWithOptions(analysisOptions);
8524 }
8525
8526 void test_locate_AssignmentExpression() {
8527 AstNode id = _findNodeIn("+=", r'''
8528 int x = 0;
8529 void main() {
8530 x += 1;
8531 }''');
8532 Element element = ElementLocator.locate(id);
8533 EngineTestCase.assertInstanceOf(
8534 (obj) => obj is MethodElement,
8535 MethodElement,
8536 element);
8537 }
8538
8539 void test_locate_BinaryExpression() {
8540 AstNode id = _findNodeIn("+", "var x = 3 + 4;");
8541 Element element = ElementLocator.locate(id);
8542 EngineTestCase.assertInstanceOf(
8543 (obj) => obj is MethodElement,
8544 MethodElement,
8545 element);
8546 }
8547
8548 void test_locate_ClassDeclaration() {
8549 AstNode id = _findNodeIn("class", "class A { }");
8550 Element element = ElementLocator.locate(id);
8551 EngineTestCase.assertInstanceOf(
8552 (obj) => obj is ClassElement,
8553 ClassElement,
8554 element);
8555 }
8556
8557 void test_locate_CompilationUnit() {
8558 CompilationUnit cu = _resolveContents("// only comment");
8559 expect(cu.element, isNotNull);
8560 Element element = ElementLocator.locate(cu);
8561 expect(element, same(cu.element));
8562 }
8563
8564 void test_locate_ConstructorDeclaration() {
8565 AstNode id = _findNodeIndexedIn("bar", 0, r'''
8566 class A {
8567 A.bar() {}
8568 }''');
8569 ConstructorDeclaration declaration =
8570 id.getAncestor((node) => node is ConstructorDeclaration);
8571 Element element = ElementLocator.locate(declaration);
8572 EngineTestCase.assertInstanceOf(
8573 (obj) => obj is ConstructorElement,
8574 ConstructorElement,
8575 element);
8576 }
8577
8578 void test_locate_FunctionDeclaration() {
8579 AstNode id = _findNodeIn("f", "int f() => 3;");
8580 FunctionDeclaration declaration =
8581 id.getAncestor((node) => node is FunctionDeclaration);
8582 Element element = ElementLocator.locate(declaration);
8583 EngineTestCase.assertInstanceOf(
8584 (obj) => obj is FunctionElement,
8585 FunctionElement,
8586 element);
8587 }
8588
8589 void
8590 test_locate_Identifier_annotationClass_namedConstructor_forSimpleFormalPar ameter() {
8591 AstNode id = _findNodeIndexedIn("Class", 2, r'''
8592 class Class {
8593 const Class.name();
8594 }
8595 void main(@Class.name() parameter) {
8596 }''');
8597 Element element = ElementLocator.locate(id);
8598 EngineTestCase.assertInstanceOf(
8599 (obj) => obj is ClassElement,
8600 ClassElement,
8601 element);
8602 }
8603
8604 void
8605 test_locate_Identifier_annotationClass_unnamedConstructor_forSimpleFormalP arameter() {
8606 AstNode id = _findNodeIndexedIn("Class", 2, r'''
8607 class Class {
8608 const Class();
8609 }
8610 void main(@Class() parameter) {
8611 }''');
8612 Element element = ElementLocator.locate(id);
8613 EngineTestCase.assertInstanceOf(
8614 (obj) => obj is ConstructorElement,
8615 ConstructorElement,
8616 element);
8617 }
8618
8619 void test_locate_Identifier_className() {
8620 AstNode id = _findNodeIn("A", "class A { }");
8621 Element element = ElementLocator.locate(id);
8622 EngineTestCase.assertInstanceOf(
8623 (obj) => obj is ClassElement,
8624 ClassElement,
8625 element);
8626 }
8627
8628 void test_locate_Identifier_constructor_named() {
8629 AstNode id = _findNodeIndexedIn("bar", 0, r'''
8630 class A {
8631 A.bar() {}
8632 }''');
8633 Element element = ElementLocator.locate(id);
8634 EngineTestCase.assertInstanceOf(
8635 (obj) => obj is ConstructorElement,
8636 ConstructorElement,
8637 element);
8638 }
8639
8640 void test_locate_Identifier_constructor_unnamed() {
8641 AstNode id = _findNodeIndexedIn("A", 1, r'''
8642 class A {
8643 A() {}
8644 }''');
8645 Element element = ElementLocator.locate(id);
8646 EngineTestCase.assertInstanceOf(
8647 (obj) => obj is ConstructorElement,
8648 ConstructorElement,
8649 element);
8650 }
8651
8652 void test_locate_Identifier_fieldName() {
8653 AstNode id = _findNodeIn("x", "class A { var x; }");
8654 Element element = ElementLocator.locate(id);
8655 EngineTestCase.assertInstanceOf(
8656 (obj) => obj is FieldElement,
8657 FieldElement,
8658 element);
8659 }
8660
8661 void test_locate_Identifier_propertAccess() {
8662 AstNode id = _findNodeIn("length", r'''
8663 void main() {
8664 int x = 'foo'.length;
8665 }''');
8666 Element element = ElementLocator.locate(id);
8667 EngineTestCase.assertInstanceOf(
8668 (obj) => obj is PropertyAccessorElement,
8669 PropertyAccessorElement,
8670 element);
8671 }
8672
8673 void test_locate_ImportDirective() {
8674 AstNode id = _findNodeIn("import", "import 'dart:core';");
8675 Element element = ElementLocator.locate(id);
8676 EngineTestCase.assertInstanceOf(
8677 (obj) => obj is ImportElement,
8678 ImportElement,
8679 element);
8680 }
8681
8682 void test_locate_IndexExpression() {
8683 AstNode id = _findNodeIndexedIn("\\[", 1, r'''
8684 void main() {
8685 List x = [1, 2];
8686 var y = x[0];
8687 }''');
8688 Element element = ElementLocator.locate(id);
8689 EngineTestCase.assertInstanceOf(
8690 (obj) => obj is MethodElement,
8691 MethodElement,
8692 element);
8693 }
8694
8695 void test_locate_InstanceCreationExpression() {
8696 AstNode node = _findNodeIndexedIn("A(", 0, r'''
8697 class A {}
8698 void main() {
8699 new A();
8700 }''');
8701 Element element = ElementLocator.locate(node);
8702 EngineTestCase.assertInstanceOf(
8703 (obj) => obj is ConstructorElement,
8704 ConstructorElement,
8705 element);
8706 }
8707
8708 void test_locate_InstanceCreationExpression_type_prefixedIdentifier() {
8709 // prepare: new pref.A()
8710 SimpleIdentifier identifier = AstFactory.identifier3("A");
8711 PrefixedIdentifier prefixedIdentifier =
8712 AstFactory.identifier4("pref", identifier);
8713 InstanceCreationExpression creation =
8714 AstFactory.instanceCreationExpression2(
8715 Keyword.NEW,
8716 AstFactory.typeName3(prefixedIdentifier));
8717 // set ClassElement
8718 ClassElement classElement = ElementFactory.classElement2("A");
8719 identifier.staticElement = classElement;
8720 // set ConstructorElement
8721 ConstructorElement constructorElement =
8722 ElementFactory.constructorElement2(classElement, null);
8723 creation.constructorName.staticElement = constructorElement;
8724 // verify that "A" is resolved to ConstructorElement
8725 Element element = ElementLocator.locate(identifier);
8726 expect(element, same(classElement));
8727 }
8728
8729 void test_locate_InstanceCreationExpression_type_simpleIdentifier() {
8730 // prepare: new A()
8731 SimpleIdentifier identifier = AstFactory.identifier3("A");
8732 InstanceCreationExpression creation =
8733 AstFactory.instanceCreationExpression2(
8734 Keyword.NEW,
8735 AstFactory.typeName3(identifier));
8736 // set ClassElement
8737 ClassElement classElement = ElementFactory.classElement2("A");
8738 identifier.staticElement = classElement;
8739 // set ConstructorElement
8740 ConstructorElement constructorElement =
8741 ElementFactory.constructorElement2(classElement, null);
8742 creation.constructorName.staticElement = constructorElement;
8743 // verify that "A" is resolved to ConstructorElement
8744 Element element = ElementLocator.locate(identifier);
8745 expect(element, same(classElement));
8746 }
8747
8748 void test_locate_LibraryDirective() {
8749 AstNode id = _findNodeIn("library", "library foo;");
8750 Element element = ElementLocator.locate(id);
8751 EngineTestCase.assertInstanceOf(
8752 (obj) => obj is LibraryElement,
8753 LibraryElement,
8754 element);
8755 }
8756
8757 void test_locate_MethodDeclaration() {
8758 AstNode id = _findNodeIn("m", r'''
8759 class A {
8760 void m() {}
8761 }''');
8762 MethodDeclaration declaration =
8763 id.getAncestor((node) => node is MethodDeclaration);
8764 Element element = ElementLocator.locate(declaration);
8765 EngineTestCase.assertInstanceOf(
8766 (obj) => obj is MethodElement,
8767 MethodElement,
8768 element);
8769 }
8770
8771 void test_locate_MethodInvocation_method() {
8772 AstNode id = _findNodeIndexedIn("bar", 1, r'''
8773 class A {
8774 int bar() => 42;
8775 }
8776 void main() {
8777 var f = new A().bar();
8778 }''');
8779 Element element = ElementLocator.locate(id);
8780 EngineTestCase.assertInstanceOf(
8781 (obj) => obj is MethodElement,
8782 MethodElement,
8783 element);
8784 }
8785
8786 void test_locate_MethodInvocation_topLevel() {
8787 String code = r'''
8788 foo(x) {}
8789 void main() {
8790 foo(0);
8791 }''';
8792 CompilationUnit cu = _resolveContents(code);
8793 int offset = code.indexOf('foo(0)');
8794 AstNode node = new NodeLocator.con1(offset).searchWithin(cu);
8795 MethodInvocation invocation =
8796 node.getAncestor((n) => n is MethodInvocation);
8797 Element element = ElementLocator.locate(invocation);
8798 EngineTestCase.assertInstanceOf(
8799 (obj) => obj is FunctionElement,
8800 FunctionElement,
8801 element);
8802 }
8803
8804 void test_locate_PostfixExpression() {
8805 AstNode id = _findNodeIn("++", "int addOne(int x) => x++;");
8806 Element element = ElementLocator.locate(id);
8807 EngineTestCase.assertInstanceOf(
8808 (obj) => obj is MethodElement,
8809 MethodElement,
8810 element);
8811 }
8812
8813 void test_locate_PrefixedIdentifier() {
8814 AstNode id = _findNodeIn("int", r'''
8815 import 'dart:core' as core;
8816 core.int value;''');
8817 PrefixedIdentifier identifier =
8818 id.getAncestor((node) => node is PrefixedIdentifier);
8819 Element element = ElementLocator.locate(identifier);
8820 EngineTestCase.assertInstanceOf(
8821 (obj) => obj is ClassElement,
8822 ClassElement,
8823 element);
8824 }
8825
8826 void test_locate_PrefixExpression() {
8827 AstNode id = _findNodeIn("++", "int addOne(int x) => ++x;");
8828 Element element = ElementLocator.locate(id);
8829 EngineTestCase.assertInstanceOf(
8830 (obj) => obj is MethodElement,
8831 MethodElement,
8832 element);
8833 }
8834
8835 void test_locate_StringLiteral_exportUri() {
8836 addNamedSource("/foo.dart", "library foo;");
8837 AstNode id = _findNodeIn("'foo.dart'", "export 'foo.dart';");
8838 Element element = ElementLocator.locate(id);
8839 EngineTestCase.assertInstanceOf(
8840 (obj) => obj is LibraryElement,
8841 LibraryElement,
8842 element);
8843 }
8844
8845 void test_locate_StringLiteral_expression() {
8846 AstNode id = _findNodeIn("abc", "var x = 'abc';");
8847 Element element = ElementLocator.locate(id);
8848 expect(element, isNull);
8849 }
8850
8851 void test_locate_StringLiteral_importUri() {
8852 addNamedSource("/foo.dart", "library foo; class A {}");
8853 AstNode id =
8854 _findNodeIn("'foo.dart'", "import 'foo.dart'; class B extends A {}");
8855 Element element = ElementLocator.locate(id);
8856 EngineTestCase.assertInstanceOf(
8857 (obj) => obj is LibraryElement,
8858 LibraryElement,
8859 element);
8860 }
8861
8862 void test_locate_StringLiteral_partUri() {
8863 addNamedSource("/foo.dart", "part of app;");
8864 AstNode id = _findNodeIn("'foo.dart'", "library app; part 'foo.dart';");
8865 Element element = ElementLocator.locate(id);
8866 EngineTestCase.assertInstanceOf(
8867 (obj) => obj is CompilationUnitElement,
8868 CompilationUnitElement,
8869 element);
8870 }
8871
8872 void test_locate_VariableDeclaration() {
8873 AstNode id = _findNodeIn("x", "var x = 'abc';");
8874 VariableDeclaration declaration =
8875 id.getAncestor((node) => node is VariableDeclaration);
8876 Element element = ElementLocator.locate(declaration);
8877 EngineTestCase.assertInstanceOf(
8878 (obj) => obj is TopLevelVariableElement,
8879 TopLevelVariableElement,
8880 element);
8881 }
8882
8883 void test_locateWithOffset_BinaryExpression() {
8884 AstNode id = _findNodeIn("+", "var x = 3 + 4;");
8885 Element element = ElementLocator.locateWithOffset(id, 0);
8886 EngineTestCase.assertInstanceOf(
8887 (obj) => obj is MethodElement,
8888 MethodElement,
8889 element);
8890 }
8891
8892 void test_locateWithOffset_StringLiteral() {
8893 AstNode id = _findNodeIn("abc", "var x = 'abc';");
8894 Element element = ElementLocator.locateWithOffset(id, 1);
8895 expect(element, isNull);
8896 }
8897
8898 /**
8899 * Find the first AST node matching a pattern in the resolved AST for the give n source.
8900 *
8901 * [nodePattern] the (unique) pattern used to identify the node of interest.
8902 * [code] the code to resolve.
8903 * Returns the matched node in the resolved AST for the given source lines.
8904 */
8905 AstNode _findNodeIn(String nodePattern, String code) {
8906 return _findNodeIndexedIn(nodePattern, 0, code);
8907 }
8908
8909 /**
8910 * Find the AST node matching the given indexed occurrence of a pattern in the resolved AST for
8911 * the given source.
8912 *
8913 * [nodePattern] the pattern used to identify the node of interest.
8914 * [index] the index of the pattern match of interest.
8915 * [code] the code to resolve.
8916 * Returns the matched node in the resolved AST for the given source lines
8917 */
8918 AstNode _findNodeIndexedIn(String nodePattern, int index, String code) {
8919 CompilationUnit cu = _resolveContents(code);
8920 int start = _getOffsetOfMatch(code, nodePattern, index);
8921 int end = start + nodePattern.length;
8922 return new NodeLocator.con2(start, end).searchWithin(cu);
8923 }
8924
8925 int _getOffsetOfMatch(String contents, String pattern, int matchIndex) {
8926 if (matchIndex == 0) {
8927 return contents.indexOf(pattern);
8928 }
8929 JavaPatternMatcher matcher =
8930 new JavaPatternMatcher(new RegExp(pattern), contents);
8931 int count = 0;
8932 while (matcher.find()) {
8933 if (count == matchIndex) {
8934 return matcher.start();
8935 }
8936 ++count;
8937 }
8938 return -1;
8939 }
8940
8941 /**
8942 * Parse, resolve and verify the given source lines to produce a fully
8943 * resolved AST.
8944 *
8945 * [code] the code to resolve.
8946 *
8947 * Returns the result of resolving the AST structure representing the content
8948 * of the source.
8949 *
8950 * Throws if source cannot be verified.
8951 */
8952 CompilationUnit _resolveContents(String code) {
8953 Source source = addSource(code);
8954 LibraryElement library = resolve(source);
8955 assertNoErrors(source);
8956 verify([source]);
8957 return analysisContext.resolveCompilationUnit(source, library);
8958 }
8959 }
8960
8961
8962 class EnumMemberBuilderTest extends EngineTestCase {
8963 void test_visitEnumDeclaration_multiple() {
8964 String firstName = "ONE";
8965 String secondName = "TWO";
8966 String thirdName = "THREE";
8967 EnumDeclaration enumDeclaration =
8968 AstFactory.enumDeclaration2("E", [firstName, secondName, thirdName]);
8969
8970 ClassElement enumElement = _buildElement(enumDeclaration);
8971 List<FieldElement> fields = enumElement.fields;
8972 expect(fields, hasLength(5));
8973
8974 FieldElement constant = fields[2];
8975 expect(constant, isNotNull);
8976 expect(constant.name, firstName);
8977 expect(constant.isStatic, isTrue);
8978 _assertGetter(constant);
8979
8980 constant = fields[3];
8981 expect(constant, isNotNull);
8982 expect(constant.name, secondName);
8983 expect(constant.isStatic, isTrue);
8984 _assertGetter(constant);
8985
8986 constant = fields[4];
8987 expect(constant, isNotNull);
8988 expect(constant.name, thirdName);
8989 expect(constant.isStatic, isTrue);
8990 _assertGetter(constant);
8991 }
8992
8993 void test_visitEnumDeclaration_single() {
8994 String firstName = "ONE";
8995 EnumDeclaration enumDeclaration =
8996 AstFactory.enumDeclaration2("E", [firstName]);
8997
8998 ClassElement enumElement = _buildElement(enumDeclaration);
8999 List<FieldElement> fields = enumElement.fields;
9000 expect(fields, hasLength(3));
9001
9002 FieldElement field = fields[0];
9003 expect(field, isNotNull);
9004 expect(field.name, "index");
9005 expect(field.isStatic, isFalse);
9006 expect(field.isSynthetic, isTrue);
9007 _assertGetter(field);
9008
9009 field = fields[1];
9010 expect(field, isNotNull);
9011 expect(field.name, "values");
9012 expect(field.isStatic, isTrue);
9013 expect(field.isSynthetic, isTrue);
9014 _assertGetter(field);
9015
9016 FieldElement constant = fields[2];
9017 expect(constant, isNotNull);
9018 expect(constant.name, firstName);
9019 expect(constant.isStatic, isTrue);
9020 _assertGetter(constant);
9021 }
9022
9023 void _assertGetter(FieldElement field) {
9024 PropertyAccessorElement getter = field.getter;
9025 expect(getter, isNotNull);
9026 expect(getter.variable, same(field));
9027 expect(getter.type, isNotNull);
9028 }
9029
9030 ClassElement _buildElement(EnumDeclaration enumDeclaration) {
9031 ElementHolder holder = new ElementHolder();
9032 ElementBuilder elementBuilder = new ElementBuilder(holder);
9033 enumDeclaration.accept(elementBuilder);
9034 EnumMemberBuilder memberBuilder =
9035 new EnumMemberBuilder(new TestTypeProvider());
9036 enumDeclaration.accept(memberBuilder);
9037 List<ClassElement> enums = holder.enums;
9038 expect(enums, hasLength(1));
9039 return enums[0];
9040 }
9041 }
9042
9043
9044 class ErrorReporterTest extends EngineTestCase {
9045 /**
9046 * Create a type with the given name in a compilation unit with the given name .
9047 *
9048 * @param fileName the name of the compilation unit containing the class
9049 * @param typeName the name of the type to be created
9050 * @return the type that was created
9051 */
9052 InterfaceType createType(String fileName, String typeName) {
9053 CompilationUnitElementImpl unit = ElementFactory.compilationUnit(fileName);
9054 ClassElementImpl element = ElementFactory.classElement2(typeName);
9055 unit.types = <ClassElement>[element];
9056 return element.type;
9057 }
9058
9059 void test_creation() {
9060 GatheringErrorListener listener = new GatheringErrorListener();
9061 TestSource source = new TestSource();
9062 expect(new ErrorReporter(listener, source), isNotNull);
9063 }
9064
9065 void test_reportTypeErrorForNode_differentNames() {
9066 DartType firstType = createType("/test1.dart", "A");
9067 DartType secondType = createType("/test2.dart", "B");
9068 GatheringErrorListener listener = new GatheringErrorListener();
9069 ErrorReporter reporter =
9070 new ErrorReporter(listener, firstType.element.source);
9071 reporter.reportTypeErrorForNode(
9072 StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
9073 AstFactory.identifier3("x"),
9074 [firstType, secondType]);
9075 AnalysisError error = listener.errors[0];
9076 expect(error.message.indexOf("(") < 0, isTrue);
9077 }
9078
9079 void test_reportTypeErrorForNode_sameName() {
9080 String typeName = "A";
9081 DartType firstType = createType("/test1.dart", typeName);
9082 DartType secondType = createType("/test2.dart", typeName);
9083 GatheringErrorListener listener = new GatheringErrorListener();
9084 ErrorReporter reporter =
9085 new ErrorReporter(listener, firstType.element.source);
9086 reporter.reportTypeErrorForNode(
9087 StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
9088 AstFactory.identifier3("x"),
9089 [firstType, secondType]);
9090 AnalysisError error = listener.errors[0];
9091 expect(error.message.indexOf("(") >= 0, isTrue);
9092 }
9093 }
9094
9095
9096 class ErrorSeverityTest extends EngineTestCase {
9097 void test_max_error_error() {
9098 expect(
9099 ErrorSeverity.ERROR.max(ErrorSeverity.ERROR),
9100 same(ErrorSeverity.ERROR));
9101 }
9102
9103 void test_max_error_none() {
9104 expect(
9105 ErrorSeverity.ERROR.max(ErrorSeverity.NONE),
9106 same(ErrorSeverity.ERROR));
9107 }
9108
9109 void test_max_error_warning() {
9110 expect(
9111 ErrorSeverity.ERROR.max(ErrorSeverity.WARNING),
9112 same(ErrorSeverity.ERROR));
9113 }
9114
9115 void test_max_none_error() {
9116 expect(
9117 ErrorSeverity.NONE.max(ErrorSeverity.ERROR),
9118 same(ErrorSeverity.ERROR));
9119 }
9120
9121 void test_max_none_none() {
9122 expect(
9123 ErrorSeverity.NONE.max(ErrorSeverity.NONE),
9124 same(ErrorSeverity.NONE));
9125 }
9126
9127 void test_max_none_warning() {
9128 expect(
9129 ErrorSeverity.NONE.max(ErrorSeverity.WARNING),
9130 same(ErrorSeverity.WARNING));
9131 }
9132
9133 void test_max_warning_error() {
9134 expect(
9135 ErrorSeverity.WARNING.max(ErrorSeverity.ERROR),
9136 same(ErrorSeverity.ERROR));
9137 }
9138
9139 void test_max_warning_none() {
9140 expect(
9141 ErrorSeverity.WARNING.max(ErrorSeverity.NONE),
9142 same(ErrorSeverity.WARNING));
9143 }
9144
9145 void test_max_warning_warning() {
9146 expect(
9147 ErrorSeverity.WARNING.max(ErrorSeverity.WARNING),
9148 same(ErrorSeverity.WARNING));
9149 }
9150 }
9151
9152
9153 class ExitDetectorTest extends ParserTestCase {
9154 void fail_doStatement_continue_with_label() {
9155 _assertFalse("{ x: do { continue x; } while(true); }");
9156 }
9157
9158 void fail_whileStatement_continue_with_label() {
9159 _assertFalse("{ x: while (true) { continue x; } }");
9160 }
9161
9162 void fail_whileStatement_doStatement_scopeRequired() {
9163 _assertTrue("{ while (true) { x: do { continue x; } while(true); }");
9164 }
9165
9166 void test_asExpression() {
9167 _assertFalse("a as Object;");
9168 }
9169
9170 void test_asExpression_throw() {
9171 _assertTrue("throw '' as Object;");
9172 }
9173
9174 void test_assertStatement() {
9175 _assertFalse("assert(a);");
9176 }
9177
9178 void test_assertStatement_throw() {
9179 _assertTrue("assert((throw 0));");
9180 }
9181
9182 void test_assignmentExpression() {
9183 _assertFalse("v = 1;");
9184 }
9185
9186 void test_assignmentExpression_lhs_throw() {
9187 _assertTrue("a[throw ''] = 0;");
9188 }
9189
9190 void test_assignmentExpression_rhs_throw() {
9191 _assertTrue("v = throw '';");
9192 }
9193
9194 void test_binaryExpression_and() {
9195 _assertFalse("a && b;");
9196 }
9197
9198 void test_binaryExpression_and_lhs() {
9199 _assertTrue("throw '' && b;");
9200 }
9201
9202 void test_binaryExpression_and_rhs() {
9203 _assertTrue("a && (throw '');");
9204 }
9205
9206 void test_binaryExpression_and_rhs2() {
9207 _assertTrue("false && (throw '');");
9208 }
9209
9210 void test_binaryExpression_and_rhs3() {
9211 _assertFalse("true && (throw '');");
9212 }
9213
9214 void test_binaryExpression_or() {
9215 _assertFalse("a || b;");
9216 }
9217
9218 void test_binaryExpression_or_lhs() {
9219 _assertTrue("throw '' || b;");
9220 }
9221
9222 void test_binaryExpression_or_rhs() {
9223 _assertTrue("a || (throw '');");
9224 }
9225
9226 void test_binaryExpression_or_rhs2() {
9227 _assertTrue("true || (throw '');");
9228 }
9229
9230 void test_binaryExpression_or_rhs3() {
9231 _assertFalse("false || (throw '');");
9232 }
9233
9234 void test_block_empty() {
9235 _assertFalse("{}");
9236 }
9237
9238 void test_block_noReturn() {
9239 _assertFalse("{ int i = 0; }");
9240 }
9241
9242 void test_block_return() {
9243 _assertTrue("{ return 0; }");
9244 }
9245
9246 void test_block_returnNotLast() {
9247 _assertTrue("{ return 0; throw 'a'; }");
9248 }
9249
9250 void test_block_throwNotLast() {
9251 _assertTrue("{ throw 0; x = null; }");
9252 }
9253
9254 void test_cascadeExpression_argument() {
9255 _assertTrue("a..b(throw '');");
9256 }
9257
9258 void test_cascadeExpression_index() {
9259 _assertTrue("a..[throw ''];");
9260 }
9261
9262 void test_cascadeExpression_target() {
9263 _assertTrue("throw ''..b();");
9264 }
9265
9266 void test_conditional_ifElse_bothThrows() {
9267 _assertTrue("c ? throw '' : throw '';");
9268 }
9269
9270 void test_conditional_ifElse_elseThrows() {
9271 _assertFalse("c ? i : throw '';");
9272 }
9273
9274 void test_conditional_ifElse_noThrow() {
9275 _assertFalse("c ? i : j;");
9276 }
9277
9278 void test_conditional_ifElse_thenThrow() {
9279 _assertFalse("c ? throw '' : j;");
9280 }
9281
9282 void test_creation() {
9283 expect(new ExitDetector(), isNotNull);
9284 }
9285
9286 void test_doStatement_throwCondition() {
9287 _assertTrue("{ do {} while (throw ''); }");
9288 }
9289
9290 void test_doStatement_true_break() {
9291 _assertFalse("{ do { break; } while (true); }");
9292 }
9293
9294 void test_doStatement_true_continue() {
9295 _assertTrue("{ do { continue; } while (true); }");
9296 }
9297
9298 void test_doStatement_true_if_return() {
9299 _assertTrue("{ do { if (true) {return null;} } while (true); }");
9300 }
9301
9302 void test_doStatement_true_noBreak() {
9303 _assertTrue("{ do {} while (true); }");
9304 }
9305
9306 void test_doStatement_true_return() {
9307 _assertTrue("{ do { return null; } while (true); }");
9308 }
9309
9310 void test_emptyStatement() {
9311 _assertFalse(";");
9312 }
9313
9314 void test_forEachStatement() {
9315 _assertFalse("for (element in list) {}");
9316 }
9317
9318 void test_forEachStatement_throw() {
9319 _assertTrue("for (element in throw '') {}");
9320 }
9321
9322 void test_forStatement_condition() {
9323 _assertTrue("for (; throw 0;) {}");
9324 }
9325
9326 void test_forStatement_implicitTrue() {
9327 _assertTrue("for (;;) {}");
9328 }
9329
9330 void test_forStatement_implicitTrue_break() {
9331 _assertFalse("for (;;) { break; }");
9332 }
9333
9334 void test_forStatement_initialization() {
9335 _assertTrue("for (i = throw 0;;) {}");
9336 }
9337
9338 void test_forStatement_true() {
9339 _assertTrue("for (; true; ) {}");
9340 }
9341
9342 void test_forStatement_true_break() {
9343 _assertFalse("{ for (; true; ) { break; } }");
9344 }
9345
9346 void test_forStatement_true_continue() {
9347 _assertTrue("{ for (; true; ) { continue; } }");
9348 }
9349
9350 void test_forStatement_true_if_return() {
9351 _assertTrue("{ for (; true; ) { if (true) {return null;} } }");
9352 }
9353
9354 void test_forStatement_true_noBreak() {
9355 _assertTrue("{ for (; true; ) {} }");
9356 }
9357
9358 void test_forStatement_updaters() {
9359 _assertTrue("for (;; i++, throw 0) {}");
9360 }
9361
9362 void test_forStatement_variableDeclaration() {
9363 _assertTrue("for (int i = throw 0;;) {}");
9364 }
9365
9366 void test_functionExpression() {
9367 _assertFalse("(){};");
9368 }
9369
9370 void test_functionExpression_bodyThrows() {
9371 _assertFalse("(int i) => throw '';");
9372 }
9373
9374 void test_functionExpressionInvocation() {
9375 _assertFalse("f(g);");
9376 }
9377
9378 void test_functionExpressionInvocation_argumentThrows() {
9379 _assertTrue("f(throw '');");
9380 }
9381
9382 void test_functionExpressionInvocation_targetThrows() {
9383 _assertTrue("throw ''(g);");
9384 }
9385
9386 void test_identifier_prefixedIdentifier() {
9387 _assertFalse("a.b;");
9388 }
9389
9390 void test_identifier_simpleIdentifier() {
9391 _assertFalse("a;");
9392 }
9393
9394 void test_if_false_else_return() {
9395 _assertTrue("if (false) {} else { return 0; }");
9396 }
9397
9398 void test_if_false_noReturn() {
9399 _assertFalse("if (false) {}");
9400 }
9401
9402 void test_if_false_return() {
9403 _assertFalse("if (false) { return 0; }");
9404 }
9405
9406 void test_if_noReturn() {
9407 _assertFalse("if (c) i++;");
9408 }
9409
9410 void test_if_return() {
9411 _assertFalse("if (c) return 0;");
9412 }
9413
9414 void test_if_true_noReturn() {
9415 _assertFalse("if (true) {}");
9416 }
9417
9418 void test_if_true_return() {
9419 _assertTrue("if (true) { return 0; }");
9420 }
9421
9422 void test_ifElse_bothReturn() {
9423 _assertTrue("if (c) return 0; else return 1;");
9424 }
9425
9426 void test_ifElse_elseReturn() {
9427 _assertFalse("if (c) i++; else return 1;");
9428 }
9429
9430 void test_ifElse_noReturn() {
9431 _assertFalse("if (c) i++; else j++;");
9432 }
9433
9434 void test_ifElse_thenReturn() {
9435 _assertFalse("if (c) return 0; else j++;");
9436 }
9437
9438 void test_indexExpression() {
9439 _assertFalse("a[b];");
9440 }
9441
9442 void test_indexExpression_index() {
9443 _assertTrue("a[throw ''];");
9444 }
9445
9446 void test_indexExpression_target() {
9447 _assertTrue("throw ''[b];");
9448 }
9449
9450 void test_instanceCreationExpression() {
9451 _assertFalse("new A(b);");
9452 }
9453
9454 void test_instanceCreationExpression_argumentThrows() {
9455 _assertTrue("new A(throw '');");
9456 }
9457
9458 void test_isExpression() {
9459 _assertFalse("A is B;");
9460 }
9461
9462 void test_isExpression_throws() {
9463 _assertTrue("throw '' is B;");
9464 }
9465
9466 void test_labeledStatement() {
9467 _assertFalse("label: a;");
9468 }
9469
9470 void test_labeledStatement_throws() {
9471 _assertTrue("label: throw '';");
9472 }
9473
9474 void test_literal_boolean() {
9475 _assertFalse("true;");
9476 }
9477
9478 void test_literal_double() {
9479 _assertFalse("1.1;");
9480 }
9481
9482 void test_literal_integer() {
9483 _assertFalse("1;");
9484 }
9485
9486 void test_literal_null() {
9487 _assertFalse("null;");
9488 }
9489
9490 void test_literal_String() {
9491 _assertFalse("'str';");
9492 }
9493
9494 void test_methodInvocation() {
9495 _assertFalse("a.b(c);");
9496 }
9497
9498 void test_methodInvocation_argument() {
9499 _assertTrue("a.b(throw '');");
9500 }
9501
9502 void test_methodInvocation_target() {
9503 _assertTrue("throw ''.b(c);");
9504 }
9505
9506 void test_parenthesizedExpression() {
9507 _assertFalse("(a);");
9508 }
9509
9510 void test_parenthesizedExpression_throw() {
9511 _assertTrue("(throw '');");
9512 }
9513
9514 void test_propertyAccess() {
9515 _assertFalse("new Object().a;");
9516 }
9517
9518 void test_propertyAccess_throws() {
9519 _assertTrue("(throw '').a;");
9520 }
9521
9522 void test_rethrow() {
9523 _assertTrue("rethrow;");
9524 }
9525
9526 void test_return() {
9527 _assertTrue("return 0;");
9528 }
9529
9530 void test_superExpression() {
9531 _assertFalse("super.a;");
9532 }
9533
9534 void test_switch_allReturn() {
9535 _assertTrue("switch (i) { case 0: return 0; default: return 1; }");
9536 }
9537
9538 void test_switch_defaultWithNoStatements() {
9539 _assertFalse("switch (i) { case 0: return 0; default: }");
9540 }
9541
9542 void test_switch_fallThroughToNotReturn() {
9543 _assertFalse("switch (i) { case 0: case 1: break; default: return 1; }");
9544 }
9545
9546 void test_switch_fallThroughToReturn() {
9547 _assertTrue("switch (i) { case 0: case 1: return 0; default: return 1; }");
9548 }
9549
9550 void test_switch_noDefault() {
9551 _assertFalse("switch (i) { case 0: return 0; }");
9552 }
9553
9554 void test_switch_nonReturn() {
9555 _assertFalse("switch (i) { case 0: i++; default: return 1; }");
9556 }
9557
9558 void test_thisExpression() {
9559 _assertFalse("this.a;");
9560 }
9561
9562 void test_throwExpression() {
9563 _assertTrue("throw new Object();");
9564 }
9565
9566 void test_tryStatement_noReturn() {
9567 _assertFalse("try {} catch (e, s) {} finally {}");
9568 }
9569
9570 void test_tryStatement_return_catch() {
9571 _assertFalse("try {} catch (e, s) { return 1; } finally {}");
9572 }
9573
9574 void test_tryStatement_return_finally() {
9575 _assertTrue("try {} catch (e, s) {} finally { return 1; }");
9576 }
9577
9578 void test_tryStatement_return_try() {
9579 _assertTrue("try { return 1; } catch (e, s) {} finally {}");
9580 }
9581
9582 void test_variableDeclarationStatement_noInitializer() {
9583 _assertFalse("int i;");
9584 }
9585
9586 void test_variableDeclarationStatement_noThrow() {
9587 _assertFalse("int i = 0;");
9588 }
9589
9590 void test_variableDeclarationStatement_throw() {
9591 _assertTrue("int i = throw new Object();");
9592 }
9593
9594 void test_whileStatement_false_nonReturn() {
9595 _assertFalse("{ while (false) {} }");
9596 }
9597
9598 void test_whileStatement_throwCondition() {
9599 _assertTrue("{ while (throw '') {} }");
9600 }
9601
9602 void test_whileStatement_true_break() {
9603 _assertFalse("{ while (true) { break; } }");
9604 }
9605
9606 void test_whileStatement_true_continue() {
9607 _assertTrue("{ while (true) { continue; } }");
9608 }
9609
9610 void test_whileStatement_true_if_return() {
9611 _assertTrue("{ while (true) { if (true) {return null;} } }");
9612 }
9613
9614 void test_whileStatement_true_noBreak() {
9615 _assertTrue("{ while (true) {} }");
9616 }
9617
9618 void test_whileStatement_true_return() {
9619 _assertTrue("{ while (true) { return null; } }");
9620 }
9621
9622 void test_whileStatement_true_throw() {
9623 _assertTrue("{ while (true) { throw ''; } }");
9624 }
9625
9626 void _assertFalse(String source) {
9627 _assertHasReturn(false, source);
9628 }
9629
9630 void _assertHasReturn(bool expectedResult, String source) {
9631 ExitDetector detector = new ExitDetector();
9632 Statement statement = ParserTestCase.parseStatement(source);
9633 expect(statement.accept(detector), same(expectedResult));
9634 }
9635
9636 void _assertTrue(String source) {
9637 _assertHasReturn(true, source);
9638 }
9639 }
9640
9641
9642 class ExpressionVisitor_AngularTest_verify extends ExpressionVisitor {
9643 ResolutionVerifier verifier;
9644
9645 ExpressionVisitor_AngularTest_verify(this.verifier);
9646
9647 @override
9648 void visitExpression(Expression expression) {
9649 expression.accept(verifier);
9650 }
9651 }
9652
9653
9654 class FileBasedSourceTest {
9655 void test_equals_false_differentFiles() {
9656 JavaFile file1 = FileUtilities2.createFile("/does/not/exist1.dart");
9657 JavaFile file2 = FileUtilities2.createFile("/does/not/exist2.dart");
9658 FileBasedSource source1 = new FileBasedSource.con1(file1);
9659 FileBasedSource source2 = new FileBasedSource.con1(file2);
9660 expect(source1 == source2, isFalse);
9661 }
9662
9663 void test_equals_false_null() {
9664 JavaFile file = FileUtilities2.createFile("/does/not/exist1.dart");
9665 FileBasedSource source1 = new FileBasedSource.con1(file);
9666 expect(source1 == null, isFalse);
9667 }
9668
9669 void test_equals_true() {
9670 JavaFile file1 = FileUtilities2.createFile("/does/not/exist.dart");
9671 JavaFile file2 = FileUtilities2.createFile("/does/not/exist.dart");
9672 FileBasedSource source1 = new FileBasedSource.con1(file1);
9673 FileBasedSource source2 = new FileBasedSource.con1(file2);
9674 expect(source1 == source2, isTrue);
9675 }
9676
9677 void test_getEncoding() {
9678 SourceFactory factory = new SourceFactory([new FileUriResolver()]);
9679 String fullPath = "/does/not/exist.dart";
9680 JavaFile file = FileUtilities2.createFile(fullPath);
9681 FileBasedSource source = new FileBasedSource.con1(file);
9682 expect(factory.fromEncoding(source.encoding), source);
9683 }
9684
9685 void test_getFullName() {
9686 String fullPath = "/does/not/exist.dart";
9687 JavaFile file = FileUtilities2.createFile(fullPath);
9688 FileBasedSource source = new FileBasedSource.con1(file);
9689 expect(source.fullName, file.getAbsolutePath());
9690 }
9691
9692 void test_getShortName() {
9693 JavaFile file = FileUtilities2.createFile("/does/not/exist.dart");
9694 FileBasedSource source = new FileBasedSource.con1(file);
9695 expect(source.shortName, "exist.dart");
9696 }
9697
9698 void test_hashCode() {
9699 JavaFile file1 = FileUtilities2.createFile("/does/not/exist.dart");
9700 JavaFile file2 = FileUtilities2.createFile("/does/not/exist.dart");
9701 FileBasedSource source1 = new FileBasedSource.con1(file1);
9702 FileBasedSource source2 = new FileBasedSource.con1(file2);
9703 expect(source2.hashCode, source1.hashCode);
9704 }
9705
9706 void test_isInSystemLibrary_contagious() {
9707 JavaFile sdkDirectory = DirectoryBasedDartSdk.defaultSdkDirectory;
9708 expect(sdkDirectory, isNotNull);
9709 DartSdk sdk = new DirectoryBasedDartSdk(sdkDirectory);
9710 UriResolver resolver = new DartUriResolver(sdk);
9711 SourceFactory factory = new SourceFactory([resolver]);
9712 // resolve dart:core
9713 Source result =
9714 resolver.resolveAbsolute(parseUriWithException("dart:core"));
9715 expect(result, isNotNull);
9716 expect(result.isInSystemLibrary, isTrue);
9717 // system libraries reference only other system libraries
9718 Source partSource = factory.resolveUri(result, "num.dart");
9719 expect(partSource, isNotNull);
9720 expect(partSource.isInSystemLibrary, isTrue);
9721 }
9722
9723 void test_isInSystemLibrary_false() {
9724 JavaFile file = FileUtilities2.createFile("/does/not/exist.dart");
9725 FileBasedSource source = new FileBasedSource.con1(file);
9726 expect(source, isNotNull);
9727 expect(source.fullName, file.getAbsolutePath());
9728 expect(source.isInSystemLibrary, isFalse);
9729 }
9730
9731 void test_issue14500() {
9732 // see https://code.google.com/p/dart/issues/detail?id=14500
9733 FileBasedSource source = new FileBasedSource.con1(
9734 FileUtilities2.createFile("/some/packages/foo:bar.dart"));
9735 expect(source, isNotNull);
9736 expect(source.exists(), isFalse);
9737 }
9738
9739 void test_resolveRelative_dart_fileName() {
9740 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9741 FileBasedSource source =
9742 new FileBasedSource.con2(parseUriWithException("dart:test"), file);
9743 expect(source, isNotNull);
9744 Uri relative = source.resolveRelativeUri(parseUriWithException("lib.dart"));
9745 expect(relative, isNotNull);
9746 expect(relative.toString(), "dart:test/lib.dart");
9747 }
9748
9749 void test_resolveRelative_dart_filePath() {
9750 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9751 FileBasedSource source =
9752 new FileBasedSource.con2(parseUriWithException("dart:test"), file);
9753 expect(source, isNotNull);
9754 Uri relative =
9755 source.resolveRelativeUri(parseUriWithException("c/lib.dart"));
9756 expect(relative, isNotNull);
9757 expect(relative.toString(), "dart:test/c/lib.dart");
9758 }
9759
9760 void test_resolveRelative_dart_filePathWithParent() {
9761 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9762 FileBasedSource source =
9763 new FileBasedSource.con2(parseUriWithException("dart:test/b/test.dart"), file);
9764 expect(source, isNotNull);
9765 Uri relative =
9766 source.resolveRelativeUri(parseUriWithException("../c/lib.dart"));
9767 expect(relative, isNotNull);
9768 expect(relative.toString(), "dart:test/c/lib.dart");
9769 }
9770
9771 void test_resolveRelative_file_fileName() {
9772 if (OSUtilities.isWindows()) {
9773 // On Windows, the URI that is produced includes a drive letter,
9774 // which I believe is not consistent across all machines that might run
9775 // this test.
9776 return;
9777 }
9778 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9779 FileBasedSource source = new FileBasedSource.con1(file);
9780 expect(source, isNotNull);
9781 Uri relative = source.resolveRelativeUri(parseUriWithException("lib.dart"));
9782 expect(relative, isNotNull);
9783 expect(relative.toString(), "file:///a/b/lib.dart");
9784 }
9785
9786 void test_resolveRelative_file_filePath() {
9787 if (OSUtilities.isWindows()) {
9788 // On Windows, the URI that is produced includes a drive letter,
9789 // which I believe is not consistent across all machines that might run
9790 // this test.
9791 return;
9792 }
9793 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9794 FileBasedSource source = new FileBasedSource.con1(file);
9795 expect(source, isNotNull);
9796 Uri relative =
9797 source.resolveRelativeUri(parseUriWithException("c/lib.dart"));
9798 expect(relative, isNotNull);
9799 expect(relative.toString(), "file:///a/b/c/lib.dart");
9800 }
9801
9802 void test_resolveRelative_file_filePathWithParent() {
9803 if (OSUtilities.isWindows()) {
9804 // On Windows, the URI that is produced includes a drive letter, which I
9805 // believe is not consistent across all machines that might run this test.
9806 return;
9807 }
9808 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9809 FileBasedSource source = new FileBasedSource.con1(file);
9810 expect(source, isNotNull);
9811 Uri relative =
9812 source.resolveRelativeUri(parseUriWithException("../c/lib.dart"));
9813 expect(relative, isNotNull);
9814 expect(relative.toString(), "file:///a/c/lib.dart");
9815 }
9816
9817 void test_resolveRelative_package_fileName() {
9818 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9819 FileBasedSource source =
9820 new FileBasedSource.con2(parseUriWithException("package:b/test.dart"), f ile);
9821 expect(source, isNotNull);
9822 Uri relative = source.resolveRelativeUri(parseUriWithException("lib.dart"));
9823 expect(relative, isNotNull);
9824 expect(relative.toString(), "package:b/lib.dart");
9825 }
9826
9827 void test_resolveRelative_package_fileNameWithoutPackageName() {
9828 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9829 FileBasedSource source =
9830 new FileBasedSource.con2(parseUriWithException("package:test.dart"), fil e);
9831 expect(source, isNotNull);
9832 Uri relative = source.resolveRelativeUri(parseUriWithException("lib.dart"));
9833 expect(relative, isNotNull);
9834 expect(relative.toString(), "package:lib.dart");
9835 }
9836
9837 void test_resolveRelative_package_filePath() {
9838 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9839 FileBasedSource source =
9840 new FileBasedSource.con2(parseUriWithException("package:b/test.dart"), f ile);
9841 expect(source, isNotNull);
9842 Uri relative =
9843 source.resolveRelativeUri(parseUriWithException("c/lib.dart"));
9844 expect(relative, isNotNull);
9845 expect(relative.toString(), "package:b/c/lib.dart");
9846 }
9847
9848 void test_resolveRelative_package_filePathWithParent() {
9849 JavaFile file = FileUtilities2.createFile("/a/b/test.dart");
9850 FileBasedSource source =
9851 new FileBasedSource.con2(parseUriWithException("package:a/b/test.dart"), file);
9852 expect(source, isNotNull);
9853 Uri relative =
9854 source.resolveRelativeUri(parseUriWithException("../c/lib.dart"));
9855 expect(relative, isNotNull);
9856 expect(relative.toString(), "package:a/c/lib.dart");
9857 }
9858
9859 void test_system() {
9860 JavaFile file = FileUtilities2.createFile("/does/not/exist.dart");
9861 FileBasedSource source =
9862 new FileBasedSource.con2(parseUriWithException("dart:core"), file);
9863 expect(source, isNotNull);
9864 expect(source.fullName, file.getAbsolutePath());
9865 expect(source.isInSystemLibrary, isTrue);
9866 }
9867 }
9868
9869
9870 class FileUriResolverTest {
9871 void test_creation() {
9872 expect(new FileUriResolver(), isNotNull);
9873 }
9874
9875 void test_resolve_file() {
9876 UriResolver resolver = new FileUriResolver();
9877 Source result =
9878 resolver.resolveAbsolute(parseUriWithException("file:/does/not/exist.dar t"));
9879 expect(result, isNotNull);
9880 expect(
9881 result.fullName,
9882 FileUtilities2.createFile("/does/not/exist.dart").getAbsolutePath());
9883 }
9884
9885 void test_resolve_nonFile() {
9886 UriResolver resolver = new FileUriResolver();
9887 Source result =
9888 resolver.resolveAbsolute(parseUriWithException("dart:core"));
9889 expect(result, isNull);
9890 }
9891 }
9892
9893
9894 class HtmlParserTest extends EngineTestCase {
9895 /**
9896 * The name of the 'script' tag in an HTML file.
9897 */
9898 static String _TAG_SCRIPT = "script";
9899 void fail_parse_scriptWithComment() {
9900 String scriptBody = r'''
9901 /**
9902 * <editable-label bind-value="dartAsignableValue">
9903 * </editable-label>
9904 */
9905 class Foo {}''';
9906 ht.HtmlUnit htmlUnit = parse("""
9907 <html>
9908 <body>
9909 <script type='application/dart'>
9910 $scriptBody
9911 </script>
9912 </body>
9913 </html>""");
9914 _validate(
9915 htmlUnit,
9916 [
9917 _t4(
9918 "html",
9919 [
9920 _t4("body", [_t("script", _a(["type", "'application/dart'"]) , scriptBody)])])]);
9921 }
9922 ht.HtmlUnit parse(String contents) {
9923 // TestSource source =
9924 // new TestSource.con1(FileUtilities2.createFile("/test.dart"), contents) ;
9925 ht.AbstractScanner scanner = new ht.StringScanner(null, contents);
9926 scanner.passThroughElements = <String>[_TAG_SCRIPT];
9927 ht.Token token = scanner.tokenize();
9928 LineInfo lineInfo = new LineInfo(scanner.lineStarts);
9929 GatheringErrorListener errorListener = new GatheringErrorListener();
9930 ht.HtmlUnit unit =
9931 new ht.HtmlParser(null, errorListener).parse(token, lineInfo);
9932 errorListener.assertNoErrors();
9933 return unit;
9934 }
9935 void test_parse_attribute() {
9936 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsdf\"></body></html>");
9937 _validate(
9938 htmlUnit,
9939 [_t4("html", [_t("body", _a(["foo", "\"sdfsdf\""]), "")])]);
9940 ht.XmlTagNode htmlNode = htmlUnit.tagNodes[0];
9941 ht.XmlTagNode bodyNode = htmlNode.tagNodes[0];
9942 expect(bodyNode.attributes[0].text, "sdfsdf");
9943 }
9944 void test_parse_attribute_EOF() {
9945 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsdf\"");
9946 _validate(
9947 htmlUnit,
9948 [_t4("html", [_t("body", _a(["foo", "\"sdfsdf\""]), "")])]);
9949 }
9950 void test_parse_attribute_EOF_missing_quote() {
9951 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsd");
9952 _validate(
9953 htmlUnit,
9954 [_t4("html", [_t("body", _a(["foo", "\"sdfsd"]), "")])]);
9955 ht.XmlTagNode htmlNode = htmlUnit.tagNodes[0];
9956 ht.XmlTagNode bodyNode = htmlNode.tagNodes[0];
9957 expect(bodyNode.attributes[0].text, "sdfsd");
9958 }
9959 void test_parse_attribute_extra_quote() {
9960 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsdf\"\"></body></html>");
9961 _validate(
9962 htmlUnit,
9963 [_t4("html", [_t("body", _a(["foo", "\"sdfsdf\""]), "")])]);
9964 }
9965 void test_parse_attribute_single_quote() {
9966 ht.HtmlUnit htmlUnit = parse("<html><body foo='sdfsdf'></body></html>");
9967 _validate(
9968 htmlUnit,
9969 [_t4("html", [_t("body", _a(["foo", "'sdfsdf'"]), "")])]);
9970 ht.XmlTagNode htmlNode = htmlUnit.tagNodes[0];
9971 ht.XmlTagNode bodyNode = htmlNode.tagNodes[0];
9972 expect(bodyNode.attributes[0].text, "sdfsdf");
9973 }
9974 void test_parse_comment_embedded() {
9975 ht.HtmlUnit htmlUnit = parse("<html <!-- comment -->></html>");
9976 _validate(htmlUnit, [_t3("html", "")]);
9977 }
9978 void test_parse_comment_first() {
9979 ht.HtmlUnit htmlUnit = parse("<!-- comment --><html></html>");
9980 _validate(htmlUnit, [_t3("html", "")]);
9981 }
9982 void test_parse_comment_in_content() {
9983 ht.HtmlUnit htmlUnit = parse("<html><!-- comment --></html>");
9984 _validate(htmlUnit, [_t3("html", "<!-- comment -->")]);
9985 }
9986 void test_parse_content() {
9987 ht.HtmlUnit htmlUnit = parse("<html>\n<p a=\"b\">blat \n </p>\n</html>");
9988 // ht.XmlTagNode.getContent() does not include whitespace
9989 // between '<' and '>' at this time
9990 _validate(
9991 htmlUnit,
9992 [
9993 _t3(
9994 "html",
9995 "\n<pa=\"b\">blat \n </p>\n",
9996 [_t("p", _a(["a", "\"b\""]), "blat \n ")])]);
9997 }
9998 void test_parse_content_none() {
9999 ht.HtmlUnit htmlUnit = parse("<html><p/>blat<p/></html>");
10000 _validate(
10001 htmlUnit,
10002 [_t3("html", "<p/>blat<p/>", [_t3("p", ""), _t3("p", "")])]);
10003 }
10004 void test_parse_declaration() {
10005 ht.HtmlUnit htmlUnit = parse("<!DOCTYPE html>\n\n<html><p></p></html>");
10006 _validate(htmlUnit, [_t4("html", [_t3("p", "")])]);
10007 }
10008 void test_parse_directive() {
10009 ht.HtmlUnit htmlUnit = parse("<?xml ?>\n\n<html><p></p></html>");
10010 _validate(htmlUnit, [_t4("html", [_t3("p", "")])]);
10011 }
10012 void test_parse_getAttribute() {
10013 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsdf\"></body></html>");
10014 ht.XmlTagNode htmlNode = htmlUnit.tagNodes[0];
10015 ht.XmlTagNode bodyNode = htmlNode.tagNodes[0];
10016 expect(bodyNode.getAttribute("foo").text, "sdfsdf");
10017 expect(bodyNode.getAttribute("bar"), null);
10018 expect(bodyNode.getAttribute(null), null);
10019 }
10020 void test_parse_getAttributeText() {
10021 ht.HtmlUnit htmlUnit = parse("<html><body foo=\"sdfsdf\"></body></html>");
10022 ht.XmlTagNode htmlNode = htmlUnit.tagNodes[0];
10023 ht.XmlTagNode bodyNode = htmlNode.tagNodes[0];
10024 expect(bodyNode.getAttributeText("foo"), "sdfsdf");
10025 expect(bodyNode.getAttributeText("bar"), null);
10026 expect(bodyNode.getAttributeText(null), null);
10027 }
10028 void test_parse_headers() {
10029 String code = r'''
10030 <html>
10031 <body>
10032 <h2>000</h2>
10033 <div>
10034 111
10035 </div>
10036 </body>
10037 </html>''';
10038 ht.HtmlUnit htmlUnit = parse(code);
10039 _validate(
10040 htmlUnit,
10041 [_t4("html", [_t4("body", [_t3("h2", "000"), _t4("div")])])]);
10042 }
10043 void test_parse_script() {
10044 ht.HtmlUnit htmlUnit =
10045 parse("<html><script >here is <p> some</script></html>");
10046 _validate(htmlUnit, [_t4("html", [_t3("script", "here is <p> some")])]);
10047 }
10048 void test_parse_self_closing() {
10049 ht.HtmlUnit htmlUnit = parse("<html>foo<br>bar</html>");
10050 _validate(htmlUnit, [_t3("html", "foo<br>bar", [_t3("br", "")])]);
10051 }
10052 void test_parse_self_closing_declaration() {
10053 ht.HtmlUnit htmlUnit = parse("<!DOCTYPE html><html>foo</html>");
10054 _validate(htmlUnit, [_t3("html", "foo")]);
10055 }
10056 XmlValidator_Attributes _a(List<String> keyValuePairs) =>
10057 new XmlValidator_Attributes(keyValuePairs);
10058 XmlValidator_Tag _t(String tag, XmlValidator_Attributes attributes,
10059 String content, [List<XmlValidator_Tag> children =
10060 XmlValidator_Tag.EMPTY_LIST]) =>
10061 new XmlValidator_Tag(tag, attributes, content, children);
10062 XmlValidator_Tag _t3(String tag, String content,
10063 [List<XmlValidator_Tag> children = XmlValidator_Tag.EMPTY_LIST]) =>
10064 new XmlValidator_Tag(tag, new XmlValidator_Attributes(), content, children );
10065 XmlValidator_Tag _t4(String tag, [List<XmlValidator_Tag> children =
10066 XmlValidator_Tag.EMPTY_LIST]) =>
10067 new XmlValidator_Tag(tag, new XmlValidator_Attributes(), null, children);
10068 void _validate(ht.HtmlUnit htmlUnit, List<XmlValidator_Tag> expectedTags) {
10069 XmlValidator validator = new XmlValidator();
10070 validator.expectTags(expectedTags);
10071 htmlUnit.accept(validator);
10072 validator.assertValid();
10073 }
10074 }
10075
10076
10077 class HtmlTagInfoBuilderTest extends HtmlParserTest {
10078 void test_builder() {
10079 HtmlTagInfoBuilder builder = new HtmlTagInfoBuilder();
10080 ht.HtmlUnit unit = parse(r'''
10081 <html>
10082 <body>
10083 <div id="x"></div>
10084 <p class='c'></p>
10085 <div class='c'></div>
10086 </body>
10087 </html>''');
10088 unit.accept(builder);
10089 HtmlTagInfo info = builder.getTagInfo();
10090 expect(info, isNotNull);
10091 List<String> allTags = info.allTags;
10092 expect(allTags, hasLength(4));
10093 expect(info.getTagWithId("x"), "div");
10094 List<String> tagsWithClass = info.getTagsWithClass("c");
10095 expect(tagsWithClass, hasLength(2));
10096 }
10097 }
10098
10099
10100 class HtmlUnitBuilderTest extends EngineTestCase {
10101 AnalysisContextImpl _context;
10102 @override
10103 void setUp() {
10104 _context = AnalysisContextFactory.contextWithCore();
10105 }
10106 @override
10107 void tearDown() {
10108 _context = null;
10109 super.tearDown();
10110 }
10111 void test_embedded_script() {
10112 HtmlElementImpl element = _build(r'''
10113 <html>
10114 <script type="application/dart">foo=2;</script>
10115 </html>''');
10116 _validate(element, [_s(_l([_v("foo")]))]);
10117 }
10118 void test_embedded_script_no_content() {
10119 HtmlElementImpl element = _build(r'''
10120 <html>
10121 <script type="application/dart"></script>
10122 </html>''');
10123 _validate(element, [_s(_l())]);
10124 }
10125 void test_external_script() {
10126 HtmlElementImpl element = _build(r'''
10127 <html>
10128 <script type="application/dart" src="other.dart"/>
10129 </html>''');
10130 _validate(element, [_s2("other.dart")]);
10131 }
10132 void test_external_script_no_source() {
10133 HtmlElementImpl element = _build(r'''
10134 <html>
10135 <script type="application/dart"/>
10136 </html>''');
10137 _validate(element, [_s2(null)]);
10138 }
10139 void test_external_script_with_content() {
10140 HtmlElementImpl element = _build(r'''
10141 <html>
10142 <script type="application/dart" src="other.dart">blat=2;</script>
10143 </html>''');
10144 _validate(element, [_s2("other.dart")]);
10145 }
10146 void test_no_scripts() {
10147 HtmlElementImpl element = _build(r'''
10148 <!DOCTYPE html>
10149 <html><p></p></html>''');
10150 _validate(element, []);
10151 }
10152 void test_two_dart_scripts() {
10153 HtmlElementImpl element = _build(r'''
10154 <html>
10155 <script type="application/dart">bar=2;</script>
10156 <script type="application/dart" src="other.dart"/>
10157 <script src="dart.js"/>
10158 </html>''');
10159 _validate(element, [_s(_l([_v("bar")])), _s2("other.dart")]);
10160 }
10161 HtmlElementImpl _build(String contents) {
10162 TestSource source = new TestSource(
10163 FileUtilities2.createFile("/test.html").getAbsolutePath(),
10164 contents);
10165 ChangeSet changeSet = new ChangeSet();
10166 changeSet.addedSource(source);
10167 _context.applyChanges(changeSet);
10168 HtmlUnitBuilder builder = new HtmlUnitBuilder(_context);
10169 return builder.buildHtmlElement(source, _context.parseHtmlUnit(source));
10170 }
10171 HtmlUnitBuilderTest_ExpectedLibrary
10172 _l([List<HtmlUnitBuilderTest_ExpectedVariable> expectedVariables =
10173 HtmlUnitBuilderTest_ExpectedVariable.EMPTY_LIST]) =>
10174 new HtmlUnitBuilderTest_ExpectedLibrary(this, expectedVariables);
10175 _ExpectedScript _s(HtmlUnitBuilderTest_ExpectedLibrary expectedLibrary) =>
10176 new _ExpectedScript.con1(expectedLibrary);
10177 _ExpectedScript _s2(String scriptSourcePath) =>
10178 new _ExpectedScript.con2(scriptSourcePath);
10179 HtmlUnitBuilderTest_ExpectedVariable _v(String varName) =>
10180 new HtmlUnitBuilderTest_ExpectedVariable(varName);
10181 void _validate(HtmlElementImpl element,
10182 List<_ExpectedScript> expectedScripts) {
10183 expect(element.context, same(_context));
10184 List<HtmlScriptElement> scripts = element.scripts;
10185 expect(scripts, isNotNull);
10186 expect(scripts, hasLength(expectedScripts.length));
10187 for (int scriptIndex = 0; scriptIndex < scripts.length; scriptIndex++) {
10188 expectedScripts[scriptIndex]._validate(scriptIndex, scripts[scriptIndex]);
10189 }
10190 }
10191 }
10192
10193
10194 class HtmlUnitBuilderTest_ExpectedLibrary {
10195 final HtmlUnitBuilderTest HtmlUnitBuilderTest_this;
10196 final List<HtmlUnitBuilderTest_ExpectedVariable> _expectedVariables;
10197 HtmlUnitBuilderTest_ExpectedLibrary(this.HtmlUnitBuilderTest_this,
10198 [this._expectedVariables = HtmlUnitBuilderTest_ExpectedVariable.EMPTY_LIST ]);
10199 void _validate(int scriptIndex, EmbeddedHtmlScriptElementImpl script) {
10200 LibraryElement library = script.scriptLibrary;
10201 expect(library, isNotNull, reason: "script $scriptIndex");
10202 expect(
10203 script.context,
10204 same(HtmlUnitBuilderTest_this._context),
10205 reason: "script $scriptIndex");
10206 CompilationUnitElement unit = library.definingCompilationUnit;
10207 expect(unit, isNotNull, reason: "script $scriptIndex");
10208 List<TopLevelVariableElement> variables = unit.topLevelVariables;
10209 expect(variables, hasLength(_expectedVariables.length));
10210 for (int index = 0; index < variables.length; index++) {
10211 _expectedVariables[index].validate(scriptIndex, variables[index]);
10212 }
10213 expect(
10214 library.enclosingElement,
10215 same(script),
10216 reason: "script $scriptIndex");
10217 }
10218 }
10219
10220
10221 class HtmlUnitBuilderTest_ExpectedVariable {
10222 static const List<HtmlUnitBuilderTest_ExpectedVariable> EMPTY_LIST = const
10223 <HtmlUnitBuilderTest_ExpectedVariable>[
10224 ];
10225 final String _expectedName;
10226 HtmlUnitBuilderTest_ExpectedVariable(this._expectedName);
10227 void validate(int scriptIndex, TopLevelVariableElement variable) {
10228 expect(variable, isNotNull, reason: "script $scriptIndex");
10229 expect(variable.name, _expectedName, reason: "script $scriptIndex");
10230 }
10231 }
10232
10233
10234 /**
10235 * Instances of the class `HtmlWarningCodeTest` test the generation of HTML warn ing codes.
10236 */
10237 class HtmlWarningCodeTest extends EngineTestCase {
10238 /**
10239 * The source factory used to create the sources to be resolved.
10240 */
10241 SourceFactory _sourceFactory;
10242
10243 /**
10244 * The analysis context used to resolve the HTML files.
10245 */
10246 AnalysisContextImpl _context;
10247
10248 /**
10249 * The contents of the 'test.html' file.
10250 */
10251 String _contents;
10252
10253 /**
10254 * The list of reported errors.
10255 */
10256 List<AnalysisError> _errors;
10257 @override
10258 void setUp() {
10259 _sourceFactory = new SourceFactory([new FileUriResolver()]);
10260 _context = new AnalysisContextImpl();
10261 _context.sourceFactory = _sourceFactory;
10262 }
10263
10264 @override
10265 void tearDown() {
10266 _sourceFactory = null;
10267 _context = null;
10268 _contents = null;
10269 _errors = null;
10270 super.tearDown();
10271 }
10272
10273 void test_invalidUri() {
10274 _verify(r'''
10275 <html>
10276 <script type='application/dart' src='ht:'/>
10277 </html>''', [HtmlWarningCode.INVALID_URI]);
10278 _assertErrorLocation2(_errors[0], "ht:");
10279 }
10280
10281 void test_uriDoesNotExist() {
10282 _verify(r'''
10283 <html>
10284 <script type='application/dart' src='other.dart'/>
10285 </html>''', [HtmlWarningCode.URI_DOES_NOT_EXIST]);
10286 _assertErrorLocation2(_errors[0], "other.dart");
10287 }
10288
10289 void _assertErrorLocation(AnalysisError error, int expectedOffset,
10290 int expectedLength) {
10291 expect(error.offset, expectedOffset, reason: error.toString());
10292 expect(error.length, expectedLength, reason: error.toString());
10293 }
10294
10295 void _assertErrorLocation2(AnalysisError error, String expectedString) {
10296 _assertErrorLocation(
10297 error,
10298 _contents.indexOf(expectedString),
10299 expectedString.length);
10300 }
10301
10302 void _verify(String contents, List<ErrorCode> expectedErrorCodes) {
10303 this._contents = contents;
10304 TestSource source = new TestSource(
10305 FileUtilities2.createFile("/test.html").getAbsolutePath(),
10306 contents);
10307 ChangeSet changeSet = new ChangeSet();
10308 changeSet.addedSource(source);
10309 _context.applyChanges(changeSet);
10310 HtmlUnitBuilder builder = new HtmlUnitBuilder(_context);
10311 builder.buildHtmlElement(source, _context.parseHtmlUnit(source));
10312 GatheringErrorListener errorListener = new GatheringErrorListener();
10313 errorListener.addAll2(builder.errorListener);
10314 errorListener.assertErrorsWithCodes(expectedErrorCodes);
10315 _errors = errorListener.errors;
10316 }
10317 }
10318
10319
10320 /**
10321 * Instances of the class `MockDartSdk` implement a [DartSdk].
10322 */
10323 class MockDartSdk implements DartSdk {
10324 @override
10325 AnalysisContext get context => null;
10326
10327 @override
10328 List<SdkLibrary> get sdkLibraries => null;
10329
10330 @override
10331 String get sdkVersion => null;
10332
10333 @override
10334 List<String> get uris => null;
10335
10336 @override
10337 Source fromFileUri(Uri uri) => null;
10338
10339 @override
10340 SdkLibrary getSdkLibrary(String dartUri) => null;
10341
10342 @override
10343 Source mapDartUri(String dartUri) => null;
10344 }
10345
10346
10347 class ReferenceFinderTest extends EngineTestCase {
10348 DirectedGraph<AstNode> _referenceGraph;
10349 Map<VariableElement, VariableDeclaration> _variableDeclarationMap;
10350 Map<ConstructorElement, ConstructorDeclaration> _constructorDeclarationMap;
10351 VariableDeclaration _head;
10352 AstNode _tail;
10353 @override
10354 void setUp() {
10355 _referenceGraph = new DirectedGraph<AstNode>();
10356 _variableDeclarationMap =
10357 new HashMap<VariableElement, VariableDeclaration>();
10358 _constructorDeclarationMap =
10359 new HashMap<ConstructorElement, ConstructorDeclaration>();
10360 _head = AstFactory.variableDeclaration("v1");
10361 }
10362 void test_visitInstanceCreationExpression_const() {
10363 _visitNode(_makeTailConstructor("A", true, true, true));
10364 _assertOneArc(_tail);
10365 }
10366 void test_visitInstanceCreationExpression_nonConstDeclaration() {
10367 // In the source:
10368 // const x = const A();
10369 // x depends on "const A()" even if the A constructor
10370 // isn't declared as const.
10371 _visitNode(_makeTailConstructor("A", false, true, true));
10372 _assertOneArc(_tail);
10373 }
10374 void test_visitInstanceCreationExpression_nonConstUsage() {
10375 _visitNode(_makeTailConstructor("A", true, false, true));
10376 _assertNoArcs();
10377 }
10378 void test_visitInstanceCreationExpression_notInMap() {
10379 // In the source:
10380 // const x = const A();
10381 // x depends on "const A()" even if the AST for the A constructor
10382 // isn't available.
10383 _visitNode(_makeTailConstructor("A", true, true, false));
10384 _assertOneArc(_tail);
10385 }
10386 void test_visitSimpleIdentifier_const() {
10387 _visitNode(_makeTailVariable("v2", true, true));
10388 _assertOneArc(_tail);
10389 }
10390 void test_visitSimpleIdentifier_nonConst() {
10391 _visitNode(_makeTailVariable("v2", false, true));
10392 _assertNoArcs();
10393 }
10394 void test_visitSimpleIdentifier_notInMap() {
10395 _visitNode(_makeTailVariable("v2", true, false));
10396 _assertNoArcs();
10397 }
10398 void test_visitSuperConstructorInvocation_const() {
10399 _visitNode(_makeTailSuperConstructorInvocation("A", true, true));
10400 _assertOneArc(_tail);
10401 }
10402 void test_visitSuperConstructorInvocation_nonConst() {
10403 _visitNode(_makeTailSuperConstructorInvocation("A", false, true));
10404 _assertNoArcs();
10405 }
10406 void test_visitSuperConstructorInvocation_notInMap() {
10407 _visitNode(_makeTailSuperConstructorInvocation("A", true, false));
10408 _assertNoArcs();
10409 }
10410 void test_visitSuperConstructorInvocation_unresolved() {
10411 SuperConstructorInvocation superConstructorInvocation =
10412 AstFactory.superConstructorInvocation();
10413 _tail = superConstructorInvocation;
10414 _visitNode(superConstructorInvocation);
10415 _assertNoArcs();
10416 }
10417 void _assertNoArcs() {
10418 Set<AstNode> tails = _referenceGraph.getTails(_head);
10419 expect(tails, hasLength(0));
10420 }
10421 void _assertOneArc(AstNode tail) {
10422 Set<AstNode> tails = _referenceGraph.getTails(_head);
10423 expect(tails, hasLength(1));
10424 expect(tails.first, same(tail));
10425 }
10426 ReferenceFinder _createReferenceFinder(AstNode source) =>
10427 new ReferenceFinder(
10428 source,
10429 _referenceGraph,
10430 _variableDeclarationMap,
10431 _constructorDeclarationMap);
10432 InstanceCreationExpression _makeTailConstructor(String name,
10433 bool isConstDeclaration, bool isConstUsage, bool inMap) {
10434 List<ConstructorInitializer> initializers =
10435 new List<ConstructorInitializer>();
10436 ConstructorDeclaration constructorDeclaration =
10437 AstFactory.constructorDeclaration(
10438 AstFactory.identifier3(name),
10439 null,
10440 AstFactory.formalParameterList(),
10441 initializers);
10442 if (isConstDeclaration) {
10443 constructorDeclaration.constKeyword = new KeywordToken(Keyword.CONST, 0);
10444 }
10445 ClassElementImpl classElement = ElementFactory.classElement2(name);
10446 SimpleIdentifier identifier = AstFactory.identifier3(name);
10447 TypeName type = AstFactory.typeName3(identifier);
10448 InstanceCreationExpression instanceCreationExpression =
10449 AstFactory.instanceCreationExpression2(
10450 isConstUsage ? Keyword.CONST : Keyword.NEW,
10451 type);
10452 _tail = instanceCreationExpression;
10453 ConstructorElementImpl constructorElement =
10454 ElementFactory.constructorElement(classElement, name, isConstDeclaration );
10455 if (inMap) {
10456 _constructorDeclarationMap[constructorElement] = constructorDeclaration;
10457 }
10458 instanceCreationExpression.staticElement = constructorElement;
10459 return instanceCreationExpression;
10460 }
10461 SuperConstructorInvocation _makeTailSuperConstructorInvocation(String name,
10462 bool isConst, bool inMap) {
10463 List<ConstructorInitializer> initializers =
10464 new List<ConstructorInitializer>();
10465 ConstructorDeclaration constructorDeclaration =
10466 AstFactory.constructorDeclaration(
10467 AstFactory.identifier3(name),
10468 null,
10469 AstFactory.formalParameterList(),
10470 initializers);
10471 _tail = constructorDeclaration;
10472 if (isConst) {
10473 constructorDeclaration.constKeyword = new KeywordToken(Keyword.CONST, 0);
10474 }
10475 ClassElementImpl classElement = ElementFactory.classElement2(name);
10476 SuperConstructorInvocation superConstructorInvocation =
10477 AstFactory.superConstructorInvocation();
10478 ConstructorElementImpl constructorElement =
10479 ElementFactory.constructorElement(classElement, name, isConst);
10480 if (inMap) {
10481 _constructorDeclarationMap[constructorElement] = constructorDeclaration;
10482 }
10483 superConstructorInvocation.staticElement = constructorElement;
10484 return superConstructorInvocation;
10485 }
10486 SimpleIdentifier _makeTailVariable(String name, bool isConst, bool inMap) {
10487 VariableDeclaration variableDeclaration =
10488 AstFactory.variableDeclaration(name);
10489 _tail = variableDeclaration;
10490 VariableElementImpl variableElement =
10491 ElementFactory.localVariableElement2(name);
10492 variableElement.const3 = isConst;
10493 AstFactory.variableDeclarationList2(
10494 isConst ? Keyword.CONST : Keyword.VAR,
10495 [variableDeclaration]);
10496 if (inMap) {
10497 _variableDeclarationMap[variableElement] = variableDeclaration;
10498 }
10499 SimpleIdentifier identifier = AstFactory.identifier3(name);
10500 identifier.staticElement = variableElement;
10501 return identifier;
10502 }
10503 void _visitNode(AstNode node) {
10504 node.accept(_createReferenceFinder(_head));
10505 }
10506 }
10507
10508
10509 class SDKLibrariesReaderTest extends EngineTestCase {
10510 void test_readFrom_dart2js() {
10511 LibraryMap libraryMap = new SdkLibrariesReader(
10512 true).readFromFile(FileUtilities2.createFile("/libs.dart"), r'''
10513 final Map<String, LibraryInfo> LIBRARIES = const <String, LibraryInfo> {
10514 'first' : const LibraryInfo(
10515 'first/first.dart',
10516 category: 'First',
10517 documented: true,
10518 platforms: VM_PLATFORM,
10519 dart2jsPath: 'first/first_dart2js.dart'),
10520 };''');
10521 expect(libraryMap, isNotNull);
10522 expect(libraryMap.size(), 1);
10523 SdkLibrary first = libraryMap.getLibrary("dart:first");
10524 expect(first, isNotNull);
10525 expect(first.category, "First");
10526 expect(first.path, "first/first_dart2js.dart");
10527 expect(first.shortName, "dart:first");
10528 expect(first.isDart2JsLibrary, false);
10529 expect(first.isDocumented, true);
10530 expect(first.isImplementation, false);
10531 expect(first.isVmLibrary, true);
10532 }
10533 void test_readFrom_empty() {
10534 LibraryMap libraryMap = new SdkLibrariesReader(
10535 false).readFromFile(FileUtilities2.createFile("/libs.dart"), "");
10536 expect(libraryMap, isNotNull);
10537 expect(libraryMap.size(), 0);
10538 }
10539 void test_readFrom_normal() {
10540 LibraryMap libraryMap = new SdkLibrariesReader(
10541 false).readFromFile(FileUtilities2.createFile("/libs.dart"), r'''
10542 final Map<String, LibraryInfo> LIBRARIES = const <String, LibraryInfo> {
10543 'first' : const LibraryInfo(
10544 'first/first.dart',
10545 category: 'First',
10546 documented: true,
10547 platforms: VM_PLATFORM),
10548
10549 'second' : const LibraryInfo(
10550 'second/second.dart',
10551 category: 'Second',
10552 documented: false,
10553 implementation: true,
10554 platforms: 0),
10555 };''');
10556 expect(libraryMap, isNotNull);
10557 expect(libraryMap.size(), 2);
10558 SdkLibrary first = libraryMap.getLibrary("dart:first");
10559 expect(first, isNotNull);
10560 expect(first.category, "First");
10561 expect(first.path, "first/first.dart");
10562 expect(first.shortName, "dart:first");
10563 expect(first.isDart2JsLibrary, false);
10564 expect(first.isDocumented, true);
10565 expect(first.isImplementation, false);
10566 expect(first.isVmLibrary, true);
10567 SdkLibrary second = libraryMap.getLibrary("dart:second");
10568 expect(second, isNotNull);
10569 expect(second.category, "Second");
10570 expect(second.path, "second/second.dart");
10571 expect(second.shortName, "dart:second");
10572 expect(second.isDart2JsLibrary, false);
10573 expect(second.isDocumented, false);
10574 expect(second.isImplementation, true);
10575 expect(second.isVmLibrary, false);
10576 }
10577 }
10578
10579
10580 class SourceFactoryTest {
10581 void test_creation() {
10582 expect(new SourceFactory([]), isNotNull);
10583 }
10584 void test_fromEncoding_invalidUri() {
10585 SourceFactory factory = new SourceFactory([]);
10586 try {
10587 factory.fromEncoding("<:&%>");
10588 fail("Expected IllegalArgumentException");
10589 } on IllegalArgumentException catch (exception) {
10590 }
10591 }
10592 void test_fromEncoding_noResolver() {
10593 SourceFactory factory = new SourceFactory([]);
10594 try {
10595 factory.fromEncoding("foo:/does/not/exist.dart");
10596 fail("Expected IllegalArgumentException");
10597 } on IllegalArgumentException catch (exception) {
10598 }
10599 }
10600 void test_fromEncoding_valid() {
10601 String encoding = "file:///does/not/exist.dart";
10602 SourceFactory factory = new SourceFactory(
10603 [new UriResolver_SourceFactoryTest_test_fromEncoding_valid(encoding)]);
10604 expect(factory.fromEncoding(encoding), isNotNull);
10605 }
10606 void test_resolveUri_absolute() {
10607 UriResolver_absolute resolver = new UriResolver_absolute();
10608 SourceFactory factory = new SourceFactory([resolver]);
10609 factory.resolveUri(null, "dart:core");
10610 expect(resolver.invoked, isTrue);
10611 }
10612 void test_resolveUri_nonAbsolute_absolute() {
10613 SourceFactory factory =
10614 new SourceFactory([new UriResolver_nonAbsolute_absolute()]);
10615 String absolutePath = "/does/not/matter.dart";
10616 Source containingSource =
10617 new FileBasedSource.con1(FileUtilities2.createFile("/does/not/exist.dart "));
10618 Source result = factory.resolveUri(containingSource, absolutePath);
10619 expect(
10620 result.fullName,
10621 FileUtilities2.createFile(absolutePath).getAbsolutePath());
10622 }
10623 void test_resolveUri_nonAbsolute_relative() {
10624 SourceFactory factory =
10625 new SourceFactory([new UriResolver_nonAbsolute_relative()]);
10626 Source containingSource =
10627 new FileBasedSource.con1(FileUtilities2.createFile("/does/not/have.dart" ));
10628 Source result = factory.resolveUri(containingSource, "exist.dart");
10629 expect(
10630 result.fullName,
10631 FileUtilities2.createFile("/does/not/exist.dart").getAbsolutePath());
10632 }
10633 void test_restoreUri() {
10634 JavaFile file1 = FileUtilities2.createFile("/some/file1.dart");
10635 JavaFile file2 = FileUtilities2.createFile("/some/file2.dart");
10636 Source source1 = new FileBasedSource.con1(file1);
10637 Source source2 = new FileBasedSource.con1(file2);
10638 Uri expected1 = parseUriWithException("file:///my_file.dart");
10639 SourceFactory factory =
10640 new SourceFactory([new UriResolver_restoreUri(source1, expected1)]);
10641 expect(factory.restoreUri(source1), same(expected1));
10642 expect(factory.restoreUri(source2), same(null));
10643 }
10644 }
10645
10646
10647 class StringScannerTest extends AbstractScannerTest {
10648 @override
10649 ht.AbstractScanner newScanner(String input) {
10650 return new ht.StringScanner(null, input);
10651 }
10652 }
10653
10654
10655 /**
10656 * Instances of the class `ToSourceVisitorTest`
10657 */
10658 class ToSourceVisitorTest extends EngineTestCase {
10659 void fail_visitHtmlScriptTagNode_attributes_content() {
10660 _assertSource(
10661 "<script type='application/dart'>f() {}</script>",
10662 HtmlFactory.scriptTagWithContent(
10663 "f() {}",
10664 [HtmlFactory.attribute("type", "'application/dart'")]));
10665 }
10666
10667 void fail_visitHtmlScriptTagNode_noAttributes_content() {
10668 _assertSource(
10669 "<script>f() {}</script>",
10670 HtmlFactory.scriptTagWithContent("f() {}"));
10671 }
10672
10673 void test_visitHtmlScriptTagNode_attributes_noContent() {
10674 _assertSource(
10675 "<script type='application/dart'/>",
10676 HtmlFactory.scriptTag([HtmlFactory.attribute("type", "'application/dart' ")]));
10677 }
10678
10679 void test_visitHtmlScriptTagNode_noAttributes_noContent() {
10680 _assertSource("<script/>", HtmlFactory.scriptTag());
10681 }
10682
10683 void test_visitHtmlUnit_empty() {
10684 _assertSource("", new ht.HtmlUnit(null, new List<ht.XmlTagNode>(), null));
10685 }
10686
10687 void test_visitHtmlUnit_nonEmpty() {
10688 _assertSource(
10689 "<html/>",
10690 new ht.HtmlUnit(null, [HtmlFactory.tagNode("html")], null));
10691 }
10692
10693 void test_visitXmlAttributeNode() {
10694 _assertSource("x=y", HtmlFactory.attribute("x", "y"));
10695 }
10696
10697 /**
10698 * Assert that a `ToSourceVisitor` will produce the expected source when visit ing the given
10699 * node.
10700 *
10701 * @param expectedSource the source string that the visitor is expected to pro duce
10702 * @param node the AST node being visited to produce the actual source
10703 */
10704 void _assertSource(String expectedSource, ht.XmlNode node) {
10705 PrintStringWriter writer = new PrintStringWriter();
10706 node.accept(new ht.ToSourceVisitor(writer));
10707 expect(writer.toString(), expectedSource);
10708 }
10709 }
10710
10711
10712 class UriKindTest {
10713 void test_fromEncoding() {
10714 expect(UriKind.fromEncoding(0x64), same(UriKind.DART_URI));
10715 expect(UriKind.fromEncoding(0x66), same(UriKind.FILE_URI));
10716 expect(UriKind.fromEncoding(0x70), same(UriKind.PACKAGE_URI));
10717 expect(UriKind.fromEncoding(0x58), same(null));
10718 }
10719
10720 void test_getEncoding() {
10721 expect(UriKind.DART_URI.encoding, 0x64);
10722 expect(UriKind.FILE_URI.encoding, 0x66);
10723 expect(UriKind.PACKAGE_URI.encoding, 0x70);
10724 }
10725 }
10726
10727
10728 class UriResolver_absolute extends UriResolver {
10729 bool invoked = false;
10730
10731 UriResolver_absolute();
10732
10733 @override
10734 Source resolveAbsolute(Uri uri) {
10735 invoked = true;
10736 return null;
10737 }
10738 }
10739
10740
10741 class UriResolver_nonAbsolute_absolute extends UriResolver {
10742 @override
10743 Source resolveAbsolute(Uri uri) {
10744 return new FileBasedSource.con2(uri, new JavaFile.fromUri(uri));
10745 }
10746 }
10747
10748
10749 class UriResolver_nonAbsolute_relative extends UriResolver {
10750 @override
10751 Source resolveAbsolute(Uri uri) {
10752 return new FileBasedSource.con2(uri, new JavaFile.fromUri(uri));
10753 }
10754 }
10755
10756
10757 class UriResolver_restoreUri extends UriResolver {
10758 Source source1;
10759
10760 Uri expected1;
10761
10762 UriResolver_restoreUri(this.source1, this.expected1);
10763
10764 @override
10765 Source resolveAbsolute(Uri uri) => null;
10766
10767 @override
10768 Uri restoreAbsolute(Source source) {
10769 if (identical(source, source1)) {
10770 return expected1;
10771 }
10772 return null;
10773 }
10774 }
10775
10776
10777 class UriResolver_SourceFactoryTest_test_fromEncoding_valid extends UriResolver
10778 {
10779 String encoding;
10780
10781 UriResolver_SourceFactoryTest_test_fromEncoding_valid(this.encoding);
10782
10783 @override
10784 Source resolveAbsolute(Uri uri) {
10785 if (uri.toString() == encoding) {
10786 return new TestSource();
10787 }
10788 return null;
10789 }
10790 }
10791
10792
10793 class ValidatingConstantValueComputer extends ConstantValueComputer {
10794 AstNode _nodeBeingEvaluated;
10795 ValidatingConstantValueComputer(TypeProvider typeProvider,
10796 DeclaredVariables declaredVariables)
10797 : super(typeProvider, declaredVariables);
10798
10799 @override
10800 void beforeComputeValue(AstNode constNode) {
10801 super.beforeComputeValue(constNode);
10802 _nodeBeingEvaluated = constNode;
10803 }
10804
10805 @override
10806 void beforeGetConstantInitializers(ConstructorElement constructor) {
10807 super.beforeGetConstantInitializers(constructor);
10808 // If we are getting the constant initializers for a node in the graph,
10809 // make sure we properly recorded the dependency.
10810 ConstructorDeclaration node = findConstructorDeclaration(constructor);
10811 if (node != null && referenceGraph.nodes.contains(node)) {
10812 expect(referenceGraph.containsPath(_nodeBeingEvaluated, node), isTrue);
10813 }
10814 }
10815
10816 @override
10817 void beforeGetParameterDefault(ParameterElement parameter) {
10818 super.beforeGetParameterDefault(parameter);
10819 // Find the ConstructorElement and figure out which
10820 // parameter we're talking about.
10821 ConstructorElement constructor =
10822 parameter.getAncestor((element) => element is ConstructorElement);
10823 int parameterIndex;
10824 List<ParameterElement> parameters = constructor.parameters;
10825 int numParameters = parameters.length;
10826 for (parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) {
10827 if (identical(parameters[parameterIndex], parameter)) {
10828 break;
10829 }
10830 }
10831 expect(parameterIndex < numParameters, isTrue);
10832 // If we are getting the default parameter for a constructor in the graph,
10833 // make sure we properly recorded the dependency on the parameter.
10834 ConstructorDeclaration constructorNode =
10835 constructorDeclarationMap[constructor];
10836 if (constructorNode != null) {
10837 FormalParameter parameterNode =
10838 constructorNode.parameters.parameters[parameterIndex];
10839 expect(referenceGraph.nodes.contains(parameterNode), isTrue);
10840 expect(
10841 referenceGraph.containsPath(_nodeBeingEvaluated, parameterNode),
10842 isTrue);
10843 }
10844 }
10845
10846 @override
10847 ConstantVisitor createConstantVisitor(ErrorReporter errorReporter) {
10848 return new ConstantValueComputerTest_ValidatingConstantVisitor(
10849 typeProvider,
10850 referenceGraph,
10851 _nodeBeingEvaluated,
10852 errorReporter);
10853 }
10854 }
10855
10856
10857 /**
10858 * Instances of `XmlValidator` traverse an [XmlNode] structure and validate the node
10859 * hierarchy.
10860 */
10861 class XmlValidator extends ht.RecursiveXmlVisitor<Object> {
10862 /**
10863 * A list containing the errors found while traversing the AST structure.
10864 */
10865 List<String> _errors = new List<String>();
10866 /**
10867 * The tags to expect when visiting or `null` if tags should not be checked.
10868 */
10869 List<XmlValidator_Tag> _expectedTagsInOrderVisited;
10870 /**
10871 * The current index into the [expectedTagsInOrderVisited] array.
10872 */
10873 int _expectedTagsIndex = 0;
10874 /**
10875 * The key/value pairs to expect when visiting or `null` if attributes should not be
10876 * checked.
10877 */
10878 List<String> _expectedAttributeKeyValuePairs;
10879 /**
10880 * The current index into the [expectedAttributeKeyValuePairs].
10881 */
10882 int _expectedAttributeIndex = 0;
10883 /**
10884 * Assert that no errors were found while traversing any of the AST structures that have been
10885 * visited.
10886 */
10887 void assertValid() {
10888 while (_expectedTagsIndex < _expectedTagsInOrderVisited.length) {
10889 String expectedTag =
10890 _expectedTagsInOrderVisited[_expectedTagsIndex++]._tag;
10891 _errors.add("Expected to visit node with tag: $expectedTag");
10892 }
10893 if (!_errors.isEmpty) {
10894 StringBuffer buffer = new StringBuffer();
10895 buffer.write("Invalid XML structure:");
10896 for (String message in _errors) {
10897 buffer.writeln();
10898 buffer.write(" ");
10899 buffer.write(message);
10900 }
10901 fail(buffer.toString());
10902 }
10903 }
10904 /**
10905 * Set the tags to be expected when visiting
10906 *
10907 * @param expectedTags the expected tags
10908 */
10909 void expectTags(List<XmlValidator_Tag> expectedTags) {
10910 // Flatten the hierarchy into expected order in which the tags are visited
10911 List<XmlValidator_Tag> expected = new List<XmlValidator_Tag>();
10912 _expectTags(expected, expectedTags);
10913 this._expectedTagsInOrderVisited = expected;
10914 }
10915 @override
10916 Object visitHtmlUnit(ht.HtmlUnit node) {
10917 if (node.parent != null) {
10918 _errors.add("HtmlUnit should not have a parent");
10919 }
10920 if (node.endToken.type != ht.TokenType.EOF) {
10921 _errors.add("HtmlUnit end token should be of type EOF");
10922 }
10923 _validateNode(node);
10924 return super.visitHtmlUnit(node);
10925 }
10926 @override
10927 Object visitXmlAttributeNode(ht.XmlAttributeNode actual) {
10928 if (actual.parent is! ht.XmlTagNode) {
10929 _errors.add(
10930 "Expected ${actual.runtimeType} to have parent of type XmlTagNode");
10931 }
10932 String actualName = actual.name;
10933 String actualValue = actual.valueToken.lexeme;
10934 if (_expectedAttributeIndex < _expectedAttributeKeyValuePairs.length) {
10935 String expectedName =
10936 _expectedAttributeKeyValuePairs[_expectedAttributeIndex];
10937 if (expectedName != actualName) {
10938 _errors.add(
10939 "Expected ${_expectedTagsIndex - 1} tag: ${_expectedTagsInOrderVisit ed[_expectedTagsIndex - 1]._tag} attribute ${_expectedAttributeIndex ~/ 2} to ha ve name: $expectedName but found: $actualName");
10940 }
10941 String expectedValue =
10942 _expectedAttributeKeyValuePairs[_expectedAttributeIndex + 1];
10943 if (expectedValue != actualValue) {
10944 _errors.add(
10945 "Expected ${_expectedTagsIndex - 1} tag: ${_expectedTagsInOrderVisit ed[_expectedTagsIndex - 1]._tag} attribute ${_expectedAttributeIndex ~/ 2} to ha ve value: $expectedValue but found: $actualValue");
10946 }
10947 } else {
10948 _errors.add(
10949 "Unexpected ${_expectedTagsIndex - 1} tag: ${_expectedTagsInOrderVisit ed[_expectedTagsIndex - 1]._tag} attribute ${_expectedAttributeIndex ~/ 2} name: $actualName value: $actualValue");
10950 }
10951 _expectedAttributeIndex += 2;
10952 _validateNode(actual);
10953 return super.visitXmlAttributeNode(actual);
10954 }
10955 @override
10956 Object visitXmlTagNode(ht.XmlTagNode actual) {
10957 if (!(actual.parent is ht.HtmlUnit || actual.parent is ht.XmlTagNode)) {
10958 _errors.add(
10959 "Expected ${actual.runtimeType} to have parent of type HtmlUnit or Xml TagNode");
10960 }
10961 if (_expectedTagsInOrderVisited != null) {
10962 String actualTag = actual.tag;
10963 if (_expectedTagsIndex < _expectedTagsInOrderVisited.length) {
10964 XmlValidator_Tag expected =
10965 _expectedTagsInOrderVisited[_expectedTagsIndex];
10966 if (expected._tag != actualTag) {
10967 _errors.add(
10968 "Expected $_expectedTagsIndex tag: ${expected._tag} but found: $ac tualTag");
10969 }
10970 _expectedAttributeKeyValuePairs = expected._attributes._keyValuePairs;
10971 int expectedAttributeCount =
10972 _expectedAttributeKeyValuePairs.length ~/
10973 2;
10974 int actualAttributeCount = actual.attributes.length;
10975 if (expectedAttributeCount != actualAttributeCount) {
10976 _errors.add(
10977 "Expected $_expectedTagsIndex tag: ${expected._tag} to have $expec tedAttributeCount attributes but found $actualAttributeCount");
10978 }
10979 _expectedAttributeIndex = 0;
10980 _expectedTagsIndex++;
10981 expect(actual.attributeEnd, isNotNull);
10982 expect(actual.contentEnd, isNotNull);
10983 int count = 0;
10984 ht.Token token = actual.attributeEnd.next;
10985 ht.Token lastToken = actual.contentEnd;
10986 while (!identical(token, lastToken)) {
10987 token = token.next;
10988 if (++count > 1000) {
10989 fail(
10990 "Expected $_expectedTagsIndex tag: ${expected._tag} to have a se quence of tokens from getAttributeEnd() to getContentEnd()");
10991 break;
10992 }
10993 }
10994 if (actual.attributeEnd.type == ht.TokenType.GT) {
10995 if (ht.HtmlParser.SELF_CLOSING.contains(actual.tag)) {
10996 expect(actual.closingTag, isNull);
10997 } else {
10998 expect(actual.closingTag, isNotNull);
10999 }
11000 } else if (actual.attributeEnd.type == ht.TokenType.SLASH_GT) {
11001 expect(actual.closingTag, isNull);
11002 } else {
11003 fail("Unexpected attribute end token: ${actual.attributeEnd.lexeme}");
11004 }
11005 if (expected._content != null && expected._content != actual.content) {
11006 _errors.add(
11007 "Expected $_expectedTagsIndex tag: ${expected._tag} to have conten t '${expected._content}' but found '${actual.content}'");
11008 }
11009 if (expected._children.length != actual.tagNodes.length) {
11010 _errors.add(
11011 "Expected $_expectedTagsIndex tag: ${expected._tag} to have ${expe cted._children.length} children but found ${actual.tagNodes.length}");
11012 } else {
11013 for (int index = 0; index < expected._children.length; index++) {
11014 String expectedChildTag = expected._children[index]._tag;
11015 String actualChildTag = actual.tagNodes[index].tag;
11016 if (expectedChildTag != actualChildTag) {
11017 _errors.add(
11018 "Expected $_expectedTagsIndex tag: ${expected._tag} child $ind ex to have tag: $expectedChildTag but found: $actualChildTag");
11019 }
11020 }
11021 }
11022 } else {
11023 _errors.add("Visited unexpected tag: $actualTag");
11024 }
11025 }
11026 _validateNode(actual);
11027 return super.visitXmlTagNode(actual);
11028 }
11029 /**
11030 * Append the specified tags to the array in depth first order
11031 *
11032 * @param expected the array to which the tags are added (not `null`)
11033 * @param expectedTags the expected tags to be added (not `null`, contains no `null`s)
11034 */
11035 void _expectTags(List<XmlValidator_Tag> expected,
11036 List<XmlValidator_Tag> expectedTags) {
11037 for (XmlValidator_Tag tag in expectedTags) {
11038 expected.add(tag);
11039 _expectTags(expected, tag._children);
11040 }
11041 }
11042 void _validateNode(ht.XmlNode node) {
11043 if (node.beginToken == null) {
11044 _errors.add("No begin token for ${node.runtimeType}");
11045 }
11046 if (node.endToken == null) {
11047 _errors.add("No end token for ${node.runtimeType}");
11048 }
11049 int nodeStart = node.offset;
11050 int nodeLength = node.length;
11051 if (nodeStart < 0 || nodeLength < 0) {
11052 _errors.add("No source info for ${node.runtimeType}");
11053 }
11054 ht.XmlNode parent = node.parent;
11055 if (parent != null) {
11056 int nodeEnd = nodeStart + nodeLength;
11057 int parentStart = parent.offset;
11058 int parentEnd = parentStart + parent.length;
11059 if (nodeStart < parentStart) {
11060 _errors.add(
11061 "Invalid source start ($nodeStart) for ${node.runtimeType} inside ${ parent.runtimeType} ($parentStart)");
11062 }
11063 if (nodeEnd > parentEnd) {
11064 _errors.add(
11065 "Invalid source end ($nodeEnd) for ${node.runtimeType} inside ${pare nt.runtimeType} ($parentStart)");
11066 }
11067 }
11068 }
11069 }
11070
11071
11072 class XmlValidator_Attributes {
11073 final List<String> _keyValuePairs;
11074 XmlValidator_Attributes([this._keyValuePairs = StringUtilities.EMPTY_ARRAY]);
11075 }
11076
11077
11078 class XmlValidator_Tag {
11079 static const List<XmlValidator_Tag> EMPTY_LIST = const <XmlValidator_Tag>[];
11080 final String _tag;
11081 final XmlValidator_Attributes _attributes;
11082 final String _content;
11083 final List<XmlValidator_Tag> _children;
11084 XmlValidator_Tag(this._tag, this._attributes, this._content, [this._children =
11085 EMPTY_LIST]);
11086 }
11087
11088
11089 class _AngularTest_findElement extends GeneralizingElementVisitor<Object> {
11090 final ElementKind kind;
11091
11092 final String name;
11093
11094 Element result;
11095
11096 _AngularTest_findElement(this.kind, this.name);
11097
11098 @override
11099 Object visitElement(Element element) {
11100 if ((kind == null || element.kind == kind) && name == element.name) {
11101 result = element;
11102 }
11103 return super.visitElement(element);
11104 }
11105 }
11106
11107
11108 class _ExpectedScript {
11109 String _expectedExternalScriptName;
11110 HtmlUnitBuilderTest_ExpectedLibrary _expectedLibrary;
11111 _ExpectedScript.con1(HtmlUnitBuilderTest_ExpectedLibrary expectedLibrary) {
11112 this._expectedExternalScriptName = null;
11113 this._expectedLibrary = expectedLibrary;
11114 }
11115 _ExpectedScript.con2(String expectedExternalScriptPath) {
11116 this._expectedExternalScriptName = expectedExternalScriptPath;
11117 this._expectedLibrary = null;
11118 }
11119 void _validate(int scriptIndex, HtmlScriptElement script) {
11120 if (_expectedLibrary != null) {
11121 _validateEmbedded(scriptIndex, script);
11122 } else {
11123 _validateExternal(scriptIndex, script);
11124 }
11125 }
11126 void _validateEmbedded(int scriptIndex, HtmlScriptElement script) {
11127 if (script is! EmbeddedHtmlScriptElementImpl) {
11128 fail(
11129 "Expected script $scriptIndex to be embedded, but found ${script != nu ll ? script.runtimeType : "null"}");
11130 }
11131 EmbeddedHtmlScriptElementImpl embeddedScript =
11132 script as EmbeddedHtmlScriptElementImpl;
11133 _expectedLibrary._validate(scriptIndex, embeddedScript);
11134 }
11135 void _validateExternal(int scriptIndex, HtmlScriptElement script) {
11136 if (script is! ExternalHtmlScriptElementImpl) {
11137 fail(
11138 "Expected script $scriptIndex to be external with src=$_expectedExtern alScriptName but found ${script != null ? script.runtimeType : "null"}");
11139 }
11140 ExternalHtmlScriptElementImpl externalScript =
11141 script as ExternalHtmlScriptElementImpl;
11142 Source scriptSource = externalScript.scriptSource;
11143 if (_expectedExternalScriptName == null) {
11144 expect(scriptSource, isNull, reason: "script $scriptIndex");
11145 } else {
11146 expect(scriptSource, isNotNull, reason: "script $scriptIndex");
11147 String actualExternalScriptName = scriptSource.shortName;
11148 expect(
11149 actualExternalScriptName,
11150 _expectedExternalScriptName,
11151 reason: "script $scriptIndex");
11152 }
11153 }
11154 }
OLDNEW
« no previous file with comments | « pkg/analyzer/lib/src/generated/sdk_io.dart ('k') | pkg/analyzer/test/generated/all_the_rest_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698