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

Side by Side Diff: packages/analyzer/test/generated/all_the_rest_test.dart

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

Powered by Google App Engine
This is Rietveld 408576698