diff --git a/tests/corelib/corelib.status b/tests/corelib/corelib.status new file mode 100644 index 00000000000..6eb2bb2c69c --- /dev/null +++ b/tests/corelib/corelib.status @@ -0,0 +1,40 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +prefix corelib + +[ $arch == ia32 || $arch == dartium ] +UnicodeTest: Fail # Bug 5163868 + + +[ $arch == ia32 ] + + +[ $arch == dartc || $arch == chromium ] +ConstListLiteralTest: Fail # Bug 3341367 +CoreRuntimeTypesTest: Fail # Bug 5196164 +StringTest: Fail # Bug 5196164 + + +[ $arch == chromium || $arch == dartium ] +# Bug 5293748 +SortTest: Skip +ListSortTest: Skip + +[ $arch == chromium ] +# Bug 5275717 +MapTest: Fail +SplayTreeTest: Fail +QueueTest: Fail +ExceptionImplementationTest: Fail + + +[ $arch == x64 ] +*: Skip + +[ $arch == simarm ] +*: Skip + +[ $arch == arm ] +*: Skip diff --git a/tests/corelib/src/CollectionFromTest.dart b/tests/corelib/src/CollectionFromTest.dart new file mode 100644 index 00000000000..fc4511f4256 --- /dev/null +++ b/tests/corelib/src/CollectionFromTest.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class CollectionFromTest { + static testMain() { + var set = new Set(); + set.add(1); + set.add(2); + set.add(4); + check(set, new List.from(set)); + check(set, new List.from(set)); + check(set, new Queue.from(set)); + check(set, new Queue.from(set)); + check(set, new Set.from(set)); + check(set, new Set.from(set)); + } + + + static check(Collection initial, Collection other) { + Expect.equals(3, initial.length); + Expect.equals(initial.length, other.length); + + int initialSum = 0; + int otherSum = 0; + + initial.forEach(void f(e) { initialSum += e; }); + other.forEach(void f(e) { otherSum += e; }); + Expect.equals(4 + 2 + 1, otherSum); + Expect.equals(otherSum, initialSum); + } +} + +main() { + CollectionFromTest.testMain(); +} diff --git a/tests/corelib/src/ConstListLiteralTest.dart b/tests/corelib/src/ConstListLiteralTest.dart new file mode 100644 index 00000000000..c7ba4419f27 --- /dev/null +++ b/tests/corelib/src/ConstListLiteralTest.dart @@ -0,0 +1,69 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that a final list literal is not expandable nor modifiable. + +class ConstListLiteralTest { + + static void testMain() { + var list = const [4, 2, 3]; + Expect.equals(3, list.length); + + var exception = null; + try { + list.add(4); + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(3, list.length); + exception = null; + + exception = null; + try { + list.addAll([4, 5]); + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(3, list.length); + + exception = null; + try { + list[0] = 0; + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(3, list.length); + + exception = null; + try { + list.sort((a, b) => a < b); + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(3, list.length); + Expect.equals(4, list[0]); + Expect.equals(2, list[1]); + Expect.equals(3, list[2]); + + exception = null; + try { + list.copyFrom([1], 0, 0, 1); + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(3, list.length); + Expect.equals(4, list[0]); + Expect.equals(2, list[1]); + Expect.equals(3, list[2]); + } +} + +main() { + ConstListLiteralTest.testMain(); +} diff --git a/tests/corelib/src/CoreRuntimeTypesTest.dart b/tests/corelib/src/CoreRuntimeTypesTest.dart new file mode 100644 index 00000000000..764f7a888ac --- /dev/null +++ b/tests/corelib/src/CoreRuntimeTypesTest.dart @@ -0,0 +1,297 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/** + * A test of simple runtime behavior on numbers, strings and lists with + * a focus on both correct behavior and runtime errors. + * + * This file is written to use minimal type declarations to match a + * typical dynamic language coding style. + */ +class CoreRuntimeTypesTest { + static testMain() { + testBooleanOperators(); + testRationalOperators(); + testIntegerOperators(); + testOperatorErrors(); + testRationalMethods(); + testIntegerMethods(); + testStringOperators(); + testStringMethods(); + testListOperators(); + testListMethods(); + testMapOperators(); + testMapMethods(); + testLiterals(); + + // TODO(ngeoffray): re-enable this test once static const fields + // in interfaces are correctly emitted (b/4336711). + // testDateMethods(); + } + + static assertEquals(a, b) { + Expect.equals(b, a); + } + + static assertListEquals(List a, List b) { + Expect.equals(b.length, a.length); + for (int i = 0; i < a.length; i++) { + Expect.equals(b[i], a[i]); + } + } + + static assertListContains(List a, List b) { + a.sort((x, y) => x.compareTo(y)); + b.sort((x, y) => x.compareTo(y)); + assertListEquals(a, b); + } + + static assertTypeError(void f()) { + try { + f(); + } catch (var exception) { + Expect.equals(true, (exception is TypeError) || + (exception is NoSuchMethodException) || + (exception is NullPointerException) || + (exception is IllegalArgumentException)); + return; + } + Expect.equals(true, false); + } + + static testBooleanOperators() { + var x = true, y = false; + assertEquals(x, true); + assertEquals(y, false); + assertEquals(x, !y); + assertEquals(!x, y); + } + + + static testRationalOperators() { + var x = 10, y = 20; + assertEquals(x + y, 30); + assertEquals(x - y, -10); + assertEquals(x * y, 200); + assertEquals(x / y, 0.5); + assertEquals(x ~/ y, 0); + assertEquals(x % y, 10); + } + + static testIntegerOperators() { + var x = 18, y = 17; + assertEquals(x | y, 19); + assertEquals(x & y, 16); + assertEquals(x ^ y, 3); + assertEquals(2 >> 1, 1); + assertEquals(1 << 1, 2); + } + + static testOperatorErrors() { + var objs = [1, '2', [3], null, true, new Map()]; + for (var i=0; i < objs.length; i++) { + for (var j=i+1; j < objs.length; j++) { + testBinaryOperatorErrors(objs[i], objs[j]); + testBinaryOperatorErrors(objs[j], objs[i]); + } + if (objs[i] != 1) { + testUnaryOperatorErrors(objs[i]); + } + } + } + + static testBinaryOperatorErrors(x, y) { + assertTypeError(() { x - y;}); + assertTypeError(() { x * y;}); + assertTypeError(() { x / y;}); + assertTypeError(() { x | y;}); + assertTypeError(() { x ^ y;}); + assertTypeError(() { x & y;}); + assertTypeError(() { x << y;}); + assertTypeError(() { x >> y;}); + assertTypeError(() { x >>> y;}); + assertTypeError(() { x ~/ y;}); + assertTypeError(() { x % y;}); + + testComparisonOperatorErrors(x, y); + } + + static testComparisonOperatorErrors(x, y) { + assertEquals(x == y, false); + assertEquals(x != y, true); + assertTypeError(() { x < y; }); + assertTypeError(() { x <= y; }); + assertTypeError(() { x > y; }); + assertTypeError(() { x >= y; }); + } + + static testUnaryOperatorErrors(x) { + // TODO(jimhug): Add guard for 'is num' when 'is' is working + assertTypeError(() { ~x;}); + assertTypeError(() { -x;}); + // TODO(jimhug): Add check for !x as an error when x is not a bool + } + + static testRationalMethods() { + var x = 10.6; + assertEquals(x.abs(), 10.6); + assertEquals((-x).abs(), 10.6); + assertEquals(x.round(), 11); + assertEquals(x.floor(), 10); + assertEquals(x.ceil(), 11); + } + + // TODO(jimhug): Determine correct behavior for mixing ints and floats. + static testIntegerMethods() { + var y = 9; + assertEquals(y.isEven(), false); + assertEquals(y.isOdd(), true); + assertEquals(y.toRadixString(2), '1001'); + assertEquals(y.toRadixString(3), '100'); + assertEquals(y.toRadixString(16), '9'); + assertEquals((0).toRadixString(16), '0'); + try { + y.toRadixString(0); + Expect.fail("Illegal radix 0 accepted."); + } catch (var e) { } + try { + y.toRadixString(-1); + Expect.fail("Illegal radix -1 accepted."); + } catch (var e) { } + } + + static testStringOperators() { + var s = "abcdef"; + assertEquals(s, "abcdef"); + assertEquals(s.charCodeAt(0), 97); + assertEquals(s[0], 'a'); + assertEquals(s.length, 6); + assertTypeError(() { s[null]; }); + assertTypeError(() { s['hello']; }); + assertTypeError(() { s[0] = 'x'; }); + } + + // TODO(jimhug): Fill out full set of string methods. + static testStringMethods() { + var s = "abcdef"; + assertEquals(s.isEmpty(), false); + assertEquals(s.startsWith("abc"), true); + assertEquals(s.endsWith("def"), true); + assertEquals(s.startsWith("aa"), false); + assertEquals(s.endsWith("ff"), false); + assertEquals(s.contains('cd', 0), true); + assertEquals(s.contains('cd', 2), true); + assertEquals(s.contains('cd', 3), false); + assertEquals(s.indexOf('cd', 2), 2); + assertEquals(s.indexOf('cd', 3), -1); + + assertTypeError(() { s.startsWith(1); }); + assertTypeError(() { s.endsWith(1); }); + } + + static testListOperators() { + var a = [1,2,3,4]; + assertEquals(a[0], 1); + assertTypeError(() { a['0']; }); + a[0] = 42; + assertEquals(a[0], 42); + assertTypeError(() { a['0'] = 99; }); + assertEquals(a.length, 4); + } + + // TODO(jimhug): Fill out full set of list methods. + static testListMethods() { + var a = [1,2,3,4]; + assertEquals(a.isEmpty(), false); + assertEquals(a.length, 4); + var exception = null; + a.clear(); + assertEquals(a.length, 0); + } + + static testMapOperators() { + var d = new Map(); + d['a'] = 1; + d['b'] = 2; + assertEquals(d['a'], 1); + assertEquals(d['b'], 2); + assertEquals(d['c'], null); + } + + static testMapMethods() { + var d = new Map(); + d['a'] = 1; + d['b'] = 2; + assertEquals(d.containsValue(2), true); + assertEquals(d.containsValue(3), false); + assertEquals(d.containsKey('a'), true); + assertEquals(d.containsKey('c'), false); + assertEquals(d.getKeys().length, 2); + assertEquals(d.getValues().length, 2); + + assertEquals(d.remove('c'), null); + assertEquals(d.remove('b'), 2); + assertListEquals(d.getKeys(), ['a']); + assertListEquals(d.getValues(), [1]); + + d['c'] = 3; + d['f'] = 4; + assertEquals(d.getKeys().length, 3); + assertEquals(d.getValues().length, 3); + assertListContains(d.getKeys(), ['a', 'c', 'f']); + assertListContains(d.getValues(), [1, 3, 4]); + + var count = 0; + d.forEach((key, value) { + count++; + assertEquals(value, d[key]); + }); + assertEquals(count, 3); + + d = { 'a': 1, 'b': 2 }; + assertEquals(d.containsValue(2), true); + assertEquals(d.containsValue(3), false); + assertEquals(d.containsKey('a'), true); + assertEquals(d.containsKey('c'), false); + assertEquals(d.getKeys().length, 2); + assertEquals(d.getValues().length, 2); + + d['g'] = null; + assertEquals(d.containsKey('g'), true); + assertEquals(d['g'], null); + } + + static testDateMethods() { + // TODO(jimhug): Switch to named constructors when available. + // Pushing this into Jan 2nd to make the year independent of timezone. + // TODO(jimhug): Pursue a better solution to TZ issues. + var msec = 115201000; + var d = new DateTime(msec); + assertEquals(d.getSeconds(), 1); + assertEquals(d.getYear(), 1970); + + d = new DateTime(); + assertEquals(d.getYear() >= 2011, true); + } + + static testLiterals() { + true.toString(); + 1.0.toString(); + .5.toString(); + 1.toString(); + if (false) { + // Depends on http://b/4198808. + null.toString(); + } + '${null}'.toString(); + '${true}'.toString(); + '${false}'.toString(); + ''.toString(); + ''.endsWith(''); + } +} + +main() { + CoreRuntimeTypesTest.testMain(); +} diff --git a/tests/corelib/src/DateTimeTest.dart b/tests/corelib/src/DateTimeTest.dart new file mode 100644 index 00000000000..ce52768ea6b --- /dev/null +++ b/tests/corelib/src/DateTimeTest.dart @@ -0,0 +1,376 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for DateTime. + +class DateTimeTest { + // Tests if the time moves eventually forward. + static void testNow() { + var t1 = new DateTime.now(); + bool timeMovedForward = false; + for (int i = 0; i < 1000000; i++) { + var t2 = new DateTime.now(); + if (t1.value < t2.value) { + timeMovedForward = true; + break; + } + } + Expect.equals(true, timeMovedForward); + } + + static void testValue() { + var dt1 = new DateTime.now(); + var value = dt1.value; + var dt2 = new DateTime.fromEpoch(value, new TimeZone.local()); + Expect.equals(value, dt2.value); + } + + static void testFarAwayDates() { + DateTime dt = + new DateTime.fromEpoch(1000000000000001, const TimeZone.utc()); + Expect.equals(33658, dt.year); + Expect.equals(9, dt.month); + Expect.equals(27, dt.day); + Expect.equals(1, dt.hours); + Expect.equals(46, dt.minutes); + Expect.equals(40, dt.seconds); + Expect.equals(1, dt.milliseconds); + Date d = dt.date; + Expect.equals(33658, d.year); + Expect.equals(9, d.month); + Expect.equals(27, d.day); + Time t = dt.time; + Expect.equals(1, t.hours); + Expect.equals(46, t.minutes); + Expect.equals(40, t.seconds); + Expect.equals(1, t.milliseconds); + dt = new DateTime.fromEpoch(-1000000000000001, const TimeZone.utc()); + Expect.equals(-29719, dt.year); + Expect.equals(4, dt.month); + Expect.equals(5, dt.day); + Expect.equals(22, dt.hours); + Expect.equals(13, dt.minutes); + Expect.equals(19, dt.seconds); + Expect.equals(999, dt.milliseconds); + d = dt.date; + Expect.equals(-29719, d.year); + Expect.equals(4, d.month); + Expect.equals(5, d.day); + t = dt.time; + Expect.equals(22, t.hours); + Expect.equals(13, t.minutes); + Expect.equals(19, t.seconds); + Expect.equals(999, t.milliseconds); + // Same with local zone. + dt = new DateTime.fromEpoch(1000000000000001, new TimeZone.local()); + Expect.equals(33658, dt.year); + Expect.equals(9, dt.month); + Expect.equals(true, dt.day == 27 || dt.day == 26); + // Not much we can test for local hours. + Expect.equals(true, dt.hours >= 0 && dt.hours < 24); + // Timezones can have offsets down to 15 minutes. + Expect.equals(true, dt.minutes % 15 == 46 % 15); + Expect.equals(40, dt.seconds); + Expect.equals(1, dt.milliseconds); + dt = new DateTime.fromEpoch(-1000000000000001, new TimeZone.local()); + Expect.equals(-29719, dt.year); + Expect.equals(4, dt.month); + Expect.equals(true, 5 == dt.day || 6 == dt.day); + // Not much we can test for local hours. + Expect.equals(true, dt.hours >= 0 && dt.hours < 24); + // Timezones can have offsets down to 15 minutes. + Expect.equals(true, dt.minutes % 15 == 13); + Expect.equals(19, dt.seconds); + Expect.equals(999, dt.milliseconds); + } + + static void testEquivalentYears() { + // All hardcoded values come from V8. This means that the values are not + // necessarily correct (see limitations of Date object in + // EcmaScript 15.9.1 and in particular 15.9.1.8/9). + DateTime dt = new DateTime.fromEpoch(-31485600000, const TimeZone.utc()); + Expect.equals(1969, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-63108000000, const TimeZone.utc()); + Expect.equals(1968, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-94644000000, const TimeZone.utc()); + Expect.equals(1967, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-126180000000, const TimeZone.utc()); + Expect.equals(1966, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-157716000000, const TimeZone.utc()); + Expect.equals(1965, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-2177402400000, const TimeZone.utc()); + Expect.equals(1901, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-5333076000000, const TimeZone.utc()); + Expect.equals(1801, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-8520285600000, const TimeZone.utc()); + Expect.equals(1700, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-14831719200000, const TimeZone.utc()); + Expect.equals(1500, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-59011408800000, const TimeZone.utc()); + Expect.equals(100, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(14, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-62011408800000, const TimeZone.utc()); + Expect.equals(4, dt.year); + Expect.equals(12, dt.month); + Expect.equals(8, dt.day); + Expect.equals(8, dt.hours); + Expect.equals(40, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(0, dt.milliseconds); + dt = new DateTime.fromEpoch(-64011408800000, const TimeZone.utc()); + Expect.equals(-59, dt.year); + Expect.equals(7, dt.month); + Expect.equals(24, dt.day); + Expect.equals(5, dt.hours); + Expect.equals(6, dt.minutes); + Expect.equals(40, dt.seconds); + Expect.equals(0, dt.milliseconds); + final int SECONDS_YEAR_2035 = 2051222400; + dt = new DateTime.fromEpoch(SECONDS_YEAR_2035 * 1000 + 1, + const TimeZone.utc()); + Expect.equals(2035, dt.year); + Expect.equals(1, dt.month); + Expect.equals(1, dt.day); + Expect.equals(0, dt.hours); + Expect.equals(0, dt.minutes); + Expect.equals(0, dt.seconds); + Expect.equals(1, dt.milliseconds); + dt = new DateTime.fromEpoch(SECONDS_YEAR_2035 * 1000 - 1, + const TimeZone.utc()); + Expect.equals(2034, dt.year); + Expect.equals(12, dt.month); + Expect.equals(31, dt.day); + Expect.equals(23, dt.hours); + Expect.equals(59, dt.minutes); + Expect.equals(59, dt.seconds); + Expect.equals(999, dt.milliseconds); + dt = new DateTime.withTimeZone(2035, 1, 1, 0, 0, 0, 1, + const TimeZone.utc()); + Expect.equals(SECONDS_YEAR_2035 * 1000 + 1, dt.value); + dt = new DateTime.withTimeZone(2034, 12, 31, 23, 59, 59, 999, + const TimeZone.utc()); + Expect.equals(SECONDS_YEAR_2035 * 1000 - 1, dt.value); + dt = new DateTime.fromEpoch(SECONDS_YEAR_2035 * 1000 + 1, + new TimeZone.local()); + Expect.equals(true, (2035 == dt.year && 1 == dt.month && 1 == dt.day) || + (2034 == dt.year && 12 == dt.month && 31 == dt.day)); + Expect.equals(0, dt.seconds); + Expect.equals(1, dt.milliseconds); + DateTime dt2 = new DateTime.fromDateAndTime(dt.date, dt.time, + new TimeZone.local()); + Expect.equals(dt.value, dt2.value); + dt = new DateTime.fromEpoch(SECONDS_YEAR_2035 * 1000 - 1, + new TimeZone.local()); + Expect.equals(true, (2035 == dt.year && 1 == dt.month && 1 == dt.day) || + (2034 == dt.year && 12 == dt.month && 31 == dt.day)); + Expect.equals(59, dt.seconds); + Expect.equals(999, dt.milliseconds); + dt2 = new DateTime.fromDateAndTime(dt.date, dt.time, new TimeZone.local()); + Expect.equals(dt.value, dt2.value); + } + + static void testUTCGetters() { + var dt = new DateTime.fromEpoch(1305140315000, const TimeZone.utc()); + Expect.equals(2011, dt.year); + Expect.equals(5, dt.month); + Expect.equals(11, dt.day); + Expect.equals(18, dt.hours); + Expect.equals(58, dt.minutes); + Expect.equals(35, dt.seconds); + Expect.equals(0, dt.milliseconds); + Expect.equals(true, const TimeZone.utc() == dt.timeZone); + Expect.equals(1305140315000, dt.value); + Date d = dt.date; + Expect.equals(2011, d.year); + Expect.equals(5, d.month); + Expect.equals(11, d.day); + Time t = dt.time; + Expect.equals(0, t.days); + Expect.equals(18, t.hours); + Expect.equals(58, t.minutes); + Expect.equals(35, t.seconds); + Expect.equals(0, t.milliseconds); + dt = new DateTime.fromEpoch(-9999999, const TimeZone.utc()); + Expect.equals(1969, dt.year); + Expect.equals(12, dt.month); + Expect.equals(31, dt.day); + Expect.equals(21, dt.hours); + Expect.equals(13, dt.minutes); + Expect.equals(20, dt.seconds); + Expect.equals(1, dt.milliseconds); + d = dt.date; + Expect.equals(1969, d.year); + Expect.equals(12, d.month); + Expect.equals(31, d.day); + t = dt.time; + Expect.equals(21, t.hours); + Expect.equals(13, t.minutes); + Expect.equals(20, t.seconds); + Expect.equals(1, t.milliseconds); + } + + static void testLocalGetters() { + var dt1 = new DateTime.fromEpoch(1305140315000, new TimeZone.local()); + var dt2 = + new DateTime.withTimeZone(dt1.year, dt1.month, dt1.day, + dt1.hours, dt1.minutes, dt1.seconds, + dt1.milliseconds, + const TimeZone.utc()); + Time zoneOffset = dt1.difference(dt2); + Expect.equals(true, zoneOffset.days == 0); + Expect.equals(true, zoneOffset.hours.abs() <= 12); + Expect.equals(dt1.year, dt2.year); + Expect.equals(dt1.month, dt2.month); + Expect.equals(true, (dt1.day - dt2.day).abs() <= 1); + Expect.equals(true, dt1.hours < 24); + // There are timezones with 0.5 or 0.25 hour offsets. + Expect.equals(true, + (dt1.minutes == dt2.minutes) || + ((dt1.minutes - dt2.minutes).abs() == 30) || + ((dt1.minutes - dt2.minutes).abs() == 15)); + Expect.equals(dt1.seconds, dt2.seconds); + Expect.equals(dt1.milliseconds, dt2.milliseconds); + } + + static void testConstructors() { + var dt1 = new DateTime.fromEpoch(1305140315000, new TimeZone.local()); + Date d = dt1.date; + Time t = dt1.time; + var dt3 = new DateTime.fromDateAndTime(d, t, null); + Expect.equals(dt1.value, dt3.value); + Expect.equals(true, dt1 == dt3); + dt3 = new DateTime.fromDateAndTime(d, t, new TimeZone.local()); + Expect.equals(dt1.value, dt3.value); + Expect.equals(true, dt1 == dt3); + dt3 = new DateTime.withTimeZone(2011, 5, 11, 18, 58, 35, 0, + const TimeZone.utc()); + Expect.equals(dt1.value, dt3.value); + Expect.equals(false, dt1 == dt3); + var dt2 = dt1.changeTimeZone(new TimeZone.local()); + dt3 = new DateTime.withTimeZone(2011, 5, dt1.day, + dt1.hours, dt1.minutes, 35, 0, + new TimeZone.local()); + Expect.equals(dt2.value, dt3.value); + Expect.equals(true, dt2 == dt3); + dt1 = new DateTime.fromEpoch(-9999999, const TimeZone.utc()); + d = dt1.date; + t = dt1.time; + dt3 = new DateTime.fromDateAndTime(d, t, const TimeZone.utc()); + Expect.equals(dt1.value, dt3.value); + } + + static void testChangeTimeZone() { + var dt1 = new DateTime.fromEpoch(1305140315000, new TimeZone.local()); + var dt2 = dt1.changeTimeZone(const TimeZone.utc()); + Expect.equals(dt1.value, dt2.value); + var dt3 = new DateTime.fromEpoch(1305140315000, const TimeZone.utc()); + Expect.equals(dt1.value, dt3.value); + Expect.equals(true, dt2.date == dt3.date); + Expect.equals(true, dt2.time == dt3.time); + var dt4 = dt3.changeTimeZone(new TimeZone.local()); + Expect.equals(true, dt1.date == dt4.date); + Expect.equals(true, dt1.time == dt4.time); + } + + static void testSubAdd() { + var dt1 = new DateTime.fromEpoch(1305140315000, const TimeZone.utc()); + var dt2 = dt1.add(const Time.duration(3 * Time.MS_PER_SECOND + 5)); + Expect.equals(true, dt1.date == dt2.date); + Expect.equals(dt1.hours, dt2.hours); + Expect.equals(dt1.minutes, dt2.minutes); + Expect.equals(dt1.seconds + 3, dt2.seconds); + Expect.equals(dt1.milliseconds + 5, dt2.milliseconds); + var dt3 = dt2.subtract(const Time.duration(3 * Time.MS_PER_SECOND + 5)); + Expect.equals(true, dt1 == dt3); + Expect.equals(false, dt1 == dt2); + } + + static void testDateStrings() { + // TODO(floitsch): Clean up the DateTime API that deals with strings. + var dt1 = new DateTime.fromString("2011-05-11 18:58:35Z"); + Expect.equals(1305140315000, dt1.value); + var str = dt1.toString(); + var dt2 = new DateTime.fromString(str); + Expect.equals(true, dt1 == dt2); + var dt3 = dt1.changeTimeZone(const TimeZone.utc()); + str = dt3.toString(); + Expect.equals("2011-05-11 18:58:35.000Z", str); + } + + static void testMain() { + testNow(); + testValue(); + testUTCGetters(); + testLocalGetters(); + testConstructors(); + testChangeTimeZone(); + testSubAdd(); + testDateStrings(); + testEquivalentYears(); + testFarAwayDates(); + } +} + +main() { + DateTimeTest.testMain(); +} diff --git a/tests/corelib/src/ExceptionImplementationTest.dart b/tests/corelib/src/ExceptionImplementationTest.dart new file mode 100644 index 00000000000..7ebf39883a8 --- /dev/null +++ b/tests/corelib/src/ExceptionImplementationTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// VMOptions=--expose_core_impl + +main() { + final msg = 1; + try { + throw new Exception(msg); + Expect.fail("Unreachable"); + } catch (Exception e) { + Expect.isTrue(e is Exception); + Expect.isTrue(e is ExceptionImplementation); + Expect.equals("Exception: $msg", e.toString()); + } +} diff --git a/tests/corelib/src/ExpressionTest.dart b/tests/corelib/src/ExpressionTest.dart new file mode 100644 index 00000000000..61d8ccc4b7f --- /dev/null +++ b/tests/corelib/src/ExpressionTest.dart @@ -0,0 +1,116 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests basic expressions. Does not attempt to validate the details of arithmetic, coercion, and +// so forth. +class ExpressionTest { + + ExpressionTest() {} + + int foo; + + static testMain() { + var test = new ExpressionTest(); + test.testBinary(); + test.testUnary(); + test.testShifts(); + test.testBitwise(); + test.testIncrement(); + test.testMangling(); + } + + testBinary() { + int x = 4, y = 2; + Expect.equals(6, x + y); + Expect.equals(2, x - y); + Expect.equals(8, x * y); + Expect.equals(2, x / y); + Expect.equals(0, x % y); + } + + testUnary() { + int x = 4, y = 2; + bool t = true, f = false; + Expect.equals(-4, -x); + Expect.equals(-5, ~x); + Expect.equals(f, !t); + } + + testShifts() { + int x = 4, y = 2; + Expect.equals(y, x >> 1); + Expect.equals(x, y << 1); + } + + testBitwise() { + int x = 4, y = 2; + Expect.equals(6, (x | y)); + Expect.equals(0, (x & y)); + Expect.equals(6, (x ^ y)); + } + + operator [](int index) { + return foo; + } + + operator []=(int index, int value) { + foo = value; + } + + testIncrement() { + int x = 4, a = x++; + Expect.equals(4, a); + Expect.equals(5, x); + Expect.equals(6, ++x); + Expect.equals(6, x++); + Expect.equals(7, x); + Expect.equals(6, --x); + Expect.equals(6, x--); + Expect.equals(5, x); + + this.foo = 0; + Expect.equals(0, this.foo++); + Expect.equals(1, this.foo); + Expect.equals(2, ++this.foo); + Expect.equals(2, this.foo); + Expect.equals(2, this.foo--); + Expect.equals(1, this.foo); + Expect.equals(0, --this.foo); + Expect.equals(0, this.foo); + + Expect.equals(0, this[0]++); + Expect.equals(1, this[0]); + Expect.equals(2, ++this[0]); + Expect.equals(2, this[0]); + Expect.equals(2, this[0]--); + Expect.equals(1, this[0]); + Expect.equals(0, --this[0]); + Expect.equals(0, this[0]); + + int $0 = 42, $1 = 87, $2 = 117; + Expect.equals(42, $0++); + Expect.equals(43, $0); + Expect.equals(44, ++$0); + Expect.equals(88, $0 += $0); + Expect.equals(87, $1++); + Expect.equals(88, $1); + Expect.equals(89, ++$1); + Expect.equals(178, ($1 += $1)); + Expect.equals(117, $2++); + Expect.equals(118, $2); + Expect.equals(119, ++$2); + } + + void testMangling() { + int $0 = 42, $1 = 87, $2 = 117; + this[0] = 0; + Expect.equals(42, (this[0] += $0)); + Expect.equals(129, (this[0] += $1)); + Expect.equals(246, (this[0] += $2)); + } +} + +main() { + ExpressionTest.testMain(); +} diff --git a/tests/corelib/src/ForInTest.dart b/tests/corelib/src/ForInTest.dart new file mode 100644 index 00000000000..ea537273bc0 --- /dev/null +++ b/tests/corelib/src/ForInTest.dart @@ -0,0 +1,95 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ForInTest { + static testMain() { + testSimple(); + testBreak(); + testContinue(); + testClosure(); + } + + static Set getSmallSet() { + Set set = new Set(); + set.add(1); + set.add(2); + set.add(4); + return set; + } + + static void testSimple() { + Set set = getSmallSet(); + int count = 0; + for (final i in set) { + count += i; + } + Expect.equals(7, count); + + count = 0; + for (var i in set) { + count += i; + } + Expect.equals(7, count); + + count = 0; + for (int i in set) { + count += i; + } + Expect.equals(7, count); + + count = 0; + for (final int i in set) { + count += i; + } + Expect.equals(7, count); + + count = 0; + int i = 0; + Expect.equals(false, set.contains(i)); // Used to test [i] after loop. + for (i in set) { + count += i; + } + Expect.equals(7, count); + // TODO(ngeoffray): We should really test that [i] is 4 with a set + // that preserves order. For now, making sure [i] is in the set + // will have to do. + Expect.equals(true, set.contains(i)); + } + + static void testBreak() { + Set set = getSmallSet(); + int count = 0; + for (final i in set) { + if (i == 4) break; + count += i; + } + Expect.equals(true, count < 4); + } + + static void testContinue() { + Set set = getSmallSet(); + int count = 0; + for (final i in set) { + if (i < 4) continue; + count += i; + } + Expect.equals(4, count); + } + + static void testClosure() { + Set set = getSmallSet(); + List closures = new List(set.length); + int index = 0; + for (var i in set) { + closures[index++] = () => i; + } + + Expect.equals(index, set.length); + Expect.equals(7, closures[0]() + closures[1]() + closures[2]()); + } +} + +main() { + ForInTest.testMain(); +} diff --git a/tests/corelib/src/HashMapTest.dart b/tests/corelib/src/HashMapTest.dart new file mode 100644 index 00000000000..af78d953e23 --- /dev/null +++ b/tests/corelib/src/HashMapTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test program for the HashMap class. + +class HashMapTest { + + static testMain() { + // TODO(srdjan/ngeoffray): Add more meaningful testing below. For now this + // is used to verify that the test script is picking up these tests. + var m = new Map(); + Expect.equals(0, m.length); + Expect.equals(true, m.isEmpty()); + m["one"] = 1; + Expect.equals(1, m.length); + Expect.equals(false, m.isEmpty()); + Expect.equals(1, m["one"]); + } +} + +main() { + HashMapTest.testMain(); +} diff --git a/tests/corelib/src/IndexOutOfRangeExceptionTest.dart b/tests/corelib/src/IndexOutOfRangeExceptionTest.dart new file mode 100644 index 00000000000..8152579df21 --- /dev/null +++ b/tests/corelib/src/IndexOutOfRangeExceptionTest.dart @@ -0,0 +1,74 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing out of range exceptions on arrays. + +class IndexOutOfRangeExceptionTest { + static testRead() { + testListRead([], 0); + testListRead([], -1); + testListRead([], 1); + + var list = [1]; + testListRead(list, -1); + testListRead(list, 1); + + list = new List(1); + testListRead(list, -1); + testListRead(list, 1); + + list = new List(); + testListRead(list, -1); + testListRead(list, 0); + testListRead(list, 1); + } + + static testWrite() { + testListWrite([], 0); + testListWrite([], -1); + testListWrite([], 1); + + var list = [1]; + testListWrite(list, -1); + testListWrite(list, 1); + + list = new List(1); + testListWrite(list, -1); + testListWrite(list, 1); + + list = new List(); + testListWrite(list, -1); + testListWrite(list, 0); + testListWrite(list, 1); + } + + static testMain() { + testRead(); + testWrite(); + } + + static testListRead(list, index) { + var exception = null; + try { + var e = list[index]; + } catch (IndexOutOfRangeException e) { + exception = e; + } + Expect.equals(true, exception != null); + } + + static testListWrite(list, index) { + var exception = null; + try { + list[index] = null; + } catch (IndexOutOfRangeException e) { + exception = e; + } + Expect.equals(true, exception != null); + } +} + +main() { + IndexOutOfRangeExceptionTest.testMain(); +} diff --git a/tests/corelib/src/LinkedHashMapTest.dart b/tests/corelib/src/LinkedHashMapTest.dart new file mode 100644 index 00000000000..60ea7179b5a --- /dev/null +++ b/tests/corelib/src/LinkedHashMapTest.dart @@ -0,0 +1,113 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for linked hash-maps. + +class LinkedHashMapTest { + static void testMain() { + Map map = new LinkedHashMap(); + map["a"] = 1; + map["b"] = 2; + map["c"] = 3; + map["d"] = 4; + map["e"] = 5; + + List keys = new List(5); + List values = new List(5); + + int index; + + clear() { + index = 0; + for (int i = 0; i < keys.length; i++) { + keys[i] = null; + values[i] = null; + } + } + + verifyKeys(List correctKeys) { + for (int i = 0; i < correctKeys.length; i++) { + Expect.equals(correctKeys[i], keys[i]); + } + } + + verifyValues(List correctValues) { + for (int i = 0; i < correctValues.length; i++) { + Expect.equals(correctValues[i], values[i]); + } + } + + testForEachMap(Object key, Object value) { + Expect.equals(map[key], value); + keys[index] = key; + values[index] = value; + index++; + } + + testForEachValue(Object v) { + values[index++] = v; + } + + testForEachKey(Object v) { + keys[index++] = v; + } + + final keysInOrder = const ["a", "b", "c", "d", "e"]; + final valuesInOrder = const [1, 2, 3, 4, 5]; + + clear(); + map.forEach(testForEachMap); + verifyKeys(keysInOrder); + verifyValues(valuesInOrder); + + clear(); + map.getKeys().forEach(testForEachKey); + verifyKeys(keysInOrder); + + clear(); + map.getValues().forEach(testForEachValue); + verifyValues(valuesInOrder); + + // Remove and then insert. + map.remove("b"); + map["b"] = 6; + final keysAfterBMove = const ["a", "c", "d", "e", "b"]; + final valuesAfterBMove = const [1, 3, 4, 5, 6]; + + + clear(); + map.forEach(testForEachMap); + verifyKeys(keysAfterBMove); + verifyValues(valuesAfterBMove); + + clear(); + map.getKeys().forEach(testForEachKey); + verifyKeys(keysAfterBMove); + + clear(); + map.getValues().forEach(testForEachValue); + verifyValues(valuesAfterBMove); + + // Update. + map["a"] = 0; + final valuesAfterAUpdate = const [0, 3, 4, 5, 6]; + + clear(); + map.forEach(testForEachMap); + verifyKeys(keysAfterBMove); + verifyValues(valuesAfterAUpdate); + + clear(); + map.getKeys().forEach(testForEachKey); + verifyKeys(keysAfterBMove); + + clear(); + map.getValues().forEach(testForEachValue); + verifyValues(valuesAfterAUpdate); + } +} + +main() { + LinkedHashMapTest.testMain(); +} diff --git a/tests/corelib/src/ListFromListTest.dart b/tests/corelib/src/ListFromListTest.dart new file mode 100644 index 00000000000..4d8e388ad91 --- /dev/null +++ b/tests/corelib/src/ListFromListTest.dart @@ -0,0 +1,87 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ListFromListTest { + + static testMain() { + var list = [1, 2, 4]; + + var sub = new List.fromList(list, 0, 3); + Expect.equals(3, sub.length); + Expect.equals(1, sub[0]); + Expect.equals(2, sub[1]); + Expect.equals(4, sub[2]); + + sub = new List.fromList(list, 1, 3); + Expect.equals(2, sub.length); + Expect.equals(2, sub[0]); + Expect.equals(4, sub[1]); + + sub = new List.fromList(list, 2, 3); + Expect.equals(1, sub.length); + Expect.equals(4, sub[0]); + + sub = new List.fromList(list, 0, 0); + Expect.equals(0, sub.length); + + sub = new List.fromList(list, 3, 3); + Expect.equals(0, sub.length); + + sub = new List.fromList(list, 0, 1); + Expect.equals(1, sub.length); + Expect.equals(1, sub[0]); + + sub = new List.fromList(list, 0, 2); + Expect.equals(2, sub.length); + Expect.equals(1, sub[0]); + Expect.equals(2, sub[1]); + + sub = new List.fromList(list, 1, 2); + Expect.equals(1, sub.length); + Expect.equals(2, sub[0]); + + sub = new List.fromList(list, -1, 2); + Expect.equals(2, sub.length); + Expect.equals(1, sub[0]); + Expect.equals(2, sub[1]); + + sub = new List.fromList(list, 1, 5); + Expect.equals(2, sub.length); + Expect.equals(2, sub[0]); + Expect.equals(4, sub[1]); + + list = []; + sub = new List.fromList(list, 1, 5); + Expect.equals(0, sub.length); + + sub = new List.fromList(list, 0, 0); + Expect.equals(0, sub.length); + + sub = new List.fromList(list, 0, 1); + Expect.equals(0, sub.length); + + // Test that the original list is unchanged after modifications + // to the list. + list = [1, 2, 4]; + sub = new List.fromList(list, 0, 3); + sub[0] = 42; + Expect.equals(1, list[0]); + Expect.equals(42, sub[0]); + + sub.add(42); + Expect.equals(4, sub.length); + Expect.equals(3, list.length); + + list.add(43); + Expect.equals(4, sub.length); + Expect.equals(4, list.length); + + Expect.equals(42, sub[3]); + Expect.equals(43, list[3]); + } +} + +main() { + ListFromListTest.testMain(); +} diff --git a/tests/corelib/src/ListIndexOfTest.dart b/tests/corelib/src/ListIndexOfTest.dart new file mode 100644 index 00000000000..ca8ab4c32d7 --- /dev/null +++ b/tests/corelib/src/ListIndexOfTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ListIndexOfTest { + static testMain() { + test(new List(5)); + var l = new List(); + l.length = 5; + test(l); + } + + static void test(List list) { + list[0] = 1; + list[1] = 2; + list[2] = 3; + list[3] = 4; + list[4] = 1; + + Expect.equals(3, list.indexOf(4, 0)); + Expect.equals(0, list.indexOf(1, 0)); + Expect.equals(4, list.lastIndexOf(1, list.length - 1)); + + Expect.equals(4, list.indexOf(1, 1)); + Expect.equals(-1, list.lastIndexOf(4, 2)); + + Expect.equals(3, list.indexOf(4, 2)); + Expect.equals(3, list.indexOf(4, -5)); + Expect.equals(-1, list.indexOf(4, 50)); + + Expect.equals(-1, list.lastIndexOf(4, 2)); + Expect.equals(-1, list.lastIndexOf(4, -5)); + Expect.equals(3, list.lastIndexOf(4, 50)); + } +} + +main() { + ListIndexOfTest.testMain(); +} diff --git a/tests/corelib/src/ListIteratorsTest.dart b/tests/corelib/src/ListIteratorsTest.dart new file mode 100644 index 00000000000..c3442b973a6 --- /dev/null +++ b/tests/corelib/src/ListIteratorsTest.dart @@ -0,0 +1,53 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ListIteratorsTest { + static void checkListIterator(List a) { + Iterator it = a.iterator(); + Expect.equals(false, it.hasNext() == a.isEmpty()); + for (int i = 0; i < a.length; i++) { + Expect.equals(true, it.hasNext()); + var elem = it.next(); + } + Expect.equals(false, it.hasNext()); + bool exceptionCaught = false; + try { + var eleme = it.next(); + } catch (NoMoreElementsException e) { + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + } + + static testMain() { + checkListIterator([]); + checkListIterator([1, 2]); + checkListIterator(new List(0)); + checkListIterator(new List(10)); + checkListIterator(new List()); + List g = new List(); + g.addAll([1, 2]); + checkListIterator(g); + + Iterator it = g.iterator(); + Expect.equals(true, it.hasNext()); + g.removeLast(); + Expect.equals(true, it.hasNext()); + g.removeLast(); + Expect.equals(false, it.hasNext()); + + g.addAll([10, 20]); + int sum = 0; + for (var elem in g) { + sum += elem; + // Iterator must realize that g has no more elements. + g.removeLast(); + } + Expect.equals(10, sum); + } +} + +main() { + ListIteratorsTest.testMain(); +} diff --git a/tests/corelib/src/ListLiteralIsGrowableTest.dart b/tests/corelib/src/ListLiteralIsGrowableTest.dart new file mode 100644 index 00000000000..5721eb72f1f --- /dev/null +++ b/tests/corelib/src/ListLiteralIsGrowableTest.dart @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + var l = []; + l.add(1); + Expect.equals(1, l.length); + Expect.equals(1, l[0]); +} diff --git a/tests/corelib/src/ListLiteralTest.dart b/tests/corelib/src/ListLiteralTest.dart new file mode 100644 index 00000000000..9a4f1bcf918 --- /dev/null +++ b/tests/corelib/src/ListLiteralTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that a list literal is expandable and modifiable. + +class ListLiteralTest { + + static void testMain() { + var list = [1, 2, 3]; + Expect.equals(3, list.length); + list.add(4); + Expect.equals(4, list.length); + list.addAll([5, 6]); + Expect.equals(6, list.length); + list[0] = 0; + Expect.equals(0, list[0]); + } +} + +main() { + ListLiteralTest.testMain(); +} diff --git a/tests/corelib/src/ListSortTest.dart b/tests/corelib/src/ListSortTest.dart new file mode 100644 index 00000000000..b861824664f --- /dev/null +++ b/tests/corelib/src/ListSortTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source("SortHelper.dart"); + +class ListSortTest { + static void testMain() { + var compare = (a, b) => a.compareTo(b); + var sort = (list) => list.sort(compare); + new SortHelper(sort, compare).run(); + + compare = (a, b) => -a.compareTo(b); + new SortHelper(sort, compare).run(); + } +} + +main() { + ListSortTest.testMain(); +} \ No newline at end of file diff --git a/tests/corelib/src/ListTest.dart b/tests/corelib/src/ListTest.dart new file mode 100644 index 00000000000..c6d944017a8 --- /dev/null +++ b/tests/corelib/src/ListTest.dart @@ -0,0 +1,107 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ListTest { + + static testMain() { + testList(); + testExpandableList(); + } + + static void expectValues(list, val1, val2, val3, val4) { + Expect.equals(true, list.length == 4); + Expect.equals(true, list.length == 4); + Expect.equals(true, !list.isEmpty()); + Expect.equals(list[0], val1); + Expect.equals(list[1], val2); + Expect.equals(list[2], val3); + Expect.equals(list[3], val4); + } + + static void testClosures(List list) { + testFilter(val) { return val == 3; } + Collection filtered = list.filter(testFilter); + Expect.equals(filtered.length, 1); + + testEvery(val) { return val != 11; } + bool test = list.every(testEvery); + Expect.equals(true, test); + + testSome(val) { return val == 1; } + test = list.some(testSome); + Expect.equals(true, test); + + testSomeFirst(val) { return val == 0; } + test = list.some(testSomeFirst); + Expect.equals(true, test); + + testSomeLast(val) { return val == (list.length - 1); } + test = list.some(testSomeLast); + Expect.equals(true, test); + } + + static void testList() { + List list = new List(4); + Expect.equals(list.length, 4); + list[0] = 4; + expectValues(list, 4, null, null, null); + String val = "fisk"; + list[1] = val; + expectValues(list, 4, val, null, null); + double d = 2.0; + list[3] = d; + expectValues(list, 4, val, null, d); + + for (int i = 0; i < list.length; i++) { + list[i] = i; + } + + for (int i = 0; i < 4; i++) { + Expect.equals(list[i], i); + } + + testClosures(list); + + var exception = null; + try { + list.clear(); + } catch (UnsupportedOperationException e) { + exception = e; + } + Expect.equals(true, exception != null); + } + + static void testExpandableList() { + List list = new List(); + Expect.equals(true, list.isEmpty()); + Expect.equals(list.length, 0); + list.add(4); + Expect.equals(1, list.length); + Expect.equals(true, !list.isEmpty()); + Expect.equals(list.length, 1); + Expect.equals(list.length, 1); + Expect.equals(list.removeLast(), 4); + + for (int i = 0; i < 10; i++) { + list.add(i); + } + + Expect.equals(list.length, 10); + for (int i = 0; i < 10; i++) { + Expect.equals(list[i], i); + } + + testClosures(list); + + Expect.equals(list.removeLast(), 9); + list.clear(); + Expect.equals(list.length, 0); + Expect.equals(list.length, 0); + Expect.equals(true, list.isEmpty()); + } +} + +main() { + ListTest.testMain(); +} diff --git a/tests/corelib/src/MapFromTest.dart b/tests/corelib/src/MapFromTest.dart new file mode 100644 index 00000000000..457021413be --- /dev/null +++ b/tests/corelib/src/MapFromTest.dart @@ -0,0 +1,77 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + testWithConstMap(); + testWithNonConstMap(); + testWithLinkedMap(); +} + +testWithConstMap() { + var map = const { 'b': 42, 'a': 43 }; + var otherMap = new Map.from(map); + Expect.isTrue(otherMap is Map); + Expect.isTrue(otherMap is HashMap); + Expect.isTrue(otherMap is !LinkedHashMap); + + Expect.equals(2, otherMap.length); + Expect.equals(2, otherMap.getKeys().length); + Expect.equals(2, otherMap.getValues().length); + + var count = (map) { + int count = 0; + map.forEach((a, b) { count += b; }); + return count; + }; + + Expect.equals(42 + 43, count(map)); + Expect.equals(count(map), count(otherMap)); +} + +testWithNonConstMap() { + var map = { 'b': 42, 'a': 43 }; + var otherMap = new Map.from(map); + Expect.isTrue(otherMap is Map); + Expect.isTrue(otherMap is HashMap); + Expect.isTrue(otherMap is !LinkedHashMap); + + Expect.equals(2, otherMap.length); + Expect.equals(2, otherMap.getKeys().length); + Expect.equals(2, otherMap.getValues().length); + + int count(map) { + int count = 0; + map.forEach((a, b) { count += b; }); + return count; + }; + + Expect.equals(42 + 43, count(map)); + Expect.equals(count(map), count(otherMap)); + + // Test that adding to the original map does not change otherMap. + map['c'] = 44; + Expect.equals(3, map.length); + Expect.equals(2, otherMap.length); + Expect.equals(2, otherMap.getKeys().length); + Expect.equals(2, otherMap.getValues().length); + + // Test that adding to otherMap does not change the original map. + otherMap['c'] = 44; + Expect.equals(3, map.length); + Expect.equals(3, otherMap.length); + Expect.equals(3, otherMap.getKeys().length); + Expect.equals(3, otherMap.getValues().length); +} + +testWithLinkedMap() { + var map = const { 'b': 1, 'a': 2, 'c': 3 }; + var otherMap = new LinkedHashMap.from(map); + Expect.isTrue(otherMap is Map); + Expect.isTrue(otherMap is HashMap); + Expect.isTrue(otherMap is LinkedHashMap); + var i = 1; + for (var val in map.getValues()) { + Expect.equals(i++, val); + } +} diff --git a/tests/corelib/src/MapTest.dart b/tests/corelib/src/MapTest.dart new file mode 100644 index 00000000000..7b491c11f0c --- /dev/null +++ b/tests/corelib/src/MapTest.dart @@ -0,0 +1,249 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// VMOptions=--expose_core_impl + +class MapTest { + + static testMain() { + test(new HashMap()); + test(new LinkedHashMap()); + test(new SplayTree()); + testLinkedHashMap(); + testMapLiteral(); + testNullValue(); + } + + static void test(Map map) { + testDeletedElement(map); + testMap(map, 1, 2, 3, 4, 5, 6, 7, 8); + map.clear(); + testMap(map, "value1", "value2", "value3", "value4", "value5", + "value6", "value7", "value8"); + } + + static void testLinkedHashMap() { + LinkedHashMap map = new LinkedHashMap(); + Expect.equals(false, map.containsKey(1)); + map[1] = 1; + map[1] = 2; + Expect.equals(1, map.length); + } + + static void testMap(Map map, key1, key2, key3, key4, key5, key6, key7, key8) { + int value1 = 10; + int value2 = 20; + int value3 = 30; + int value4 = 40; + int value5 = 50; + int value6 = 60; + int value7 = 70; + int value8 = 80; + + Expect.equals(0, map.length); + + map[key1] = value1; + Expect.equals(value1, map[key1]); + map[key1] = value2; + Expect.equals(false, map.containsKey(key2)); + Expect.equals(1, map.length); + + map[key1] = value1; + Expect.equals(value1, map[key1]); + // Add enough entries to make sure the table grows. + map[key2] = value2; + Expect.equals(value2, map[key2]); + Expect.equals(2, map.length); + map[key3] = value3; + Expect.equals(value2, map[key2]); + Expect.equals(value3, map[key3]); + map[key4] = value4; + Expect.equals(value3, map[key3]); + Expect.equals(value4, map[key4]); + map[key5] = value5; + Expect.equals(value4, map[key4]); + Expect.equals(value5, map[key5]); + map[key6] = value6; + Expect.equals(value5, map[key5]); + Expect.equals(value6, map[key6]); + map[key7] = value7; + Expect.equals(value6, map[key6]); + Expect.equals(value7, map[key7]); + map[key8] = value8; + Expect.equals(value1, map[key1]); + Expect.equals(value2, map[key2]); + Expect.equals(value3, map[key3]); + Expect.equals(value4, map[key4]); + Expect.equals(value5, map[key5]); + Expect.equals(value6, map[key6]); + Expect.equals(value7, map[key7]); + Expect.equals(value8, map[key8]); + Expect.equals(8, map.length); + + map.remove(key4); + Expect.equals(false, map.containsKey(key4)); + Expect.equals(7, map.length); + + // Test clearing the table. + map.clear(); + Expect.equals(0, map.length); + Expect.equals(false, map.containsKey(key1)); + Expect.equals(false, map.containsKey(key2)); + Expect.equals(false, map.containsKey(key3)); + Expect.equals(false, map.containsKey(key4)); + Expect.equals(false, map.containsKey(key5)); + Expect.equals(false, map.containsKey(key6)); + Expect.equals(false, map.containsKey(key7)); + Expect.equals(false, map.containsKey(key8)); + + // Test adding and removing again. + map[key1] = value1; + Expect.equals(value1, map[key1]); + Expect.equals(1, map.length); + map[key2] = value2; + Expect.equals(value2, map[key2]); + Expect.equals(2, map.length); + map[key3] = value3; + Expect.equals(value3, map[key3]); + map.remove(key3); + Expect.equals(2, map.length); + map[key4] = value4; + Expect.equals(value4, map[key4]); + map.remove(key4); + Expect.equals(2, map.length); + map[key5] = value5; + Expect.equals(value5, map[key5]); + map.remove(key5); + Expect.equals(2, map.length); + map[key6] = value6; + Expect.equals(value6, map[key6]); + map.remove(key6); + Expect.equals(2, map.length); + map[key7] = value7; + Expect.equals(value7, map[key7]); + map.remove(key7); + Expect.equals(2, map.length); + map[key8] = value8; + Expect.equals(value8, map[key8]); + map.remove(key8); + Expect.equals(2, map.length); + + Expect.equals(true, map.containsKey(key1)); + Expect.equals(true, map.containsValue(value1)); + + // Test Map.forEach. + Map other_map = new Map(); + void testForEachMap(key, value) { + other_map[key] = value; + } + map.forEach(testForEachMap); + Expect.equals(true, other_map.containsKey(key1)); + Expect.equals(true, other_map.containsKey(key2)); + Expect.equals(true, other_map.containsValue(value1)); + Expect.equals(true, other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Collection.getKeys. + void testForEachCollection(value) { + other_map[value] = value; + } + Collection keys = map.getKeys(); + keys.forEach(testForEachCollection); + Expect.equals(true, other_map.containsKey(key1)); + Expect.equals(true, other_map.containsKey(key2)); + Expect.equals(true, other_map.containsValue(key1)); + Expect.equals(true, other_map.containsValue(key2)); + Expect.equals(true, !other_map.containsKey(value1)); + Expect.equals(true, !other_map.containsKey(value2)); + Expect.equals(true, !other_map.containsValue(value1)); + Expect.equals(true, !other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Collection.getValues. + Collection values = map.getValues(); + values.forEach(testForEachCollection); + Expect.equals(true, !other_map.containsKey(key1)); + Expect.equals(true, !other_map.containsKey(key2)); + Expect.equals(true, !other_map.containsValue(key1)); + Expect.equals(true, !other_map.containsValue(key2)); + Expect.equals(true, other_map.containsKey(value1)); + Expect.equals(true, other_map.containsKey(value2)); + Expect.equals(true, other_map.containsValue(value1)); + Expect.equals(true, other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Map.putIfAbsent. + map.clear(); + Expect.equals(false, map.containsKey(key1)); + map.putIfAbsent(key1, () => 10); + Expect.equals(true, map.containsKey(key1)); + Expect.equals(10, map[key1]); + Expect.equals(10, + map.putIfAbsent(key1, () => 11)); + } + + static void testDeletedElement(Map map) { + map.clear(); + for (int i = 0; i < 100; i++) { + map[1] = 2; + Expect.equals(1, map.length); + map.remove(1); + Expect.equals(0, map.length); + } + Expect.equals(0, map.length); + } + + static void testMapLiteral() { + Map m = {"a": 1, "b" : 2, "c": 3 }; + Expect.equals(3, m.length); + int sum = 0; + m.forEach((a, b) { + sum += b; + }); + Expect.equals(6, sum); + + List values = m.getKeys(); + Expect.equals(3, values.length); + String first = values[0]; + String second = values[1]; + String third = values[2]; + String all = "${first}${second}${third}"; + Expect.equals(3, all.length); + Expect.equals(true, all.contains("a", 0)); + Expect.equals(true, all.contains("b", 0)); + Expect.equals(true, all.contains("c", 0)); + } + + static void testNullValue() { + Map m = {"a": 1, "b" : null, "c": 3 }; + + Expect.equals(null, m["b"]); + Expect.equals(true, m.containsKey("b")); + Expect.equals(3, m.length); + + m["a"] = null; + m["c"] = null; + Expect.equals(null, m["a"]); + Expect.equals(true, m.containsKey("a")); + Expect.equals(null, m["c"]); + Expect.equals(true, m.containsKey("c")); + Expect.equals(3, m.length); + + m.remove("a"); + Expect.equals(2, m.length); + Expect.equals(null, m["a"]); + Expect.equals(false, m.containsKey("a")); + } +} + +main() { + MapTest.testMain(); +} diff --git a/tests/corelib/src/MathTest.dart b/tests/corelib/src/MathTest.dart new file mode 100644 index 00000000000..f74850e02f6 --- /dev/null +++ b/tests/corelib/src/MathTest.dart @@ -0,0 +1,372 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class MathTest { + static void testConstants() { + // Source for mathematical constants is Wolfram Alpha. + Expect.equals(2.7182818284590452353602874713526624977572470936999595749669, + Math.E); + Expect.equals(2.3025850929940456840179914546843642076011014886287729760333, + Math.LN10); + Expect.equals(0.6931471805599453094172321214581765680755001343602552541206, + Math.LN2); + Expect.equals(1.4426950408889634073599246810018921374266459541529859341354, + Math.LOG2E); + Expect.equals(0.4342944819032518276511289189166050822943970058036665661144, + Math.LOG10E); + Expect.equals(3.1415926535897932384626433832795028841971693993751058209749, + Math.PI); + Expect.equals(0.7071067811865475244008443621048490392848359376884740365883, + Math.SQRT1_2); + Expect.equals(1.4142135623730950488016887242096980785696718753769480731766, + Math.SQRT2); + } + + static checkClose(double a, double b, EPSILON) { + Expect.equals(true, a - EPSILON <= b); + Expect.equals(true, b <= a + EPSILON); + } + + static void testSin() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.sin(0.0), EPSILON); + checkClose(0.0, Math.sin(Math.PI), EPSILON); + checkClose(0.0, Math.sin(2.0 * Math.PI), EPSILON); + checkClose(1.0, Math.sin(Math.PI / 2.0), EPSILON); + checkClose(-1.0, Math.sin(Math.PI * (3.0 / 2.0)), EPSILON); + } + + static void testCos() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(1.0, Math.cos(0.0), EPSILON); + checkClose(-1.0, Math.cos(Math.PI), EPSILON); + checkClose(1.0, Math.cos(2.0 * Math.PI), EPSILON); + checkClose(0.0, Math.cos(Math.PI / 2.0), EPSILON); + checkClose(0.0, Math.cos(Math.PI * (3.0 / 2.0)), EPSILON); + } + + static void testTan() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.tan(0.0), EPSILON); + checkClose(0.0, Math.tan(Math.PI), EPSILON); + checkClose(0.0, Math.tan(2.0 * Math.PI), EPSILON); + checkClose(1.0, Math.tan(Math.PI / 4.0), EPSILON); + } + + static void testAsin() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.asin(0.0), EPSILON); + checkClose(Math.PI / 2.0, Math.asin(1.0), EPSILON); + checkClose(-Math.PI / 2.0, Math.asin(-1.0), EPSILON); + } + + + static void testAcos() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.acos(1.0), EPSILON); + checkClose(Math.PI, Math.acos(-1.0), EPSILON); + checkClose(Math.PI / 2.0, Math.acos(0.0), EPSILON); + } + + static void testAtan() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.atan(0.0), EPSILON); + checkClose(Math.PI / 4.0, Math.atan(1.0), EPSILON); + checkClose(-Math.PI / 4.0, Math.atan(-1.0), EPSILON); + } + + static void testAtan2() { + // Given the imprecision of PI we can't expect better results than this. + final double EPSILON = 1e-15; + checkClose(0.0, Math.atan2(0.0, 5.0), EPSILON); + checkClose(Math.PI / 4.0, Math.atan2(2.0, 2.0), EPSILON); + checkClose(3 * Math.PI / 4.0, Math.atan2(0.5, -0.5), EPSILON); + checkClose(-3 * Math.PI / 4.0, Math.atan2(-2.5, -2.5), EPSILON); + } + + static checkVeryClose(double a, double b) { + // We find a ulp (unit in the last place) by shifting the original number + // to the right. This only works if we are not too close to infinity or if + // we work with denormals. + // We special case or 0.0, but not for infinity. + if (a == 0.0) { + final minimalDouble = 4.9406564584124654e-324; + Expect.equals(true, b.abs() <= minimalDouble); + return; + } + if (b == 0.0) { + // No need to look if they are close. Otherwise the check for 'a' above + // whould have triggered. + Expect.equals(a, b); + } + final double shiftRightBy52 = 2.220446049250313080847263336181640625e-16; + final double shiftedA = (a * shiftRightBy52).abs(); + // Compared to 'a', 'shiftedA' is now ~1-2 ulp. + + final double limitLow = a - shiftedA; + final double limitHigh = a + shiftedA; + Expect.equals(false, a == limitLow); + Expect.equals(false, a == limitHigh); + Expect.equals(true, limitLow <= b); + Expect.equals(true, b <= limitHigh); + } + + static void testSqrt() { + checkVeryClose(2.0, Math.sqrt(4.0)); + checkVeryClose(Math.SQRT2, Math.sqrt(2.0)); + checkVeryClose(Math.SQRT1_2, Math.sqrt(0.5)); + checkVeryClose(1e50, Math.sqrt(1e100)); + checkVeryClose(1.1111111061110855443054405046358901279277111935183977e56, + Math.sqrt(12345678901234e99)); + } + + static void testExp() { + checkVeryClose(Math.E, Math.exp(1.0)); + final EPSILON = 1e-15; + checkClose(10.0, Math.exp(Math.LN10), EPSILON); + checkClose(2.0, Math.exp(Math.LN2), EPSILON); + } + + static void testLog() { + // Even though E is imprecise, it is good enough to get really close to 1. + // We still provide an epsilon. + checkClose(1.0, Math.log(Math.E), 1e-16); + checkVeryClose(Math.LN10, Math.log(10.0)); + checkVeryClose(Math.LN2, Math.log(2.0)); + } + + static void testPow() { + checkVeryClose(16.0, Math.pow(4.0, 2.0)); + checkVeryClose(Math.SQRT2, Math.pow(2.0, 0.5)); + checkVeryClose(Math.SQRT1_2, Math.pow(0.5, 0.5)); + } + + static bool parseIntThrowsBadNumberFormatException(str) { + try { + Math.parseInt(str); + return false; + } catch (BadNumberFormatException e) { + return true; + } + } + + static void testParseInt() { + Expect.equals(499, Math.parseInt("499")); + Expect.equals(499, Math.parseInt("+499")); + Expect.equals(-499, Math.parseInt("-499")); + Expect.equals(499, Math.parseInt(" 499 ")); + Expect.equals(499, Math.parseInt(" +499 ")); + Expect.equals(-499, Math.parseInt(" -499 ")); + Expect.equals(0, Math.parseInt("0")); + Expect.equals(0, Math.parseInt("+0")); + Expect.equals(0, Math.parseInt("-0")); + Expect.equals(0, Math.parseInt(" 0 ")); + Expect.equals(0, Math.parseInt(" +0 ")); + Expect.equals(0, Math.parseInt(" -0 ")); + Expect.equals(0x1234567890, Math.parseInt("0x1234567890")); + Expect.equals(0x1234567890, Math.parseInt("+0x1234567890")); + Expect.equals(-0x1234567890, Math.parseInt("-0x1234567890")); + Expect.equals(0x1234567890, Math.parseInt(" 0x1234567890 ")); + Expect.equals(0x1234567890, Math.parseInt(" +0x1234567890 ")); + Expect.equals(-0x1234567890, Math.parseInt(" -0x1234567890 ")); + Expect.equals(256, Math.parseInt("0x100")); + Expect.equals(256, Math.parseInt("+0x100")); + Expect.equals(-256, Math.parseInt("-0x100")); + Expect.equals(256, Math.parseInt(" 0x100 ")); + Expect.equals(256, Math.parseInt(" +0x100 ")); + Expect.equals(-256, Math.parseInt(" -0x100 ")); + Expect.equals(0xabcdef, Math.parseInt("0xabcdef")); + Expect.equals(0xABCDEF, Math.parseInt("0xABCDEF")); + Expect.equals(0xabcdef, Math.parseInt("0xabCDEf")); + Expect.equals(-0xabcdef, Math.parseInt("-0xabcdef")); + Expect.equals(-0xABCDEF, Math.parseInt("-0xABCDEF")); + Expect.equals(0xabcdef, Math.parseInt(" 0xabcdef ")); + Expect.equals(0xABCDEF, Math.parseInt(" 0xABCDEF ")); + Expect.equals(-0xabcdef, Math.parseInt(" -0xabcdef ")); + Expect.equals(-0xABCDEF, Math.parseInt(" -0xABCDEF ")); + Expect.equals(0xabcdef, Math.parseInt("0x00000abcdef")); + Expect.equals(0xABCDEF, Math.parseInt("0x00000ABCDEF")); + Expect.equals(-0xabcdef, Math.parseInt("-0x00000abcdef")); + Expect.equals(-0xABCDEF, Math.parseInt("-0x00000ABCDEF")); + Expect.equals(0xabcdef, Math.parseInt(" 0x00000abcdef ")); + Expect.equals(0xABCDEF, Math.parseInt(" 0x00000ABCDEF ")); + Expect.equals(-0xabcdef, Math.parseInt(" -0x00000abcdef ")); + Expect.equals(-0xABCDEF, Math.parseInt(" -0x00000ABCDEF ")); + Expect.equals(10, Math.parseInt("010")); + Expect.equals(-10, Math.parseInt("-010")); + Expect.equals(10, Math.parseInt(" 010 ")); + Expect.equals(-10, Math.parseInt(" -010 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("1b")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" 1b ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" 1 b ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("1e2")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" 1e2 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("00x12")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" 00x12 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("-1b")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" -1b ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" -1 b ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("-1e2")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" -1e2 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("-00x12")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" -00x12 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" -00x12 ")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("0x0x12")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("0.1")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("0x3.1")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("5.")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("+-5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("-+5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("--5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("++5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("+ 5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("- 5")); + Expect.equals(true, parseIntThrowsBadNumberFormatException("")); + Expect.equals(true, parseIntThrowsBadNumberFormatException(" ")); + } + + static bool parseDoubleThrowsBadNumberFormatException(str) { + try { + Math.parseDouble(str); + return false; + } catch (BadNumberFormatException e) { + return true; + } + } + + static void testParseDouble() { + Expect.equals(499.0, Math.parseDouble("499")); + Expect.equals(499.0, Math.parseDouble("499.0")); + Expect.equals(499.0, Math.parseDouble("499.0")); + Expect.equals(499.0, Math.parseDouble("+499")); + Expect.equals(-499.0, Math.parseDouble("-499")); + Expect.equals(499.0, Math.parseDouble(" 499 ")); + Expect.equals(499.0, Math.parseDouble(" +499 ")); + Expect.equals(-499.0, Math.parseDouble(" -499 ")); + Expect.equals(0.0, Math.parseDouble("0")); + Expect.equals(0.0, Math.parseDouble("+0")); + Expect.equals(-0.0, Math.parseDouble("-0")); + Expect.equals(true, Math.parseDouble("-0").isNegative()); + Expect.equals(0.0, Math.parseDouble(" 0 ")); + Expect.equals(0.0, Math.parseDouble(" +0 ")); + Expect.equals(-0.0, Math.parseDouble(" -0 ")); + Expect.equals(true, Math.parseDouble(" -0 ").isNegative()); + Expect.equals(1.0 * 0x1234567890, Math.parseDouble("0x1234567890")); + Expect.equals(1.0 * 0x1234567890, Math.parseDouble("+0x1234567890")); + Expect.equals(1.0 * -0x1234567890, Math.parseDouble("-0x1234567890")); + Expect.equals(1.0 * 0x1234567890, Math.parseDouble(" 0x1234567890 ")); + Expect.equals(1.0 * 0x1234567890, Math.parseDouble(" +0x1234567890 ")); + Expect.equals(1.0 * -0x1234567890, Math.parseDouble(" -0x1234567890 ")); + Expect.equals(256.0, Math.parseDouble("0x100")); + Expect.equals(256.0, Math.parseDouble("+0x100")); + Expect.equals(-256.0, Math.parseDouble("-0x100")); + Expect.equals(256.0, Math.parseDouble(" 0x100 ")); + Expect.equals(256.0, Math.parseDouble(" +0x100 ")); + Expect.equals(-256.0, Math.parseDouble(" -0x100 ")); + Expect.equals(1.0 * 0xabcdef, Math.parseDouble("0xabcdef")); + Expect.equals(1.0 * 0xABCDEF, Math.parseDouble("0xABCDEF")); + Expect.equals(1.0 * 0xabcdef, Math.parseDouble("0xabCDEf")); + Expect.equals(1.0 * -0xabcdef, Math.parseDouble("-0xabcdef")); + Expect.equals(1.0 * -0xABCDEF, Math.parseDouble("-0xABCDEF")); + Expect.equals(1.0 * 0xabcdef, Math.parseDouble(" 0xabcdef ")); + Expect.equals(1.0 * 0xABCDEF, Math.parseDouble(" 0xABCDEF ")); + Expect.equals(1.0 * -0xabcdef, Math.parseDouble(" -0xabcdef ")); + Expect.equals(1.0 * -0xABCDEF, Math.parseDouble(" -0xABCDEF ")); + Expect.equals(1.0 * 0xabcdef, Math.parseDouble("0x00000abcdef")); + Expect.equals(1.0 * 0xABCDEF, Math.parseDouble("0x00000ABCDEF")); + Expect.equals(1.0 * -0xabcdef, Math.parseDouble("-0x00000abcdef")); + Expect.equals(1.0 * -0xABCDEF, Math.parseDouble("-0x00000ABCDEF")); + Expect.equals(1.0 * 0xabcdef, Math.parseDouble(" 0x00000abcdef ")); + Expect.equals(1.0 * 0xABCDEF, Math.parseDouble(" 0x00000ABCDEF ")); + Expect.equals(1.0 * -0xabcdef, Math.parseDouble(" -0x00000abcdef ")); + Expect.equals(1.0 * -0xABCDEF, Math.parseDouble(" -0x00000ABCDEF ")); + Expect.equals(10.0, Math.parseDouble("010")); + Expect.equals(-10.0, Math.parseDouble("-010")); + Expect.equals(10.0, Math.parseDouble(" 010 ")); + Expect.equals(-10.0, Math.parseDouble(" -010 ")); + Expect.equals(0.1, Math.parseDouble("0.1")); + Expect.equals(0.1, Math.parseDouble(" 0.1 ")); + Expect.equals(0.1, Math.parseDouble(" +0.1 ")); + Expect.equals(-0.1, Math.parseDouble(" -0.1 ")); + Expect.equals(0.1, Math.parseDouble(".1")); + Expect.equals(0.1, Math.parseDouble(" .1 ")); + Expect.equals(0.1, Math.parseDouble(" +.1 ")); + Expect.equals(-0.1, Math.parseDouble(" -.1 ")); + Expect.equals(1234567.89, Math.parseDouble("1234567.89")); + Expect.equals(1234567.89, Math.parseDouble(" 1234567.89 ")); + Expect.equals(1234567.89, Math.parseDouble(" +1234567.89 ")); + Expect.equals(-1234567.89, Math.parseDouble(" -1234567.89 ")); + Expect.equals(1234567e89, Math.parseDouble("1234567e89")); + Expect.equals(1234567e89, Math.parseDouble(" 1234567e89 ")); + Expect.equals(1234567e89, Math.parseDouble(" +1234567e89 ")); + Expect.equals(-1234567e89, Math.parseDouble(" -1234567e89 ")); + Expect.equals(1234567.89e2, Math.parseDouble("1234567.89e2")); + Expect.equals(1234567.89e2, Math.parseDouble(" 1234567.89e2 ")); + Expect.equals(1234567.89e2, Math.parseDouble(" +1234567.89e2 ")); + Expect.equals(-1234567.89e2, Math.parseDouble(" -1234567.89e2 ")); + Expect.equals(1234567.89e2, Math.parseDouble("1234567.89E2")); + Expect.equals(1234567.89e2, Math.parseDouble(" 1234567.89E2 ")); + Expect.equals(1234567.89e2, Math.parseDouble(" +1234567.89E2 ")); + Expect.equals(-1234567.89e2, Math.parseDouble(" -1234567.89E2 ")); + Expect.equals(1234567.89e-2, Math.parseDouble("1234567.89e-2")); + Expect.equals(1234567.89e-2, Math.parseDouble(" 1234567.89e-2 ")); + Expect.equals(1234567.89e-2, Math.parseDouble(" +1234567.89e-2 ")); + Expect.equals(-1234567.89e-2, Math.parseDouble(" -1234567.89e-2 ")); + // TODO(floitsch): add tests for NaN and Infinity. + Expect.equals(false, parseDoubleThrowsBadNumberFormatException("1.5")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("1b")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" 1b ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" 1 b ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" e3 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" .e3 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("00x12")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" 00x12 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("-1b")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -1b ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -1 b ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("-00x12")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -00x12 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -00x12 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("0x0x12")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("+ 1.5")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("- 1.5")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("5.")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" 5. ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" +5. ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -5. ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException("1234567.e2")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" 1234567.e2 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" +1234567.e2 ")); + Expect.equals(true, parseDoubleThrowsBadNumberFormatException(" -1234567.e2 ")); + } + + static testMain() { + testConstants(); + testSin(); + testCos(); + testTan(); + testAsin(); + testAcos(); + testAtan(); + testAtan2(); + testSqrt(); + testLog(); + testExp(); + testPow(); + testParseInt(); + testParseDouble(); + } +} + +main() { + MathTest.testMain(); +} diff --git a/tests/corelib/src/PortTest.dart b/tests/corelib/src/PortTest.dart new file mode 100644 index 00000000000..276df2c9514 --- /dev/null +++ b/tests/corelib/src/PortTest.dart @@ -0,0 +1,63 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing properties of ports. + +class PortTest { + + static void testMain() { + testHashCode(); + testEquals(); + testMap(); + } + + static void testHashCode() { + ReceivePort rp0 = new ReceivePort(); + ReceivePort rp1 = new ReceivePort(); + Expect.equals(rp0.toSendPort().hashCode(), rp0.toSendPort().hashCode()); + Expect.equals(rp1.toSendPort().hashCode(), rp1.toSendPort().hashCode()); + rp0.close(); + rp1.close(); + } + + static void testEquals() { + ReceivePort rp0 = new ReceivePort(); + ReceivePort rp1 = new ReceivePort(); + Expect.equals(rp0.toSendPort(), rp0.toSendPort()); + Expect.equals(rp1.toSendPort(), rp1.toSendPort()); + Expect.equals(false, (rp0.toSendPort() == rp1.toSendPort())); + rp0.close(); + rp1.close(); + } + + static void testMap() { + ReceivePort rp0 = new ReceivePort(); + ReceivePort rp1 = new ReceivePort(); + final map = new Map(); + map[rp0.toSendPort()] = 42; + map[rp1.toSendPort()] = 87; + Expect.equals(42, map[rp0.toSendPort()]); + Expect.equals(87, map[rp1.toSendPort()]); + + map[rp0.toSendPort()] = 99; + Expect.equals(99, map[rp0.toSendPort()]); + Expect.equals(87, map[rp1.toSendPort()]); + + map.remove(rp0.toSendPort()); + Expect.equals(false, map.containsKey(rp0.toSendPort())); + Expect.equals(87, map[rp1.toSendPort()]); + + map.remove(rp1.toSendPort()); + Expect.equals(false, map.containsKey(rp0.toSendPort())); + Expect.equals(false, map.containsKey(rp1.toSendPort())); + + rp0.close(); + rp1.close(); + } + +} + +main() { + PortTest.testMain(); +} diff --git a/tests/corelib/src/PromiseTest.dart b/tests/corelib/src/PromiseTest.dart new file mode 100644 index 00000000000..867236fb759 --- /dev/null +++ b/tests/corelib/src/PromiseTest.dart @@ -0,0 +1,721 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class PromiseTest { + + static void testMain() { + testNormalComplete(); + testFromValue(); + testNormalCompleteWithHandler(); + testNormalCompleteManyHandlers(); + testError(); + testErrorWithHandler(); + testCancel(); + testCancelWithHandler(); + testChainComplete(); + testChainError(); + testChainCancel(); + testFlatten(); + testJoinSelectSecond(); + testWaitFor1(); + testWaitForAll(); + } + + static void testNormalComplete() { + Promise a = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + + readValueThrowsException_(a); + readErrorThrowsException_(a); + a.complete(3); + Expect.equals(true, a.isDone()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(3, a.value); + Expect.equals(null, a.error); + } + + static void testFromValue() { + Promise a = new Promise.fromValue(3); + Expect.equals(true, a.isDone()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(3, a.value); + Expect.equals(null, a.error); + } + + static void testNormalCompleteWithHandler() { + Promise a = new Promise(); + Promise b = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + int afterA = null; + int afterB = null; + + // value computed after setup is done. + a.addCompleteHandler((int v) { afterA = v; }); + a.complete(3); + + // value computed before setup was done. + b.complete(4); + b.addCompleteHandler((int v) { afterB = v; }); + + Expect.equals(true, a.isDone()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(null, a.error); + Expect.equals(null, b.error); + + Expect.equals(3, a.value); + Expect.equals(4, b.value); + Expect.equals(3, afterA); + Expect.equals(4, afterB); + } + + static void testNormalCompleteManyHandlers() { + Promise a = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + int afterA1 = null; + int afterA2 = null; + int afterA3 = null; + + // value computed after setup is done. + a.addCompleteHandler((int v) { afterA1 = v; }); + a.complete(3); + a.addCompleteHandler((int v) { afterA2 = v; }); + a.addCompleteHandler((int v) { afterA3 = v; }); + + Expect.equals(true, a.isDone()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(null, a.error); + Expect.equals(3, a.value); + Expect.equals(3, afterA1); + Expect.equals(3, afterA2); + Expect.equals(3, afterA3); + } + + static void testError() { + Promise a = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + a.fail("Err"); + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(true, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals("Err", a.error); + readValueThrowsException_(a, a.error); + } + + static void testErrorWithHandler() { + Promise a = new Promise(); + Promise b = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + String afterA = null; + String afterB = null; + + // error after set up is done + a.addErrorHandler((v) { afterA = v; }); + a.fail("ErrA"); + + // error before setup is done + b.fail("ErrB"); + b.addErrorHandler((v) { afterB = v; }); + + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(true, a.hasError()); + Expect.equals(false, a.isCancelled()); + + Expect.equals(true, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(true, b.hasError()); + Expect.equals(false, b.isCancelled()); + + Expect.equals("ErrA", a.error); + Expect.equals("ErrB", b.error); + Expect.equals("ErrA", afterA); + Expect.equals("ErrB", afterB); + + readValueThrowsException_(a, a.error); + readValueThrowsException_(b, b.error); + } + + static void testCancel() { + Promise a = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + + readValueThrowsException_(a); + readErrorThrowsException_(a); + a.cancel(); + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(true, a.isCancelled()); + Expect.equals(null, a.value); + Expect.equals(null, a.error); + } + + static void testCancelWithHandler() { + Promise a = new Promise(); + Promise b = new Promise(); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + bool aCancel = false; + bool bCancel = false; + + // cancel after setup + a.addCancelHandler(() { aCancel = true; }); + a.cancel(); + + // cancel before setup is done + b.cancel(); + b.addCancelHandler(() { bCancel = true; }); + + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(true, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(true, b.isCancelled()); + Expect.equals(null, a.value); + Expect.equals(null, b.value); + Expect.equals(null, a.error); + Expect.equals(null, b.error); + Expect.equals(true, aCancel); + Expect.equals(true, bCancel); + + Promise c = new Promise(); + bool cCancel = false; + c.cancel(); + c.complete(3); + c.addCancelHandler(() { cCancel = true; }); + Expect.equals(true, cCancel); + Expect.equals(true, c.isDone()); + Expect.equals(true, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(true, c.isCancelled()); + + Promise d = new Promise(); + bool dCancel = false; + d.cancel(); + d.fail("fail"); + d.addCancelHandler(() { dCancel = true; }); + Expect.equals(true, dCancel); + Expect.equals(true, d.isDone()); + Expect.equals(false, d.hasValue()); + Expect.equals(true, d.hasError()); + Expect.equals(true, d.isCancelled()); + } + + static void testChainComplete() { + Promise a = new Promise(); + Promise b = a.then((int ares) => ares + 1); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + int resA = null; + a.addCompleteHandler((int v) { resA = v; }); + int resB = null; + b.addCompleteHandler((int v) { resB = v; }); + + a.complete(3); + + Expect.equals(true, a.isDone()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + + Expect.equals(3, a.value); + Expect.equals(4, b.value); + Expect.equals(null, a.error); + Expect.equals(null, b.error); + Expect.equals(3, resA); + Expect.equals(4, resB); + } + + static void testChainError() { + Promise a = new Promise(); + Promise b = a.then((int ares) => ares + 1); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + String errA = null; + a.addErrorHandler((e) { errA = e; }); + String errB = null; + b.addErrorHandler((e) { errB = e; }); + + a.fail("err-from-a"); + + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(true, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(true, b.hasError()); + Expect.equals(false, b.isCancelled()); + + Expect.equals("err-from-a", a.error); + Expect.equals("err-from-a", b.error); + Expect.equals("err-from-a", errA); + Expect.equals("err-from-a", errB); + + readValueThrowsException_(a, a.error); + readValueThrowsException_(b, b.error); + } + + static void testChainCancel() { + Promise a = new Promise(); + Promise b = a.then((int ares) => ares + 1); + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + bool bCancel = false; + b.addCancelHandler(() { bCancel = true; }); + bool bError = false; + b.addErrorHandler((e) { bError = true; }); + bool aCancel = false; + a.addCancelHandler(() { aCancel = true; }); + + a.cancel(); + + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(true, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(true, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(null, a.value); + Expect.equals(null, a.error); + Expect.equals("Source promise was cancelled", b.error); + readValueThrowsException_(b, b.error); + Expect.equals(false, bCancel); + Expect.equals(true, bError); + Expect.equals(true, aCancel); + } + + static void testFlatten() { + Promise a = new Promise(); + Promise> b = new Promise>(); + Promise>> c = new Promise>>(); + Promise>>> d = + new Promise>>>(); + Promise flat = d.flatten(); + + Expect.equals(false, a.isDone()); + Expect.equals(false, b.isDone()); + Expect.equals(false, c.isDone()); + Expect.equals(false, d.isDone()); + Expect.equals(false, flat.isDone()); + readValueThrowsException_(a); + readValueThrowsException_(b); + readValueThrowsException_(c); + readValueThrowsException_(d); + readValueThrowsException_(flat); + + b.complete(a); + + Expect.equals(false, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(false, c.isDone()); + Expect.equals(false, d.isDone()); + Expect.equals(false, flat.isDone()); + readValueThrowsException_(a); + Expect.equals(a, b.value); + readValueThrowsException_(c); + readValueThrowsException_(d); + readValueThrowsException_(flat); + + d.complete(c); + + Expect.equals(false, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(false, c.isDone()); + Expect.equals(true, d.isDone()); + Expect.equals(false, flat.isDone()); + readValueThrowsException_(a); + Expect.equals(a, b.value); + readValueThrowsException_(c); + Expect.equals(c, d.value); + readValueThrowsException_(flat); + + a.complete(2); + + Expect.equals(true, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(false, c.isDone()); + Expect.equals(true, d.isDone()); + Expect.equals(false, flat.isDone()); + Expect.equals(2, a.value); + Expect.equals(a, b.value); + readValueThrowsException_(c); + Expect.equals(c, d.value); + readValueThrowsException_(flat); + + c.complete(b); + + Expect.equals(true, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(true, c.isDone()); + Expect.equals(true, d.isDone()); + Expect.equals(true, flat.isDone()); + Expect.equals(2, a.value); + Expect.equals(a, b.value); + Expect.equals(b, c.value); + Expect.equals(c, d.value); + Expect.equals(2, flat.value); + } + + static void testJoinSelectSecond() { + Promise a = new Promise(); + Promise b = new Promise(); + Promise c = new Promise(); + Promise second = new Promise(); + bool first = true; + second.join([a, b, c], (p) { + if (first == true) { + first = false; + return false; + } else { + return true; + } + }); + + Expect.equals(false, a.isDone()); + Expect.equals(false, b.isDone()); + Expect.equals(false, c.isDone()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + readValueThrowsException_(c); + readErrorThrowsException_(c); + Expect.equals(false, second.isDone()); + readValueThrowsException_(second); + readErrorThrowsException_(second); + + b.complete(2); + + Expect.equals(false, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(false, c.isDone()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + Expect.equals(2, b.value); + Expect.equals(null, b.error); + readValueThrowsException_(c); + readErrorThrowsException_(c); + Expect.equals(false, second.isDone()); + readValueThrowsException_(second); + readErrorThrowsException_(second); + + c.complete(3); + + Expect.equals(true, second.isDone()); + Expect.equals(false, a.isDone()); + Expect.equals(true, b.isDone()); + Expect.equals(true, c.isDone()); + + readValueThrowsException_(a); + readErrorThrowsException_(a); + Expect.equals(2, b.value); + Expect.equals(null, b.error); + Expect.equals(3, c.value); + Expect.equals(null, c.error); + Expect.equals(3, second.value); + } + + static void testWaitFor1() { + Promise a = new Promise(); + Promise b = new Promise(); + Promise c = new Promise(); + Promise first = new Promise(); + first.waitFor([a, b, c], 1); + + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(false, c.isDone()); + Expect.equals(false, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(false, c.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + readValueThrowsException_(c); + readErrorThrowsException_(c); + Expect.equals(false, first.isDone()); + + b.complete(2); + + // a & c got cancelled + Expect.equals(true, first.isDone()); + Expect.equals(true, first.hasValue()); + Expect.equals(false, first.hasError()); + Expect.equals(false, first.isCancelled()); + Expect.equals(true, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(true, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(true, c.isDone()); + Expect.equals(false, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(true, c.isCancelled()); + + Expect.equals(null, a.value); + Expect.equals(2, b.value); + Expect.equals(null, c.value); + Expect.equals(null, a.error); + Expect.equals(null, b.error); + Expect.equals(null, c.error); + Expect.equals(2, first.value); + } + + static void testWaitForAll() { + Promise a = new Promise(); + Promise b = new Promise(); + Promise c = new Promise(); + Promise all = new Promise(); + all.waitFor([a, b, c], 3); + + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(false, b.isDone()); + Expect.equals(false, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(false, c.isDone()); + Expect.equals(false, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(false, c.isCancelled()); + Expect.equals(false, all.isDone()); + Expect.equals(false, all.hasValue()); + Expect.equals(false, all.hasError()); + Expect.equals(false, all.isCancelled()); + readValueThrowsException_(a); + readErrorThrowsException_(a); + readValueThrowsException_(b); + readErrorThrowsException_(b); + readValueThrowsException_(c); + readErrorThrowsException_(c); + readValueThrowsException_(all); + readErrorThrowsException_(all); + + b.complete(2); + + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(false, c.isDone()); + Expect.equals(false, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(false, c.isCancelled()); + Expect.equals(false, all.isDone()); + Expect.equals(false, all.hasValue()); + Expect.equals(false, all.hasError()); + Expect.equals(false, all.isCancelled()); + + readValueThrowsException_(a); + readErrorThrowsException_(a); + Expect.equals(2, b.value); + Expect.equals(null, b.error); + readValueThrowsException_(c); + readErrorThrowsException_(c); + readValueThrowsException_(all); + readErrorThrowsException_(all); + + c.complete(3); + + Expect.equals(false, a.isDone()); + Expect.equals(false, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(true, c.isDone()); + Expect.equals(true, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(false, c.isCancelled()); + Expect.equals(false, all.isDone()); + Expect.equals(false, all.hasValue()); + Expect.equals(false, all.hasError()); + Expect.equals(false, all.isCancelled()); + + readValueThrowsException_(a); + readErrorThrowsException_(a); + Expect.equals(2, b.value); + Expect.equals(null, b.error); + Expect.equals(3, c.value); + Expect.equals(null, c.error); + readValueThrowsException_(all); + readErrorThrowsException_(all); + + a.complete(1); + + Expect.equals(true, a.isDone()); + Expect.equals(true, a.hasValue()); + Expect.equals(false, a.hasError()); + Expect.equals(false, a.isCancelled()); + Expect.equals(true, b.isDone()); + Expect.equals(true, b.hasValue()); + Expect.equals(false, b.hasError()); + Expect.equals(false, b.isCancelled()); + Expect.equals(true, c.isDone()); + Expect.equals(true, c.hasValue()); + Expect.equals(false, c.hasError()); + Expect.equals(false, c.isCancelled()); + Expect.equals(true, all.isDone()); + Expect.equals(true, all.hasValue()); + Expect.equals(false, all.hasError()); + Expect.equals(false, all.isCancelled()); + + Expect.equals(1, a.value); + Expect.equals(null, a.error); + Expect.equals(2, b.value); + Expect.equals(null, b.error); + Expect.equals(3, c.value); + Expect.equals(null, c.error); + Expect.equals(1, all.value); + Expect.equals(null, all.error); + } + + static void readValueThrowsException_(Promise p, [var error = null]) { + bool errorFound = false; + try { + var x = p.value; + } catch (var e) { + errorFound = true; + if (error !== null) { + Expect.equals(true, error === e); + } + } + Expect.equals(true, errorFound); + } + + static void readErrorThrowsException_(Promise p) { + bool errorFound = false; + try { + var x = p.error; + } catch (var e) { + errorFound = true; + } + Expect.equals(true, errorFound); + } +} + +main() { + PromiseTest.testMain(); +} diff --git a/tests/corelib/src/QueueIteratorTest.dart b/tests/corelib/src/QueueIteratorTest.dart new file mode 100644 index 00000000000..59c3b83030b --- /dev/null +++ b/tests/corelib/src/QueueIteratorTest.dart @@ -0,0 +1,67 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class QueueIteratorTest { + static testMain() { + testSmallQueue(); + testLargeQueue(); + testEmptyQueue(); + } + + static void testThrows(Iterator it) { + Expect.equals(false, it.hasNext()); + var exception = null; + try { + it.next(); + } catch (NoMoreElementsException e) { + exception = e; + } + Expect.equals(true, exception != null); + } + + static int sum(int expected, Iterator it) { + int count = 0; + while (it.hasNext()) { + count += it.next(); + } + Expect.equals(expected, count); + } + + static void testSmallQueue() { + Queue queue = new Queue(); + queue.addLast(1); + queue.addLast(2); + queue.addLast(3); + + Iterator it = queue.iterator(); + Expect.equals(true, it.hasNext()); + sum(6, it); + testThrows(it); + } + + static void testLargeQueue() { + Queue queue = new Queue(); + int count = 0; + for (int i = 0; i < 100; i++) { + count += i; + queue.addLast(i); + } + Iterator it = queue.iterator(); + Expect.equals(true, it.hasNext()); + sum(count, it); + testThrows(it); + } + + static void testEmptyQueue() { + Queue queue = new Queue(); + Iterator it = queue.iterator(); + Expect.equals(false, it.hasNext()); + sum(0, it); + testThrows(it); + } +} + +main() { + QueueIteratorTest.testMain(); +} diff --git a/tests/corelib/src/QueueTest.dart b/tests/corelib/src/QueueTest.dart new file mode 100644 index 00000000000..ab93c509ced --- /dev/null +++ b/tests/corelib/src/QueueTest.dart @@ -0,0 +1,174 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--expose_core_impl + +class QueueTest { + + static testMain() { + Queue queue = new Queue(); + checkQueue(queue, 0, 0); + + queue.addFirst(1); + checkQueue(queue, 1, 1); + + queue.addLast(10); + checkQueue(queue, 2, 11); + + Expect.equals(10, queue.removeLast()); + checkQueue(queue, 1, 1); + + queue.addLast(10); + Expect.equals(1, queue.removeFirst()); + checkQueue(queue, 1, 10); + + queue.addFirst(1); + queue.addLast(100); + queue.addLast(1000); + Expect.equals(1000, queue.removeLast()); + queue.addLast(1000); + checkQueue(queue, 4, 1111); + + queue.removeFirst(); + checkQueue(queue, 3, 1110); + + bool is10(int value) { + return (value == 10); + } + + Queue other = queue.filter(is10); + checkQueue(other, 1, 10); + + Expect.equals(true, queue.some(is10)); + + bool isInstanceOfInt(int value) { + return (value is int); + } + + Expect.equals(true, queue.every(isInstanceOfInt)); + + Expect.equals(false, queue.every(is10)); + + bool is1(int value) { + return (value == 1); + } + Expect.equals(false, queue.some(is1)); + + queue.clear(); + Expect.equals(0, queue.length); + + var exception = null; + try { + queue.removeFirst(); + } catch (EmptyQueueException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(0, queue.length); + + exception = null; + try { + queue.removeLast(); + } catch (EmptyQueueException e) { + exception = e; + } + Expect.equals(true, exception != null); + Expect.equals(0, queue.length); + + queue.addFirst(1); + queue.addFirst(2); + Expect.equals(2, queue.first()); + Expect.equals(1, queue.last()); + + queue.addLast(3); + Expect.equals(3, queue.last()); + bool isGreaterThanOne(int value) { + return (value > 1); + } + + other = queue.filter(isGreaterThanOne); + checkQueue(other, 2, 5); + + testAddAll(); + } + + static void checkQueue(Queue queue, int expectedSize, int expectedSum) { + Expect.equals(expectedSize, queue.length); + int sum = 0; + void sumElements(int value) { + sum += value; + } + queue.forEach(sumElements); + Expect.equals(expectedSum, sum); + } + + static testAddAll() { + Set set = new Set.from([1, 2, 4]); + + Queue queue1 = new Queue.from(set); + Queue queue2 = new Queue(); + Queue queue3 = new Queue(); + + queue2.addAll(set); + queue3.addAll(queue1); + + Expect.equals(3, set.length); + Expect.equals(3, queue1.length); + Expect.equals(3, queue2.length); + Expect.equals(3, queue3.length); + + int sum = 0; + void f(e) { sum += e; }; + + set.forEach(f); + Expect.equals(7, sum); + sum = 0; + + queue1.forEach(f); + Expect.equals(7, sum); + sum = 0; + + queue2.forEach(f); + Expect.equals(7, sum); + sum = 0; + + queue3.forEach(f); + Expect.equals(7, sum); + sum = 0; + + set = new Set.from([]); + queue1 = new Queue.from(set); + queue2 = new Queue(); + queue3 = new Queue(); + + queue2.addAll(set); + queue3.addAll(queue1); + + Expect.equals(0, set.length); + Expect.equals(0, queue1.length); + Expect.equals(0, queue2.length); + Expect.equals(0, queue3.length); + + testQueueElements(); + } + + static testQueueElements() { + Queue queue1 = new DoubleLinkedQueue.from([1, 2, 4]); + Queue queue2 = new DoubleLinkedQueue(); + queue2.addAll(queue1); + + Expect.equals(queue1.length, queue2.length); + DoubleLinkedQueueEntry entry1 = queue1.firstEntry(); + DoubleLinkedQueueEntry entry2 = queue2.firstEntry(); + while (entry1 != null) { + Expect.equals(true, entry1 !== entry2); + entry1 = entry1.nextEntry(); + entry2 = entry2.nextEntry(); + } + Expect.equals(null, entry2); + } +} + +main() { + QueueTest.testMain(); +} diff --git a/tests/corelib/src/RegExpAllMatchesTest.dart b/tests/corelib/src/RegExpAllMatchesTest.dart new file mode 100644 index 00000000000..f6bcd6c3f07 --- /dev/null +++ b/tests/corelib/src/RegExpAllMatchesTest.dart @@ -0,0 +1,104 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.allMatches. + +class RegExpAllMatchesTest { + static testIterator() { + var matches = new RegExp("foo", "").allMatches("foo foo"); + Iterator it = matches.iterator(); + Expect.equals(true, it.hasNext()); + Expect.equals('foo', it.next().group(0)); + Expect.equals(true, it.hasNext()); + Expect.equals('foo', it.next().group(0)); + Expect.equals(false, it.hasNext()); + + // Run two iterators over the same results. + it = matches.iterator(); + Iterator it2 = matches.iterator(); + Expect.equals(true, it.hasNext()); + Expect.equals(true, it2.hasNext()); + Expect.equals('foo', it.next().group(0)); + Expect.equals('foo', it2.next().group(0)); + Expect.equals(true, it.hasNext()); + Expect.equals(true, it2.hasNext()); + Expect.equals('foo', it.next().group(0)); + Expect.equals('foo', it2.next().group(0)); + Expect.equals(false, it.hasNext()); + Expect.equals(false, it2.hasNext()); + } + + static testForEach() { + var matches = new RegExp("foo", "").allMatches("foo foo"); + var str = ""; + matches.forEach((Match m) { + str += m.group(0); + }); + Expect.equals("foofoo", str); + } + + static testFilter() { + var matches = new RegExp("foo?", "").allMatches("foo fo foo fo"); + var filtered = matches.filter((Match m) { + return m.group(0) == 'foo'; + }); + Expect.equals(2, filtered.length); + var str = ""; + for (Match m in filtered) { + str += m.group(0); + } + Expect.equals("foofoo", str); + } + + static testEvery() { + var matches = new RegExp("foo?", "").allMatches("foo fo foo fo"); + Expect.equals(true, matches.every((Match m) { + return m.group(0).startsWith("fo"); + })); + Expect.equals(false, matches.every((Match m) { + return m.group(0).startsWith("foo"); + })); + } + + static testSome() { + var matches = new RegExp("foo?", "").allMatches("foo fo foo fo"); + Expect.equals(true, matches.some((Match m) { + return m.group(0).startsWith("fo"); + })); + Expect.equals(true, matches.some((Match m) { + return m.group(0).startsWith("foo"); + })); + Expect.equals(false, matches.some((Match m) { + return m.group(0).startsWith("fooo"); + })); + } + + static testIsEmpty() { + var matches = new RegExp("foo?", "").allMatches("foo fo foo fo"); + Expect.equals(false, matches.isEmpty()); + matches = new RegExp("fooo", "").allMatches("foo fo foo fo"); + Expect.equals(true, matches.isEmpty()); + } + + static testGetCount() { + var matches = new RegExp("foo?", "").allMatches("foo fo foo fo"); + Expect.equals(4, matches.length); + matches = new RegExp("fooo", "").allMatches("foo fo foo fo"); + Expect.equals(0, matches.length); + } + + static testMain() { + testIterator(); + testForEach(); + testFilter(); + testEvery(); + testSome(); + testIsEmpty(); + testGetCount(); + } +} + +main() { + RegExpAllMatchesTest.testMain(); +} diff --git a/tests/corelib/src/RegExpFirstMatchTest.dart b/tests/corelib/src/RegExpFirstMatchTest.dart new file mode 100644 index 00000000000..29bdbe6feef --- /dev/null +++ b/tests/corelib/src/RegExpFirstMatchTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.firstMatch. + +class RegExpFirstMatchTest { + static testMain() { + Expect.equals('cat', new RegExp("(\\w+)", "").firstMatch("cat dog")[0]); + Expect.equals(null, new RegExp("foo", "").firstMatch("bar")); + } +} + +main() { + RegExpFirstMatchTest.testMain(); +} diff --git a/tests/corelib/src/RegExpGroupTest.dart b/tests/corelib/src/RegExpGroupTest.dart new file mode 100644 index 00000000000..dd9f6773386 --- /dev/null +++ b/tests/corelib/src/RegExpGroupTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.group. + +class RegExpGroupTest { + static testMain() { + var match = new RegExp("(a(b)((c|de)+))", "").firstMatch("abcde"); + Expect.equals('abcde', match.group(0)); + Expect.equals('abcde', match.group(1)); + Expect.equals('b', match.group(2)); + Expect.equals('cde', match[3]); + Expect.equals('de', match[4]); + } +} + +main() { + RegExpGroupTest.testMain(); +} diff --git a/tests/corelib/src/RegExpGroupsTest.dart b/tests/corelib/src/RegExpGroupsTest.dart new file mode 100644 index 00000000000..358bd6bd966 --- /dev/null +++ b/tests/corelib/src/RegExpGroupsTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.groups. + +class RegExpGroupsTest { + static testMain() { + var match = new RegExp("(a(b)((c|de)+))", "").firstMatch("abcde"); + var groups = match.groups([0, 4, 2, 3]); + Expect.equals('abcde', groups[0]); + Expect.equals('de', groups[1]); + Expect.equals('b', groups[2]); + Expect.equals('cde', groups[3]); + } +} + +main() { + RegExpGroupsTest.testMain(); +} diff --git a/tests/corelib/src/RegExpHasMatchTest.dart b/tests/corelib/src/RegExpHasMatchTest.dart new file mode 100644 index 00000000000..411c328fe47 --- /dev/null +++ b/tests/corelib/src/RegExpHasMatchTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.hasMatch. + +class RegExpHasMatchTest { + static testMain() { + Expect.equals(false, new RegExp("bar", "").hasMatch("foo")); + Expect.equals(true, new RegExp("bar|foo", "").hasMatch("foo")); + Expect.equals(true, new RegExp("o+", "").hasMatch("foo")); + } +} + +main() { + RegExpHasMatchTest.testMain(); +} diff --git a/tests/corelib/src/RegExpStartEndTest.dart b/tests/corelib/src/RegExpStartEndTest.dart new file mode 100644 index 00000000000..1349d7cf9d3 --- /dev/null +++ b/tests/corelib/src/RegExpStartEndTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + var matches = + new RegExp("(a(b)((c|de)+))", "").allMatches("abcde abcde abcde"); + var it = matches.iterator(); + int start = 0; + int end = 5; + while (it.hasNext()) { + Match match = it.next(); + Expect.equals(start, match.start()); + Expect.equals(end, match.end()); + start += 6; + end += 6; + } +} diff --git a/tests/corelib/src/RegExpStringMatchTest.dart b/tests/corelib/src/RegExpStringMatchTest.dart new file mode 100644 index 00000000000..130d64fc75d --- /dev/null +++ b/tests/corelib/src/RegExpStringMatchTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for RegExp.stringMatch. + +class RegExpStringMatchTest { + static testMain() { + Expect.equals('cat', new RegExp("(\\w+)", "").stringMatch("cat dog")); + Expect.equals(null, new RegExp("foo", "").stringMatch("bar")); + } +} + +main() { + RegExpStringMatchTest.testMain(); +} diff --git a/tests/corelib/src/SetIteratorTest.dart b/tests/corelib/src/SetIteratorTest.dart new file mode 100644 index 00000000000..f848d40e399 --- /dev/null +++ b/tests/corelib/src/SetIteratorTest.dart @@ -0,0 +1,149 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class FixedHashCode implements Hashable { + final int _hashCode; + const FixedHashCode(this._hashCode); + int hashCode() { return _hashCode; } +} + +class SetIteratorTest { + static testMain() { + testSmallSet(); + testLargeSet(); + testEmptySet(); + testSetWithDeletedEntries(); + testBug5116829(); + testDifferentSizes(); + testDifferentHashCodes(); + } + + static void testThrows(Iterator it) { + Expect.equals(false, it.hasNext()); + var exception = null; + try { + it.next(); + } catch (NoMoreElementsException e) { + exception = e; + } + Expect.equals(true, exception != null); + } + + static int sum(int expected, Iterator it) { + int count = 0; + while (it.hasNext()) { + count += it.next(); + } + Expect.equals(expected, count); + } + + static void testSmallSet() { + Set set = new Set(); + set.add(1); + set.add(2); + set.add(3); + + Iterator it = set.iterator(); + Expect.equals(true, it.hasNext()); + sum(6, it); + testThrows(it); + } + + static void testLargeSet() { + Set set = new Set(); + int count = 0; + for (int i = 0; i < 100; i++) { + count += i; + set.add(i); + } + Iterator it = set.iterator(); + Expect.equals(true, it.hasNext()); + sum(count, it); + testThrows(it); + } + + static void testEmptySet() { + Set set = new Set(); + Iterator it = set.iterator(); + Expect.equals(false, it.hasNext()); + sum(0, it); + testThrows(it); + } + + static void testSetWithDeletedEntries() { + Set set = new Set(); + for (int i = 0; i < 100; i++) { + set.add(i); + } + for (int i = 0; i < 100; i++) { + set.remove(i); + } + Iterator it = set.iterator(); + Expect.equals(false, it.hasNext()); + sum(0, it); + testThrows(it); + + int count = 0; + for (int i = 0; i < 100; i++) { + set.add(i); + if (i % 2 == 0) set.remove(i); + else count += i; + } + it = set.iterator(); + Expect.equals(true, it.hasNext()); + sum(count, it); + testThrows(it); + } + + static void testBug5116829() { + // During iteration we skipped slot 0 of the hashset's key list. "A" was + // hashed to slot 0 and therefore triggered the bug. + Set mystrs = new Set(); + mystrs.add("A"); + int seen = 0; + for (String elt in mystrs) { + seen++; + Expect.equals("A", elt); + } + Expect.equals(1, seen); + } + + static void testDifferentSizes() { + for (int i = 1; i < 20; i++) { + Set set = new Set(); + int sum = 0; + for (int j = 0; j < i; j++) { + set.add(j); + sum += j; + } + int count = 0; + int controlSum = 0; + for (int x in set) { + controlSum += x; + count++; + } + Expect.equals(i, count); + Expect.equals(sum, controlSum); + } + } + + static void testDifferentHashCodes() { + for (int i = -20; i < 20; i++) { + Set set = new Set(); + var element = new FixedHashCode(i); + set.add(element); + Expect.equals(1, set.length); + bool foundIt = false; + for (var x in set) { + foundIt = true; + Expect.equals(true, x === element); + } + Expect.equals(true, foundIt); + } + } +} + +main() { + SetIteratorTest.testMain(); +} diff --git a/tests/corelib/src/SetTest.dart b/tests/corelib/src/SetTest.dart new file mode 100644 index 00000000000..a623a17b7c6 --- /dev/null +++ b/tests/corelib/src/SetTest.dart @@ -0,0 +1,142 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class SetTest { + + static testMain() { + Set set = new Set(); + Expect.equals(0, set.length); + set.add(1); + Expect.equals(1, set.length); + Expect.equals(true, set.contains(1)); + + set.add(1); + Expect.equals(1, set.length); + Expect.equals(true, set.contains(1)); + + set.remove(1); + Expect.equals(0, set.length); + Expect.equals(false, set.contains(1)); + + for (int i = 0; i < 10; i++) { + set.add(i); + } + + Expect.equals(10, set.length); + for (int i = 0; i < 10; i++) { + Expect.equals(true, set.contains(i)); + } + + Expect.equals(10, set.length); + + for (int i = 10; i < 20; i++) { + Expect.equals(false, set.contains(i)); + } + + // Test Set.forEach. + int sum = 0; + testForEach(int val) { + sum += (val + 1); + } + + set.forEach(testForEach); + Expect.equals(10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1, sum); + + Expect.equals(true, set.isSubsetOf(set)); + Expect.equals(true, set.containsAll(set)); + + // Test Set.filter. + testFilter(int val) { + return val.isEven(); + } + + Set filtered = set.filter(testFilter); + Expect.equals(5, filtered.length); + + Expect.equals(true, set.contains(0)); + Expect.equals(true, set.contains(2)); + Expect.equals(true, set.contains(4)); + Expect.equals(true, set.contains(6)); + Expect.equals(true, set.contains(8)); + + sum = 0; + filtered.forEach(testForEach); + Expect.equals(1 + 3 + 5 + 7 + 9, sum); + + Expect.equals(true, set.containsAll(filtered)); + Expect.equals(true, filtered.isSubsetOf(set)); + + // Test Set.every. + testEvery(int val) { + return (val < 10); + } + + Expect.equals(true, set.every(testEvery)); + Expect.equals(true, filtered.every(testEvery)); + + filtered.add(10); + Expect.equals(false, filtered.every(testEvery)); + + // Test Set.some. + testSome(int val) { + return (val == 4); + } + + Expect.equals(true, set.some(testSome)); + Expect.equals(true, filtered.some(testSome)); + filtered.remove(4); + Expect.equals(false, filtered.some(testSome)); + + // Test Set.intersection. + Set intersection = set.intersection(filtered); + Expect.equals(true, set.contains(0)); + Expect.equals(true, set.contains(2)); + Expect.equals(true, set.contains(6)); + Expect.equals(true, set.contains(8)); + Expect.equals(false, intersection.contains(1)); + Expect.equals(false, intersection.contains(3)); + Expect.equals(false, intersection.contains(4)); + Expect.equals(false, intersection.contains(5)); + Expect.equals(false, intersection.contains(7)); + Expect.equals(false, intersection.contains(9)); + Expect.equals(false, intersection.contains(10)); + Expect.equals(4, intersection.length); + + Expect.equals(true, set.containsAll(intersection)); + Expect.equals(true, filtered.containsAll(intersection)); + Expect.equals(true, intersection.isSubsetOf(set)); + Expect.equals(true, intersection.isSubsetOf(filtered)); + + // Test Set.addAll. + List list = new List(10); + for (int i = 0; i < 10; i++) { + list[i] = i + 10; + } + set.addAll(list); + Expect.equals(20, set.length); + for (int i = 0; i < 20; i++) { + Expect.equals(true, set.contains(i)); + } + + // Test Set.removeAll + set.removeAll(list); + Expect.equals(10, set.length); + for (int i = 0; i < 10; i++) { + Expect.equals(true, set.contains(i)); + } + for (int i = 10; i < 20; i++) { + Expect.equals(false, set.contains(i)); + } + + // Test Set.clear. + set.clear(); + Expect.equals(0, set.length); + set.add(11); + Expect.equals(1, set.length); + } +} + +main() { + SetTest.testMain(); +} diff --git a/tests/corelib/src/SortHelper.dart b/tests/corelib/src/SortHelper.dart new file mode 100644 index 00000000000..59314b93ab6 --- /dev/null +++ b/tests/corelib/src/SortHelper.dart @@ -0,0 +1,162 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class SortHelper { + + SortHelper(this.sortFunction, this.compareFunction) {} + + void run() { + testSortIntLists(); + testSortDoubleLists(); + } + + void printList(List a) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < a.length; i++) { + if (i != 0) buffer.add(","); + buffer.add(a[i]); + } + print("[$buffer]"); + } + + void isSorted(List a) { + for (int i = 1; i < a.length; i++) { + if (compareFunction(a[i - 1], a[i]) > 0) { + return false; + } + } + return true; + } + + void testSortIntLists() { + List a = new List(40); + + for (int i = 0; i < a.length; i++) { + a[i] = i; + } + testSort(a); + + for (int i = 0; i < a.length; i++) { + a[a.length - i - 1] = i; + } + testSort(a); + + for (int i = 0; i < 21; i++) { + a[i] = 1; + } + for (int i = 21; i < a.length; i++) { + a[i] = 2; + } + testSort(a); + + // Same with bad pivot-choices. + for (int i = 0; i < 21; i++) { + a[i] = 1; + } + for (int i = 21; i < a.length; i++) { + a[i] = 2; + } + a[6] = 1; + a[13] = 1; + a[19] = 1; + a[25] = 1; + a[33] = 2; + testSort(a); + + for (int i = 0; i < 21; i++) { + a[i] = 2; + } + for (int i = 21; i < a.length; i++) { + a[i] = 1; + } + testSort(a); + + // Same with bad pivot-choices. + for (int i = 0; i < 21; i++) { + a[i] = 2; + } + for (int i = 21; i < a.length; i++) { + a[i] = 1; + } + a[6] = 2; + a[13] = 2; + a[19] = 2; + a[25] = 2; + a[33] = 1; + testSort(a); + + var a2 = new List(0); + testSort(a2); + + var a3 = new List(1); + a3[0] = 1; + testSort(a3); + + // -------- + // Test insertion sort. + testInsertionSort(0, 1, 2, 3); + testInsertionSort(0, 1, 3, 2); + testInsertionSort(0, 3, 2, 1); + testInsertionSort(0, 3, 1, 2); + testInsertionSort(0, 2, 1, 3); + testInsertionSort(0, 2, 3, 1); + testInsertionSort(1, 0, 2, 3); + testInsertionSort(1, 0, 3, 2); + testInsertionSort(1, 2, 3, 0); + testInsertionSort(1, 2, 0, 3); + testInsertionSort(1, 3, 2, 0); + testInsertionSort(1, 3, 0, 2); + testInsertionSort(2, 0, 1, 3); + testInsertionSort(2, 0, 3, 1); + testInsertionSort(2, 1, 3, 0); + testInsertionSort(2, 1, 0, 3); + testInsertionSort(2, 3, 1, 0); + testInsertionSort(2, 3, 0, 1); + testInsertionSort(3, 0, 1, 2); + testInsertionSort(3, 0, 2, 1); + testInsertionSort(3, 1, 2, 0); + testInsertionSort(3, 1, 0, 2); + testInsertionSort(3, 2, 1, 0); + testInsertionSort(3, 2, 0, 1); + } + + void testSort(List a) { + printList(a); + sortFunction(a); + printList(a); + bool sorted = isSorted(a); + Expect.equals(true, sorted); + print(sorted); + } + + void testInsertionSort(int i1, int i2, int i3, int i4) { + var a = new List(4); + a[0] = i1; + a[1] = i2; + a[2] = i3; + a[3] = i4; + testSort(a); + } + + void testSortDoubleLists() { + List a = new List(40); + for (int i = 0; i < a.length; i++) { + a[i] = 1.0 * i + 0.5; + } + testSort(a); + + for (int i = 0; i < a.length; i++) { + a[i] = 1.0 * (a.length - i) + 0.5; + } + testSort(a); + + for (int i = 0; i < a.length; i++) { + a[i] = 1.5; + } + testSort(a); + } + + Function sortFunction; + Function compareFunction; +} diff --git a/tests/corelib/src/SortTest.dart b/tests/corelib/src/SortTest.dart new file mode 100644 index 00000000000..db010788b52 --- /dev/null +++ b/tests/corelib/src/SortTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for sort routines. +// VMOptions=--expose_core_impl +#source("SortHelper.dart"); + +class SortTest { + + static void testMain() { + var compare = (a, b) => a.compareTo(b); + var sort = (list) => DualPivotQuicksort.sort(list, compare); + new SortHelper(sort, compare).run(); + + compare = (a, b) => -a.compareTo(b); + new SortHelper(sort, compare).run(); + } +} + +main() { + SortTest.testMain(); +} diff --git a/tests/corelib/src/SplayTreeTest.dart b/tests/corelib/src/SplayTreeTest.dart new file mode 100644 index 00000000000..85f32e19eb6 --- /dev/null +++ b/tests/corelib/src/SplayTreeTest.dart @@ -0,0 +1,30 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for Splaytrees. +// VMOptions=--expose_core_impl + +class SplayTreeTest { + + static testMain() { + SplayTree tree = new SplayTree(); + tree[1] = "first"; + tree[3] = "third"; + tree[5] = "fifth"; + tree[2] = "second"; + tree[4] = "fourth"; + + var correctSolution = ["first", "second", "third", "fourth", "fifth"]; + + tree.forEach((key, value) { + Expect.equals(true, key >= 1); + Expect.equals(true, key <= 5); + Expect.equals(value, correctSolution[key - 1]); + }); + } +} + +main() { + SplayTreeTest.testMain(); +} diff --git a/tests/corelib/src/StopWatchTest.dart b/tests/corelib/src/StopWatchTest.dart new file mode 100644 index 00000000000..2b47cba58f0 --- /dev/null +++ b/tests/corelib/src/StopWatchTest.dart @@ -0,0 +1,65 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing stopwatch support. + +class StopWatchTest { + static bool checkTicking(StopWatch sw) { + sw.start(); + for (int i = 0; i < 10000; i++) { + Math.parseInt(i.toString()); + if (sw.elapsed() > 0) { + break; + } + } + return sw.elapsed() > 0; + } + + static bool checkStopping(StopWatch sw) { + sw.stop(); + int v1 = sw.elapsed(); + Expect.isTrue(v1 > 0); // Expect a non-zero elapsed time. + StopWatch sw2 = new StopWatch(); // Used for verification. + sw2.start(); + for (int i = 0; i < 10000; i++) { + Math.parseInt(i.toString()); + int v2 = sw.elapsed(); + if (v1 != v2) { + return false; + } + v1 = v2; + } + // The test only makes sense if measureable time elapsed and elapsed time + // on the stopped StopWatch did not increase. + Expect.isTrue(sw2.elapsed() > 0); + return true; + } + + static checkRestart() { + StopWatch sw = new StopWatch(); + sw.start(); + for (int i = 0; i < 1000; i++) { + Math.parseInt(i.toString()); + } + sw.stop(); + int initial = sw.elapsed(); + sw.start(); + for (int i = 0; i < 10; i++) { + Math.parseInt(i.toString()); + } + sw.stop(); + Expect.isTrue(sw.elapsed() >= initial); + } + + static testMain() { + StopWatch sw = new StopWatch(); + Expect.isTrue(checkTicking(sw)); + Expect.isTrue(checkStopping(sw)); + checkRestart(); + } +} + +main() { + StopWatchTest.testMain(); +} diff --git a/tests/corelib/src/StringBufferTest.dart b/tests/corelib/src/StringBufferTest.dart new file mode 100644 index 00000000000..1da2960d025 --- /dev/null +++ b/tests/corelib/src/StringBufferTest.dart @@ -0,0 +1,157 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// TODO(srdjan): Move StringBuffer to visible names. + +class StringBufferTest { + static testConstructor() { + StringBuffer bf = new StringBuffer(""); + Expect.equals(true, bf.isEmpty()); + + bf = new StringBuffer("abc"); + Expect.equals(3, bf.length); + Expect.equals("abc", bf.toString()); + } + + static testAdd() { + StringBuffer bf = new StringBuffer(""); + Expect.equals(true, bf.isEmpty()); + + bf.add("a"); + Expect.equals(1, bf.length); + Expect.equals("a", bf.toString()); + + bf = new StringBuffer(""); + bf.add("a"); + bf.add("b"); + Expect.equals("ab", bf.toString()); + + bf = new StringBuffer("abc"); + bf.add("d"); + bf.add("e"); + bf.add("f"); + bf.add("g"); + bf.add("h"); + bf.add("i"); + bf.add("j"); + bf.add("k"); + bf.add("l"); + bf.add("m"); + bf.add("n"); + bf.add("o"); + bf.add("p"); + bf.add("q"); + bf.add("r"); + bf.add("s"); + bf.add("t"); + bf.add("u"); + bf.add("v"); + bf.add("w"); + bf.add("x"); + bf.add("y"); + bf.add("z"); + bf.add("\n"); + bf.add("thequickbrownfoxjumpsoverthelazydog"); + Expect.equals("abcdefghijklmnopqrstuvwxyz\n" + + "thequickbrownfoxjumpsoverthelazydog", + bf.toString()); + + bf = new StringBuffer(""); + for (int i = 0; i < 100000; i++) { + bf.add(''); + bf.add(""); + } + Expect.equals("", bf.toString()); + + Expect.equals(bf, bf.add("foo")); + } + + static testLength() { + StringBuffer bf = new StringBuffer(""); + Expect.equals(0, bf.length); + bf.add("foo"); + Expect.equals(3, bf.length); + bf.add("bar"); + Expect.equals(6, bf.length); + bf.add(""); + Expect.equals(6, bf.length); + } + + static testIsEmpty() { + StringBuffer bf = new StringBuffer(""); + Expect.equals(true, bf.isEmpty()); + bf.add("foo"); + Expect.equals(false, bf.isEmpty()); + } + + static testAddAll() { + StringBuffer bf = new StringBuffer(""); + bf.addAll(["foo", "bar", "a", "b", "c"]); + Expect.equals("foobarabc", bf.toString()); + + bf.addAll([]); + Expect.equals("foobarabc", bf.toString()); + + bf.addAll(["", "", ""]); + Expect.equals("foobarabc", bf.toString()); + + Expect.equals(bf, bf.addAll(["foo"])); + } + + static testClear() { + StringBuffer bf = new StringBuffer(""); + bf.add("foo"); + bf.clear(); + Expect.equals("", bf.toString()); + Expect.equals(0, bf.length); + + bf.add("bar"); + Expect.equals("bar", bf.toString()); + Expect.equals(3, bf.length); + bf.clear(); + Expect.equals("", bf.toString()); + Expect.equals(0, bf.length); + + Expect.equals(bf, bf.clear()); + } + + static testToString() { + StringBuffer bf = new StringBuffer(""); + Expect.equals("", bf.toString()); + + bf = new StringBuffer("foo"); + Expect.equals("foo", bf.toString()); + + bf = new StringBuffer("foo"); + bf.add("bar"); + Expect.equals("foobar", bf.toString()); + } + + static testChaining() { + StringBuffer bf = new StringBuffer(""); + StringBuffer bf2 = new StringBuffer(""); + bf2.add("bf2"); + bf.add("foo") + .add("bar") + .add(bf2) + .add(bf2) + .add("toto"); + Expect.equals("foobarbf2bf2toto", bf.toString()); + } + + static testMain() { + testToString(); + testConstructor(); + testLength(); + testIsEmpty(); + testAdd(); + testAddAll(); + testClear(); + testChaining(); + } +} + +main() { + StringBufferTest.testMain(); +} diff --git a/tests/corelib/src/StringCaseTest.dart b/tests/corelib/src/StringCaseTest.dart new file mode 100644 index 00000000000..ba2f07d88ec --- /dev/null +++ b/tests/corelib/src/StringCaseTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringCaseTest { + + static testMain() { + testLowerUpper(); + } + + static testLowerUpper() { + var a = "Stop! Smell the Roses."; + var allLower = "stop! smell the roses."; + var allUpper = "STOP! SMELL THE ROSES."; + Expect.equals(allUpper, a.toUpperCase()); + Expect.equals(allLower, a.toLowerCase()); + } +} + +main() { + StringCaseTest.testMain(); +} diff --git a/tests/corelib/src/StringFromListTest.dart b/tests/corelib/src/StringFromListTest.dart new file mode 100644 index 00000000000..acd0f5c22ee --- /dev/null +++ b/tests/corelib/src/StringFromListTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringFromListTest { + static testMain() { + Expect.equals("", new String.fromCharCodes(new List(0))); + Expect.equals("", new String.fromCharCodes([])); + Expect.equals("", new String.fromCharCodes(const [])); + Expect.equals("AB", new String.fromCharCodes([65, 66])); + Expect.equals("AB", new String.fromCharCodes(const [65, 66])); + Expect.equals("", new String.fromCharCodes(new List())); + var a = new List(); + a.add(65); + a.add(66); + Expect.equals("AB", new String.fromCharCodes(a)); + } +} + +main() { + StringFromListTest.testMain(); +} diff --git a/tests/corelib/src/StringPatternTest.dart b/tests/corelib/src/StringPatternTest.dart new file mode 100644 index 00000000000..a7e07bf63b0 --- /dev/null +++ b/tests/corelib/src/StringPatternTest.dart @@ -0,0 +1,76 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing String.allMatches. + +String str = "this is a string with hello here and hello there"; + +main() { + testNoMatch(); + testOneMatch(); + testTwoMatches(); + testEmptyPattern(); + testEmptyString(); + testEmptyPatternAndString(); +} + +testNoMatch() { + // Also tests that RegExp groups don't work. + String helloPattern = "with (hello)"; + Iterable matches = helloPattern.allMatches(str); + Expect.isFalse(matches.iterator().hasNext()); +} + +testOneMatch() { + String helloPattern = "with hello"; + Iterable matches = helloPattern.allMatches(str); + var iterator = matches.iterator(); + Match match = iterator.next(); + Expect.isFalse(iterator.hasNext()); + Expect.equals(str.indexOf('with', 0), match.start()); + Expect.equals(str.indexOf('with', 0) + helloPattern.length, match.end()); + Expect.equals(helloPattern, match.pattern); + Expect.equals(str, match.str); + Expect.equals(helloPattern, match[0]); + Expect.equals(0, match.groupCount()); +} + +testTwoMatches() { + String helloPattern = "hello"; + Iterable matches = helloPattern.allMatches(str); + + int count = 0; + int start = 0; + for (var match in matches) { + count++; + Expect.equals(str.indexOf('hello', start), match.start()); + Expect.equals( + str.indexOf('hello', start) + helloPattern.length, match.end()); + Expect.equals(helloPattern, match.pattern); + Expect.equals(str, match.str); + Expect.equals(helloPattern, match[0]); + Expect.equals(0, match.groupCount()); + start = match.end(); + } + Expect.equals(2, count); +} + +testEmptyPattern() { + String pattern = ""; + Iterable matches = pattern.allMatches(str); + Expect.isFalse(matches.iterator().hasNext()); +} + +testEmptyString() { + String pattern = "foo"; + String str = ""; + Iterable matches = pattern.allMatches(str); + Expect.isFalse(matches.iterator().hasNext()); +} + +testEmptyPatternAndString() { + String pattern = ""; + String str = ""; + Iterable matches = pattern.allMatches(str); + Expect.isFalse(matches.iterator().hasNext()); +} diff --git a/tests/corelib/src/StringReplaceTest.dart b/tests/corelib/src/StringReplaceTest.dart new file mode 100644 index 00000000000..171af371e13 --- /dev/null +++ b/tests/corelib/src/StringReplaceTest.dart @@ -0,0 +1,48 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringReplaceTest { + static testMain() { + Expect.equals( + "AtoBtoCDtoE", "AfromBtoCDtoE".replaceFirst("from", "to")); + + // Test with the replaced string at the begining. + Expect.equals( + "toABtoCDtoE", "fromABtoCDtoE".replaceFirst("from", "to")); + + // Test with the replaced string at the end. + Expect.equals( + "toABtoCDtoEto", "fromABtoCDtoEto".replaceFirst("from", "to")); + + // Test when there are no occurence of the string to replace. + Expect.equals("ABC", "ABC".replaceFirst("from", "to")); + + // Test when the string to change is the empty string. + Expect.equals("", "".replaceFirst("from", "to")); + + // Test when the string to change is a substring of the string to + // replace. + Expect.equals("fro", "fro".replaceFirst("from", "to")); + + // Test when the string to change is the replaced string. + Expect.equals("to", "from".replaceFirst("from", "to")); + + // Test when the string to change is the replacement string. + Expect.equals("to", "to".replaceFirst("from", "to")); + + // Test replacing by the empty string. + Expect.equals("", "from".replaceFirst("from", "")); + Expect.equals("AB", "AfromB".replaceFirst("from", "")); + + // Test changing the empty string. + Expect.equals("to", "".replaceFirst("", "to")); + + // Test replacing the empty string. + Expect.equals("toAtoBtoCto", "AtoBtoCto".replaceFirst("", "to")); + } +} + +main() { + StringReplaceTest.testMain(); +} diff --git a/tests/corelib/src/StringSplitTest.dart b/tests/corelib/src/StringSplitTest.dart new file mode 100644 index 00000000000..7cacc7c59e6 --- /dev/null +++ b/tests/corelib/src/StringSplitTest.dart @@ -0,0 +1,46 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringSplitTest { + static testMain() { + var list = "a b c".split(" "); + Expect.equals(3, list.length); + Expect.equals("a", list[0]); + Expect.equals("b", list[1]); + Expect.equals("c", list[2]); + + list = "adbdc".split("d"); + Expect.equals(3, list.length); + Expect.equals("a", list[0]); + Expect.equals("b", list[1]); + Expect.equals("c", list[2]); + + list = "addbddc".split("dd"); + Expect.equals(3, list.length); + Expect.equals("a", list[0]); + Expect.equals("b", list[1]); + Expect.equals("c", list[2]); + + list = "abc".split(" "); + Expect.equals(1, list.length); + Expect.equals("abc", list[0]); + + list = "abc".split(""); + Expect.equals(3, list.length); + Expect.equals("a", list[0]); + Expect.equals("b", list[1]); + Expect.equals("c", list[2]); + + list = " ".split(" "); + Expect.equals(4, list.length); + Expect.equals("", list[0]); + Expect.equals("", list[1]); + Expect.equals("", list[2]); + Expect.equals("", list[3]); + } +} + +main() { + StringSplitTest.testMain(); +} diff --git a/tests/corelib/src/StringTest.dart b/tests/corelib/src/StringTest.dart new file mode 100644 index 00000000000..62f8b816f09 --- /dev/null +++ b/tests/corelib/src/StringTest.dart @@ -0,0 +1,301 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// TODO(ngeoffray): test String methods with null arguments. +class StringTest { + + static testMain() { + testOutOfRange(); + testIllegalArgument(); + testConcat(); + testIndex(); + testCharCodeAt(); + testEquals(); + testEndsWith(); + testStartsWith(); + testIndexOf(); + testLastIndexOf(); + testContains(); + testReplaceAll(); + testCompareTo(); + testToList(); + testCharCodes(); + } + + static void testOutOfRange() { + String a = "Hello"; + bool exception_caught = false; + try { + var c = a[20]; // Throw exception. + } catch (IndexOutOfRangeException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + } + + static testIllegalArgument() { + String a = "Hello"; + bool exception_caught = false; + try { + var c = a[2.2]; // Throw exception. + Expect.equals(true, false); + } catch (IllegalArgumentException e) { + exception_caught = true; + } catch (TypeError e) { // Thrown in checked mode only. + exception_caught = true; + } + Expect.equals(true, exception_caught); + } + + static testIndex() { + String str = "string"; + for (int i = 0; i < str.length; i++) { + Expect.equals(true, str[i] is String); + Expect.equals(1, str[i].length); + } + } + + static testCharCodeAt() { + String str = "string"; + for (int i = 0; i < str.length; i++) { + Expect.equals(true, str.charCodeAt(i) is int); + } + } + + static testConcat() { + var a = "One"; + var b = "Four"; + var c = a.concat(b); + Expect.equals(7, c.length); + Expect.equals("OneFour", c); + } + + static testEquals() { + Expect.equals("str", "str"); + + Expect.equals("str", "s".concat("t").concat("r")); + Expect.equals("s".concat("t").concat("r"), "str"); + + Expect.equals(false, "str" == "s"); + Expect.equals(false, "str" == "r"); + Expect.equals(false, "str" == "st"); + Expect.equals(false, "str" == "tr"); + + Expect.equals(false, "s" == "str"); + Expect.equals(false, "r" == "str"); + Expect.equals(false, "st" == "str"); + Expect.equals(false, "tr" == "str"); + + Expect.equals(false, "" == "s"); + Expect.equals("", ""); + } + + static testEndsWith() { + Expect.equals(true, "str".endsWith("r")); + Expect.equals(true, "str".endsWith("tr")); + Expect.equals(true, "str".endsWith("str")); + + Expect.equals(false, "str".endsWith("stri")); + Expect.equals(false, "str".endsWith("t")); + Expect.equals(false, "str".endsWith("st")); + Expect.equals(false, "str".endsWith("s")); + + Expect.equals(true, "".endsWith("")); + Expect.equals(false, "".endsWith("s")); + } + + static testStartsWith() { + Expect.equals(true, "str".startsWith("s")); + Expect.equals(true, "str".startsWith("st")); + Expect.equals(true, "str".startsWith("str")); + + Expect.equals(false, "str".startsWith("stri")); + Expect.equals(false, "str".startsWith("r")); + Expect.equals(false, "str".startsWith("tr")); + Expect.equals(false, "str".startsWith("t")); + + Expect.equals(true, "".startsWith("")); + Expect.equals(false, "".startsWith("s")); + } + + static testIndexOf() { + Expect.equals(0, "str".indexOf("", 0)); + Expect.equals(0, "".indexOf("", 0)); + Expect.equals(-1, "".indexOf("a", 0)); + + Expect.equals(1, "str".indexOf("t", 0)); + Expect.equals(1, "str".indexOf("tr", 0)); + Expect.equals(0, "str".indexOf("str", 0)); + Expect.equals(0, "str".indexOf("st", 0)); + Expect.equals(0, "str".indexOf("s", 0)); + Expect.equals(2, "str".indexOf("r", 0)); + Expect.equals(-1, "str".indexOf("string", 0)); + + Expect.equals(1, "strstr".indexOf("t", 0)); + Expect.equals(1, "strstr".indexOf("tr", 0)); + Expect.equals(0, "strstr".indexOf("str", 0)); + Expect.equals(0, "strstr".indexOf("st", 0)); + Expect.equals(0, "strstr".indexOf("s", 0)); + Expect.equals(2, "strstr".indexOf("r", 0)); + Expect.equals(-1, "str".indexOf("string", 0)); + + Expect.equals(4, "strstr".indexOf("t", 2)); + Expect.equals(4, "strstr".indexOf("tr", 2)); + Expect.equals(3, "strstr".indexOf("str", 1)); + Expect.equals(3, "strstr".indexOf("str", 2)); + Expect.equals(3, "strstr".indexOf("str", 3)); + Expect.equals(3, "strstr".indexOf("st", 1)); + Expect.equals(3, "strstr".indexOf("s", 3)); + Expect.equals(5, "strstr".indexOf("r", 3)); + Expect.equals(5, "strstr".indexOf("r", 4)); + Expect.equals(5, "strstr".indexOf("r", 5)); + + String str = "hello"; + for (int i = 0; i < 10; i++) { + int result = str.indexOf("", i); + if (i > str.length) { + Expect.equals(str.length, result); + } else { + Expect.equals(i, result); + } + } + } + + static testLastIndexOf() { + Expect.equals(2, "str".lastIndexOf("", 2)); + Expect.equals(0, "".lastIndexOf("", 0)); + Expect.equals(-1, "".lastIndexOf("a", 0)); + + Expect.equals(1, "str".lastIndexOf("t", 2)); + Expect.equals(1, "str".lastIndexOf("tr", 2)); + Expect.equals(0, "str".lastIndexOf("str", 2)); + Expect.equals(0, "str".lastIndexOf("st", 2)); + Expect.equals(0, "str".lastIndexOf("s", 2)); + Expect.equals(2, "str".lastIndexOf("r", 2)); + Expect.equals(-1, "str".lastIndexOf("string", 2)); + + Expect.equals(4, "strstr".lastIndexOf("t", 5)); + Expect.equals(4, "strstr".lastIndexOf("tr", 5)); + Expect.equals(3, "strstr".lastIndexOf("str", 5)); + Expect.equals(3, "strstr".lastIndexOf("st", 5)); + Expect.equals(3, "strstr".lastIndexOf("s", 5)); + Expect.equals(5, "strstr".lastIndexOf("r", 5)); + Expect.equals(-1, "str".lastIndexOf("string", 5)); + + Expect.equals(4, "strstr".lastIndexOf("t", 5)); + Expect.equals(4, "strstr".lastIndexOf("tr", 5)); + Expect.equals(3, "strstr".lastIndexOf("str", 5)); + Expect.equals(3, "strstr".lastIndexOf("str", 5)); + Expect.equals(3, "strstr".lastIndexOf("str", 5)); + Expect.equals(3, "strstr".lastIndexOf("st", 5)); + Expect.equals(3, "strstr".lastIndexOf("s", 5)); + Expect.equals(5, "strstr".lastIndexOf("r", 5)); + Expect.equals(2, "strstr".lastIndexOf("r", 4)); + Expect.equals(2, "strstr".lastIndexOf("r", 3)); + + String str = "hello"; + for (int i = 0; i < 10; i++) { + int result = str.lastIndexOf("", i); + if (i > str.length) { + Expect.equals(str.length, result); + } else { + Expect.equals(i, result); + } + } + } + + static testContains() { + Expect.equals(true, "str".contains("s", 0)); + Expect.equals(true, "str".contains("st", 0)); + Expect.equals(true, "str".contains("str", 0)); + Expect.equals(true, "str".contains("t", 0)); + Expect.equals(true, "str".contains("r", 0)); + Expect.equals(true, "str".contains("tr", 0)); + + Expect.equals(false, "str".contains("sr", 0)); + Expect.equals(false, "str".contains("string", 0)); + + Expect.equals(true, "str".contains("", 0)); + Expect.equals(true, "".contains("", 0)); + Expect.equals(false, "".contains("s", 0)); + } + + static testReplaceAll() { + Expect.equals( + "AtoBtoCDtoE", "AfromBfromCDfromE".replaceAll("from", "to")); + + // Test with the replaced string at the begining. + Expect.equals( + "toABtoCDtoE", "fromABfromCDfromE".replaceAll("from", "to")); + + // Test with the replaced string at the end. + Expect.equals( + "toABtoCDtoEto", "fromABfromCDfromEfrom".replaceAll("from", "to")); + + // Test when there are no occurence of the string to replace. + Expect.equals("ABC", "ABC".replaceAll("from", "to")); + + // Test when the string to change is the empty string. + Expect.equals("", "".replaceAll("from", "to")); + + // Test when the string to change is a substring of the string to + // replace. + Expect.equals("fro", "fro".replaceAll("from", "to")); + + // Test when the string to change is the replaced string. + Expect.equals("to", "from".replaceAll("from", "to")); + + // Test when the string to change is the replacement string. + Expect.equals("to", "to".replaceAll("from", "to")); + + // Test replacing by the empty string. + Expect.equals("", "from".replaceAll("from", "")); + Expect.equals("AB", "AfromB".replaceAll("from", "")); + + // Test changing the empty string. + Expect.equals("to", "".replaceAll("", "to")); + + // Test replacing the empty string. + Expect.equals("toAtoBtoCto", "ABC".replaceAll("", "to")); + } + + static testCompareTo() { + Expect.equals(0, "".compareTo("")); + Expect.equals(0, "str".compareTo("str")); + Expect.equals(-1, "str".compareTo("string")); + Expect.equals(1, "string".compareTo("str")); + Expect.equals(1, "string".compareTo("")); + Expect.equals(-1, "".compareTo("string")); + } + + static testToList() { + test(str) { + var list = str.splitChars(); + Expect.equals(str.length, list.length); + for (int i = 0; i < str.length; i++) { + Expect.equals(str[i], list[i]); + } + } + test("abc"); + test(""); + test(" "); + } + + static testCharCodes() { + test(str) { + var list = str.charCodes(); + Expect.equals(str.length, list.length); + for (int i = 0; i < str.length; i++) { + Expect.equals(str.charCodeAt(i), list[i]); + } + } + test("abc"); + test(""); + test(" "); + } +} + +main() { + StringTest.testMain(); +} diff --git a/tests/corelib/src/StringTrimTest.dart b/tests/corelib/src/StringTrimTest.dart new file mode 100644 index 00000000000..ab54484fa9e --- /dev/null +++ b/tests/corelib/src/StringTrimTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringTrimTest { + static testMain() { + Expect.equals("", " ".trim()); + Expect.equals("", " ".trim()); + var a = " lots of space on the left"; + Expect.equals("lots of space on the left", a.trim()); + a = "lots of space on the right "; + Expect.equals("lots of space on the right", a.trim()); + a = " lots of space "; + Expect.equals("lots of space", a.trim()); + a = " x "; + Expect.equals("x", a.trim()); + Expect.equals("", " \t \n \r ".trim()); + } +} + +main() { + StringTrimTest.testMain(); +} diff --git a/tests/corelib/src/StringsTest.dart b/tests/corelib/src/StringsTest.dart new file mode 100644 index 00000000000..060bbfa0756 --- /dev/null +++ b/tests/corelib/src/StringsTest.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing class 'Strings'. + +class StringsTest { + + StringsTest() {} + + toString() { + return "Strings Tester"; + } + static testCreation() { + String s = "Hello"; + List l = new List(s.length); + for (int i = 0; i < l.length; i++) { + l[i] = s.charCodeAt(i); + } + String s2 = new String.fromCharCodes(l); + Expect.equals(s, s2); + } + + static void testMain() { + testCreation(); + } +} + + +main() { + StringsTest.testMain(); +} diff --git a/tests/corelib/src/UnicodeTest.dart b/tests/corelib/src/UnicodeTest.dart new file mode 100644 index 00000000000..ea420f98a80 --- /dev/null +++ b/tests/corelib/src/UnicodeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class UnicodeTest { + + static testMain() { + var lowerStrasse = + new String.fromCharCodes([115, 116, 114, 97, 223, 101]); + Expect.equals("STRASSE", lowerStrasse.toUpperCase()); + } +} + +main() { + UnicodeTest.testMain(); +} diff --git a/tests/corelib/testcfg.py b/tests/corelib/testcfg.py new file mode 100644 index 00000000000..2df39433e47 --- /dev/null +++ b/tests/corelib/testcfg.py @@ -0,0 +1,8 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import testing + +def GetConfiguration(context, root): + return testing.StandardTestConfiguration(context, root) diff --git a/tests/isolate/isolate.status b/tests/isolate/isolate.status new file mode 100644 index 00000000000..92961c270d8 --- /dev/null +++ b/tests/isolate/isolate.status @@ -0,0 +1,51 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +prefix isolate + +[ $arch == dartium ] +ConstructorTest: Fail # Bug 5246195 +MandelIsolateTest: Fail # Bug 5246195 +SpawnTest: Fail # Bug 5246195 +MessageTest: Fail # Bug 5246195 +IsolateComplexMessagesTest: Fail # Bug 5246195 +CountTest: Fail # Bug 5246195 +PromiseBasedTest: Fail # Bug 5246195 +StaticStateTest: Fail # Bug 5246195 +RequestReplyTest: Crash, Fail # Bug 5395487 +CrossIsolateMessageTest: Fail # Bug 5246195 + + +[ $arch == ia32 ] +Isolate2NegativeTest: Skip # Need to resolve correct behaviour. + +[ $arch == dartium || $arch == ia32 || $arch == x64 || $arch == simarm || $arch == arm ] +SerializationTest: Skip # DartC test (uses coreimpl). + +[ $arch == chromium && $arch == release ] +ConstructorTest: Fail # Bug 5382463 +SpawnTest: Fail # Bug 5382463 +IsolateComplexMessagesTest: Fail # Bug 5382463 +CountTest: Fail # Bug 5401734 +PromiseBasedTest: Fail # Bug 5401734 +MintMakerPromiseTest: Fail # Bug 5401734 +MintMakerTest: Fail # Bug 5401734 +RequestReplyTest: Fail # Bug 5401734 +StaticStateTest: Fail # Bug 5401734 + +[ $arch == chromium ] +MandelIsolateTest: Skip # Bug 5353937. + +[ $arch == dartc ] +MintMakerPromiseTest: Fail # Bug 5283149. +MintMakerTest: Fail # Bug 5283149. + +[ $arch == x64 ] +*: Skip + +[ $arch == simarm ] +*: Skip + +[ $arch == arm ] +*: Skip diff --git a/tests/isolate/src/ConstructorTest.dart b/tests/isolate/src/ConstructorTest.dart new file mode 100644 index 00000000000..de8736c7abb --- /dev/null +++ b/tests/isolate/src/ConstructorTest.dart @@ -0,0 +1,33 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("ConstructorTest"); +#import("TestFramework.dart"); + +class ConstructorTest extends Isolate { + final int field; + ConstructorTest() : super(), field = 499; + + void main() { + this.port.receive((ignoredMessage, reply) { + reply.send(field, null); + this.port.close(); + }); + } +} + +void test(TestExpectation expect) { + ConstructorTest test = new ConstructorTest(); + expect.completes(test.spawn()).then((SendPort port) { + ReceivePort reply = port.call("ignored"); + reply.receive(expect.runs2((message, replyPort) { + Expect.equals(499, message); + expect.succeeded(); + })); + }); +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/CountTest.dart b/tests/isolate/src/CountTest.dart new file mode 100644 index 00000000000..ba93892ed4c --- /dev/null +++ b/tests/isolate/src/CountTest.dart @@ -0,0 +1,58 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("CountTest"); +#import("TestFramework.dart"); + +class TestIsolate extends Isolate { + + TestIsolate() : super(); + + void main() { + int count = 0; + this.port.receive((int message, SendPort replyTo) { + if (message == -1) { + Expect.equals(10, count); + replyTo.send(-1, null); + this.port.close(); + return; + } + + Expect.equals(count, message); + count++; + replyTo.send(message * 2, null); + }); + } +} + +void test(TestExpectation expect) { + int count = 0; + expect.completes(new TestIsolate().spawn()).then((SendPort remote) { + ReceivePort local = new ReceivePort(); + SendPort reply = local.toSendPort(); + + local.receive(expect.runs2((int message, SendPort replyTo) { + if (message == -1) { + Expect.equals(11, count); + local.close(); + expect.succeeded(); + return; + } + + Expect.equals((count - 1) * 2, message); + remote.send(count++, reply); + if (count == 10) { + remote.send(-1, reply); + } + })); + remote.send(count++, reply); + }); +} + +void main() { + runTests([test]); +} + + + diff --git a/tests/isolate/src/CrossIsolateMessageTest.dart b/tests/isolate/src/CrossIsolateMessageTest.dart new file mode 100644 index 00000000000..540761b6136 --- /dev/null +++ b/tests/isolate/src/CrossIsolateMessageTest.dart @@ -0,0 +1,72 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing that isolates can communicate to isolates +// other than the main isolate. + +#library('CrossIsolateMessageTest'); +#import('TestFramework.dart'); + +class CrossIsolate1 extends Isolate { + CrossIsolate1() : super.heavy(); + + void main() { + this.port.receive((msg, replyTo) { + SendPort otherIsolate = msg; + ReceivePort receivePort = new ReceivePort(); + receivePort.receive((msg, replyTo) { + otherIsolate.send(msg + 58, null); // 100. + receivePort.close(); + }); + replyTo.send('ready', receivePort.toSendPort()); + this.port.close(); + }); + } +} + +// CrossIsolate2 is nearly the same as CrossIsolate1, but contains a +// different constant. +class CrossIsolate2 extends Isolate { + CrossIsolate2() : super.heavy(); + + void main() { + this.port.receive((msg, replyTo) { + SendPort mainIsolate = msg; + ReceivePort receivePort = new ReceivePort(); + receivePort.receive((msg, replyTo) { + mainIsolate.send(msg + 399, null); // 499. + receivePort.close(); + }); + replyTo.send('ready', receivePort.toSendPort()); + this.port.close(); + }); + } +} + +test(TestExpectation expect) { + // Create CrossIsolate1 and CrossIsolate2. + expect.completes(new CrossIsolate1().spawn()).then((SendPort port1) { + expect.completes(new CrossIsolate2().spawn()).then((SendPort port2) { + // Create a new receive port and send it to isolate2. + ReceivePort myPort = new ReceivePort(); + port2.call(myPort.toSendPort()).receive(expect.runs2((msg, port2b) { + Expect.equals("ready", msg); + // Send port of isolate2 to isolate1. + port1.call(port2b).receive(expect.runs2((msg, port1b) { + Expect.equals("ready", msg); + myPort.receive(expect.runs2((msg, replyTo) { + Expect.equals(499, msg); + expect.succeeded(); + myPort.close(); + })); + port1b.send(42, null); + })); + })); + }); + }); +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/Isolate2NegativeTest.dart b/tests/isolate/src/Isolate2NegativeTest.dart new file mode 100644 index 00000000000..c9adfa9c1b4 --- /dev/null +++ b/tests/isolate/src/Isolate2NegativeTest.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing that exceptions in other isolates bring down +// the program. + +#library('Isolate2NegativeTest'); +#import('TestFramework.dart'); + +class Isolate2NegativeTest extends Isolate { + Isolate2NegativeTest() : super(); + + void main() { + throw "foo"; + } +} + +void test(TestExpectation expect) { + // We will never call 'expect.succeeded'. This test fails with a timeout. + expect.completes(new Isolate2NegativeTest().spawn()); +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/IsolateComplexMessagesTest.dart b/tests/isolate/src/IsolateComplexMessagesTest.dart new file mode 100644 index 00000000000..41cc72b337a --- /dev/null +++ b/tests/isolate/src/IsolateComplexMessagesTest.dart @@ -0,0 +1,82 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing isolate communication with +// complex messages. + +#library("IsolateComplexMessagesTest"); +#import("TestFramework.dart"); + + +void test(TestExpectation expect) { + expect.completes(new LogIsolate().spawn()).then((SendPort remote) { + + remote.send(1, null); + remote.send("Hello", null); + remote.send("World", null); + remote.send(const [null, 1, 2, 3, 4], null); + remote.send(const [1, 2.0, true, false, 0xffffffffff], null); + remote.send(const ["Hello", "World", 0xffffffffff], null); + // Shutdown the LogRunner. + remote.call(-1).receive(expect.runs2((int message, SendPort replyTo) { + Expect.equals(6, message); + expect.succeeded(); + })); + }); +} + + +class LogIsolate extends Isolate { + LogIsolate() : super() { } + + void main() { + int count = 0; + + this.port.receive((var message, SendPort replyTo) { + if (message == -1) { + this.port.close(); + replyTo.send(count, null); + } else { + switch (count) { + case 0: + Expect.equals(1, message); + break; + case 1: + Expect.equals("Hello", message); + break; + case 2: + Expect.equals("World", message); + break; + case 3: + Expect.equals(5, message.length); + Expect.equals(null, message[0]); + Expect.equals(1, message[1]); + Expect.equals(2, message[2]); + Expect.equals(3, message[3]); + Expect.equals(4, message[4]); + break; + case 4: + Expect.equals(5, message.length); + Expect.equals(1, message[0]); + Expect.equals(2.0, message[1]); + Expect.equals(true, message[2]); + Expect.equals(false, message[3]); + Expect.equals(0xffffffffff, message[4]); + break; + case 5: + Expect.equals(3, message.length); + Expect.equals("Hello", message[0]); + Expect.equals("World", message[1]); + Expect.equals(0xffffffffff, message[2]); + break; + } + count++; + } + }); + } +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/IsolateNegativeTest.dart b/tests/isolate/src/IsolateNegativeTest.dart new file mode 100644 index 00000000000..8f0e214eab3 --- /dev/null +++ b/tests/isolate/src/IsolateNegativeTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing that isolates are spawned. + +#library('IsolateNegativeTest'); +#import("TestFramework.dart"); + +class IsolateNegativeTest extends Isolate { + IsolateNegativeTest() : super(); + + void main() { + this.port.receive((ignored, replyTo) { + replyTo.send("foo", null); + }); + } +} + +void test(TestExpectation expect) { + expect.completes(new IsolateNegativeTest().spawn()).then((SendPort port) { + port.call("foo").receive(expect.runs2((message, replyTo) { + Expect.equals(true, "Expected fail"); // <=-------- Should fail here. + expect.succeeded(); + })); + }); +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/MandelIsolateTest.dart b/tests/isolate/src/MandelIsolateTest.dart new file mode 100644 index 00000000000..d107e4e2096 --- /dev/null +++ b/tests/isolate/src/MandelIsolateTest.dart @@ -0,0 +1,155 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("MandelIsolateTest"); +#import('TestFramework.dart'); + +final TERMINATION_MESSAGE = -1; +final N = 100; +final ISOLATES = 20; + +void test(TestExpectation expect) { + final state = new MandelbrotState(); + expect.completes(state._validated).then((result) { + Expect.isTrue(result); + expect.succeeded(); + }); + for (int i = 0; i < Math.min(ISOLATES, N); i++) state.startClient(i); +} + + +class MandelbrotState { + + MandelbrotState() { + _result = new List>(N); + _lineProcessedBy = new List(N); + _sent = 0; + _missing = N; + _validated = new Promise(); + } + + void startClient(int id) { + assert(_sent < N); + final client = new LineProcessorClient(this, id); + client.processLine(_sent++); + } + + void notifyProcessedLine(LineProcessorClient client, int y, List line) { + assert(_result[y] === null); + _result[y] = line; + _lineProcessedBy[y] = client; + + if (_sent != N) { + client.processLine(_sent++); + } else { + client.shutdown(); + } + + // If all lines have been computed, validate the result. + if (--_missing == 0) { + _printResult(); + _validateResult(); + } + } + + void _validateResult() { + // TODO(ngeoffray): Implement this. + _validated.complete(true); + } + + void _printResult() { + var output = new StringBuffer(); + for (int i = 0; i < _result.length; i++) { + List line = _result[i]; + for (int j = 0; j < line.length; j++) { + if (line[j] < 10) output.add("0"); + output.add(line[j]); + } + output.add("\n"); + } + // print(output); + } + + List> _result; + List _lineProcessedBy; + int _sent; + int _missing; + Promise _validated; +} + + +class LineProcessorClient { + + LineProcessorClient(MandelbrotState this._state, int this._id) { + _out = new LineProcessor().spawn(); + } + + void processLine(int y) { + _out.then((SendPort p) { + p.call(y).receive((List message, SendPort replyTo) { + _state.notifyProcessedLine(this, y, message); + }); + }); + } + + void shutdown() { + _out.then((SendPort p) { + p.send(TERMINATION_MESSAGE, null); + }); + } + + MandelbrotState _state; + int _id; + Promise _out; + +} + + +class LineProcessor extends Isolate { + + LineProcessor() : super() { } + + void main() { + this.port.receive((message, SendPort replyTo) { + if (message == TERMINATION_MESSAGE) { + assert(replyTo == null); + this.port.close(); + } else { + replyTo.send(_processLine(message), null); + } + }); + } + + static List _processLine(int y) { + double inverseN = 2.0 / N; + double Civ = y * inverseN - 1.0; + List result = new List(N); + for (int x = 0; x < N; x++) { + double Crv = x * inverseN - 1.5; + + double Zrv = Crv; + double Ziv = Civ; + + double Trv = Crv * Crv; + double Tiv = Civ * Civ; + + int i = 49; + do { + Ziv = (Zrv * Ziv) + (Zrv * Ziv) + Civ; + Zrv = Trv - Tiv + Crv; + + Trv = Zrv * Zrv; + Tiv = Ziv * Ziv; + } while (((Trv + Tiv) <= 4.0) && (--i > 0)); + + result[x] = i; + } + return result; + } + +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/MessageTest.dart b/tests/isolate/src/MessageTest.dart new file mode 100644 index 00000000000..b0ab8948729 --- /dev/null +++ b/tests/isolate/src/MessageTest.dart @@ -0,0 +1,146 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing serialization of messages. +// VMOptions=--enable_type_checks --enable_asserts + +#library('MessageTest'); +#import("TestFramework.dart"); + +// --------------------------------------------------------------------------- +// Message passing test. +// --------------------------------------------------------------------------- + +class MessageTest { + static void test(TestExpectation expect) { + PingPongClient.test(expect); + } + + static final List list1 = const ["Hello", "World", "Hello", 0xfffffffffff]; + static final List list2 = const [null, list1, list1, list1, list1]; + static final List list3 = const [list2, 2.0, true, false, 0xfffffffffff]; + static final Map map1 = const { + "a=1" : 1, "b=2" : 2, "c=3" : 3, + }; + static final Map map2 = const { + "list1" : list1, "list2" : list2, "list3" : list3, + }; + static final List list4 = const [map1, map2]; + static final List elms = const [ + list1, list2, list3, list4, + ]; + + static void VerifyMap(Map expected, Map actual) { + Expect.equals(true, expected is Map); + Expect.equals(true, actual is Map); + Expect.equals(expected.length, actual.length); + testForEachMap(key, value) { + if (value is List) { + VerifyList(value, actual[key]); + } else { + Expect.equals(value, actual[key]); + } + } + expected.forEach(testForEachMap); + } + + static void VerifyList(List expected, List actual) { + for (int i = 0; i < expected.length; i++) { + if (expected[i] is List) { + VerifyList(expected[i], actual[i]); + } else if (expected[i] is Map) { + VerifyMap(expected[i], actual[i]); + } else { + Expect.equals(expected[i], actual[i]); + } + } + } + + static void VerifyObject(int index, var actual) { + var expected = elms[index]; + Expect.equals(true, expected is List); + Expect.equals(true, actual is List); + Expect.equals(expected.length, actual.length); + VerifyList(expected, actual); + } +} + +class PingPongClient { + static void test(TestExpectation expect) { + expect.completes(new PingPongServer().spawn()).then((SendPort remote) { + + // Send objects and receive them back. + for (int i = 0; i < MessageTest.elms.length; i++) { + var sentObject = MessageTest.elms[i]; + // TODO(asiva): remove this local var idx once thew new for-loop + // semantics for closures is implemented. + var idx = i; + remote.call(sentObject).receive(expect.runs2( + (var receivedObject, SendPort replyTo) { + MessageTest.VerifyObject(idx, receivedObject); + })); + } + + // Send recursive objects and receive them back. + List local_list1 = ["Hello", "World", "Hello", 0xffffffffff]; + List local_list2 = [null, local_list1, local_list1 ]; + List local_list3 = [local_list2, 2.0, true, false, 0xffffffffff]; + List sendObject = new List(5); + sendObject[0] = local_list1; + sendObject[1] = sendObject; + sendObject[2] = local_list2; + sendObject[3] = sendObject; + sendObject[4] = local_list3; + remote.call(sendObject).receive( + (var replyObject, SendPort replyTo) { + Expect.equals(true, sendObject is List); + Expect.equals(true, replyObject is List); + Expect.equals(sendObject.length, replyObject.length); + Expect.equals(true, replyObject[1] === replyObject); + Expect.equals(true, replyObject[3] === replyObject); + Expect.equals(true, replyObject[0] === replyObject[2][1]); + Expect.equals(true, replyObject[0] === replyObject[2][2]); + Expect.equals(true, replyObject[2] === replyObject[4][0]); + Expect.equals(true, replyObject[0][0] === replyObject[0][2]); + // Bigint literals are not canonicalized so do a == check. + Expect.equals(true, replyObject[0][3] == replyObject[4][4]); + }); + + // Shutdown the MessageServer. + remote.call(-1).receive(expect.runs2( + (int message, SendPort replyTo) { + Expect.equals(MessageTest.elms.length + 1, message); + expect.succeeded(); + })); + }); + } +} + +class PingPongServer extends Isolate { + PingPongServer() : super() {} + + void main() { + int count = 0; + this.port.receive( + (var message, SendPort replyTo) { + if (message == -1) { + this.port.close(); + replyTo.send(count, null); + } else { + // Check if the received object is correct. + if (count < MessageTest.elms.length) { + MessageTest.VerifyObject(count, message); + } + // Bounce the received object back so that the sender + // can make sure that the object matches. + replyTo.send(message, null); + count++; + } + }); + } +} + +main() { + runTests([MessageTest.test]); +} diff --git a/tests/isolate/src/MintMakerPromiseTest.dart b/tests/isolate/src/MintMakerPromiseTest.dart new file mode 100644 index 00000000000..edf3e1e987b --- /dev/null +++ b/tests/isolate/src/MintMakerPromiseTest.dart @@ -0,0 +1,221 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface Mint factory MintImpl { + + Mint(); + + Purse createPurse(int balance); + +} + + +class MintImpl implements Mint { + + MintImpl() { } + + Purse createPurse(int balance) { + return new PurseImpl(this, balance); + } + +} + + +interface Purse { + + int queryBalance(); + Purse sproutPurse(); + void deposit(int amount, Purse$Proxy source); + +} + + +class PurseImpl implements Purse { + + PurseImpl(this._mint, this._balance) { } + + int queryBalance() { + return _balance; + } + + Purse sproutPurse() { + return _mint.createPurse(0); + } + + void deposit(int amount, Purse$Proxy purse) { + Purse$ProxyImpl impl = purse.dynamic; // TODO: Get rid of this 'cast'. + PurseImpl source = impl.local; + if (source._balance < amount) throw "Not enough dough."; + _balance += amount; + source._balance -= amount; + } + + Mint _mint; + int _balance; + +} + + +class MintMakerPromiseTest { + + static void testMain() { + Mint$Proxy mint = createMint(); + Purse$Proxy purse = mint.createPurse(100); + expectEquals(100, purse.queryBalance()); + + Purse$Proxy sprouted = purse.sproutPurse(); + expectEquals(0, sprouted.queryBalance()); + + sprouted.deposit(5, purse); + expectEquals(0 + 5, sprouted.queryBalance()); + expectEquals(100 - 5, purse.queryBalance()); + + sprouted.deposit(42, purse); + expectEquals(0 + 5 + 42, sprouted.queryBalance()); + expectEquals(100 - 5 - 42, purse.queryBalance()); + + expectDone(6); + } + + static Mint$Proxy createMint() { + Proxy isolate = new Proxy.forIsolate(new Mint$Dispatcher$Isolate()); + return new Mint$ProxyImpl(isolate); + } + + + static List results; + + static void expectEquals(int expected, Promise promise) { + if (results === null) { + results = new List(); + } + results.add(promise.then((int actual) { + Expect.equals(expected, actual); + })); + } + + static void expectDone(int n) { + if (results === null) { + Expect.equals(0, n); + } else { + Promise done = new Promise(); + done.waitFor(results, results.length); + done.then((ignored) { + Expect.equals(n, results.length); + }); + } + } + +} + + +// --------------------------------------------------------------------------- +// THE REST OF THIS FILE COULD BE AUTOGENERATED +// --------------------------------------------------------------------------- + +interface Mint$Proxy { + + Purse$Proxy createPurse(int balance); // Promise balance. + +} + + +class Mint$ProxyImpl extends Proxy implements Mint$Proxy { + + Mint$ProxyImpl(Proxy isolate) : super.forReply(isolate.call([null])) {} + + Purse$Proxy createPurse(int balance) { + return new Purse$ProxyImpl(this.call([balance])); + } + +} + + +class Mint$Dispatcher extends Dispatcher { + + Mint$Dispatcher(Mint mint) : super(mint) { } + + void process(var message, void reply(var response)) { + int balance = message[0]; + Purse purse = target.createPurse(balance); + SendPort port = Dispatcher.serve(new Purse$Dispatcher(purse)); + reply(port); + } + +} + + +class Mint$Dispatcher$Isolate extends Isolate { + + Mint$Dispatcher$Isolate() : super() { } + + void main() { + this.port.receive((var message, SendPort replyTo) { + Mint mint = new Mint(); + SendPort port = Dispatcher.serve(new Mint$Dispatcher(mint)); + Proxy proxy = new Proxy.forPort(replyTo); + proxy.send([port]); + }); + } + +} + + +interface Purse$Proxy { + + Promise queryBalance(); + Purse$Proxy sproutPurse(); + void deposit(int amount, Purse$Proxy source); // Promise amount. + +} + + +class Purse$ProxyImpl extends Proxy implements Purse$Proxy { + + Purse$ProxyImpl(Promise port) : super.forReply(port) { } + + Promise queryBalance() { + return this.call(["balance"]); + } + + void deposit(int amount, Purse$Proxy source) { + this.send(["deposit", amount, source]); + } + + Purse$Proxy sproutPurse() { + return new Purse$ProxyImpl(this.call(["sprout"])); + } + +} + + +class Purse$Dispatcher extends Dispatcher { + + Purse$Dispatcher(Purse purse) : super(purse) { } + + void process(var message, void reply(var response)) { + String command = message[0]; + if (command == "balance") { + int balance = target.queryBalance(); + reply(balance); + } else if (command == "deposit") { + int amount = message[1]; + Promise port = new Promise.fromValue(message[2]); + Purse$Proxy source = new Purse$ProxyImpl(port); + target.deposit(amount, source); + } else if (command == "sprout") { + Purse purse = target.sproutPurse(); + SendPort port = Dispatcher.serve(new Purse$Dispatcher(purse)); + reply(port); + } else { + // TODO: Send an exception back. + reply("Exception: Command not understood"); + } + } + +} + +main() { + MintMakerPromiseTest.testMain(); +} diff --git a/tests/isolate/src/MintMakerTest.dart b/tests/isolate/src/MintMakerTest.dart new file mode 100644 index 00000000000..e7ad507e6f7 --- /dev/null +++ b/tests/isolate/src/MintMakerTest.dart @@ -0,0 +1,272 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Things that should be "auto-generated" are between AUTO START and +// AUTO END (or just AUTO if it's a single line). + + +class Mint { + Mint() : registry_ = new Map() { + // AUTO START + ReceivePort mintPort = new ReceivePort(); + port = mintPort.toSendPort(); + serveMint(mintPort); + // AUTO END + } + + // AUTO START + void serveMint(ReceivePort port) { + port.receive((var message, SendPort replyTo) { + int balance = message; + Purse purse = createPurse(balance); + replyTo.send([ purse.port ], null); + }); + } + // AUTO END + + Purse createPurse(int balance) { + Purse purse = new Purse(this, balance); + registry_[purse.port] = purse; + return purse; + } + + Purse lookupPurse(SendPort port) { + return registry_[port]; + } + + Map registry_; + // AUTO + SendPort port; +} + + +// AUTO START +class MintWrapper { + MintWrapper(SendPort this.mint_) {} + + void createPurse(int balance, handlePurse(PurseWrapper purse)) { + mint_.call(balance).receive((var message, SendPort replyTo) { + SendPort purse = message[0]; + handlePurse(new PurseWrapper(purse)); + }); + } + + SendPort mint_; +} +// AUTO END + + +/* +One way this could look without the autogenerated code: + +class Mint { + Mint() : registry_ = new Map() { + } + + wrap Purse createPurse(int balance) { + Purse purse = new Purse(this, balance); + registry_[purse.port] = purse; + return purse; + } + + Purse lookupPurse(SendPort port) { + return registry_[port]; + } + + Map registry_; +} + +The other end of the port would use Wrapper as the wrapper, or +Future as a future for the wrapper. +*/ + + +class Purse { + Purse(Mint this.mint, int this.balance) { + // AUTO START + ReceivePort recipient = new ReceivePort(); + port = recipient.toSendPort(); + servePurse(recipient); + // AUTO END + } + + // AUTO START + void servePurse(ReceivePort recipient) { + recipient.receive((var message, SendPort replyTo) { + String command = message[0]; + if (command == "balance") { + replyTo.send(queryBalance(), null); + } else if (command == "deposit") { + Purse source = mint.lookupPurse(message[2]); + deposit(message[1], source); + } else if (command == "sprout") { + Purse result = sproutPurse(); + replyTo.send([ result.port ], null); + } else { + // TODO: Send an exception back. + replyTo.send("Exception: Command not understood", null); + } + }); + } + // AUTO END + + int queryBalance() { return balance; } + + Purse sproutPurse() { return mint.createPurse(0); } + + void deposit(int amount, Purse source) { + // TODO: Throw an exception if the source purse doesn't hold + // enough dough. + balance += amount; + source.balance -= amount; + } + + Mint mint; + int balance; + // AUTO + SendPort port; +} + + +// AUTO START +class PurseWrapper { + PurseWrapper(SendPort this.purse_) {} + + void queryBalance(handleBalance(int balance)) { + purse_.call([ "balance" ]).receive((var message, SendPort replyTo) { + int balance = message; + handleBalance(balance); + }); + } + + void sproutPurse(handleSprouted(PurseWrapper sprouted)) { + purse_.call([ "sprout" ]).receive((var message, SendPort replyTo) { + SendPort sprouted = message[0]; + handleSprouted(new PurseWrapper(sprouted)); + }); + } + + void deposit(PurseWrapper source, int amount) { + purse_.send([ "deposit", amount, source.purse_ ], null); + } + + + SendPort purse_; +} +// AUTO END + + +// AUTO STATUS UNCLEAR! + +class MintMakerWrapperIsolate extends Isolate { + MintMakerWrapperIsolate() : super() { } + void main() { + this.port.receive((var message, SendPort replyTo) { + Mint mint = new Mint(); + replyTo.send([ mint.port ], null); + }); + } +} + +class MintMakerWrapper { + MintMakerWrapper() { + port_ = new MintMakerWrapperIsolate().spawn(); + } + + void makeMint(handleMint(MintWrapper mint)) { + port_.then((SendPort port) { + port.call(null).receive((var message, SendPort replyTo) { + SendPort mint = message[0]; + handleMint(new MintWrapper(mint)); + }); + }); + } + + Promise port_; +} + + +class MintMakerTest { + static void testMain() { + MintMakerWrapper mintMaker = new MintMakerWrapper(); + mintMaker.makeMint((MintWrapper mint) { + mint.createPurse(100, (PurseWrapper purse) { + purse.queryBalance((int balance) { + Expect.equals(100, balance); + }); + purse.sproutPurse((PurseWrapper sprouted) { + sprouted.queryBalance((int balance) { + Expect.equals(0, balance); + }); + sprouted.deposit(purse, 5); + sprouted.queryBalance((int balance) { + Expect.equals(0 + 5, balance); + }); + purse.queryBalance((int balance) { + Expect.equals(100 - 5, balance); + }); + sprouted.deposit(purse, 42); + sprouted.queryBalance((int balance) { + Expect.equals(0 + 5 + 42, balance); + }); + purse.queryBalance((int balance) { + Expect.equals(100 - 5 - 42, balance); + }); + }); + }); + }); + } + + /* This is an attempt to show how the above code could look like if we had + * better language support for asynchronous messages (deferred/asynccall). + * The static helper methods like createPurse and queryBalance would also + * have to be marked async. + + void run(port) { + MintMakerWrapper mintMaker = spawnMintMaker(); + deferred { + MintWrapper mint = asynccall mintMaker.createMint(); + PurseWrapper purse = asynccall mint.createPurse(100); + Expect.equals(100, asynccall purse.queryBalance()); + + PurseWrapper sprouted = asynccall purse.sproutPurse(); + Expect.equals(0, asynccall sprouted.queryBalance()); + + asynccall sprouted.deposit(purse, 5); + Expect.equals(0 + 5, asynccall sprouted.queryBalance()); + Expect.equals(100 - 5, asynccall purse.queryBalance()); + + asynccall sprouted.deposit(purse, 42); + Expect.equals(0 + 5 + 42, asynccall sprouted.queryBalance()); + Expect.equals(100 - 5 - 42, asynccall purse.queryBalance()); + } + } + */ + + /* And a version using futures and wrappers. + + void run(port) { + Wrapper mintMaker = spawnMintMaker(); + Future mint = mintMaker...createMint(); + Future purse = mint...createPurse(100); + Expect.equals(100, purse.queryBalance()); + + Future sprouted = purse...sproutPurse(); + Expect.equals(0, sprouted.queryBalance()); + + sprouted...deposit(purse, 5); + Expect.equals(0 + 5, sprouted.queryBalance()); + Expect.equals(100 - 5, purse.queryBalance()); + + sprouted...deposit(purse, 42); + Expect.equals(0 + 5 + 42, sprouted.queryBalance()); + Expect.equals(100 - 5 - 42, purse.queryBalance()); + } + */ + +} + +main() { + MintMakerTest.testMain(); +} diff --git a/tests/isolate/src/PromiseBasedTest.dart b/tests/isolate/src/PromiseBasedTest.dart new file mode 100644 index 00000000000..91b3e9c0325 --- /dev/null +++ b/tests/isolate/src/PromiseBasedTest.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("PromiseBasedTest"); +#import("TestFramework.dart"); + +class TestIsolate extends Isolate { + + TestIsolate() : super(); + + void main() { + int seed = 0; + this.port.receive((var message, SendPort replyTo) { + if (seed == 0) { + seed = message[0]; + } else { + Promise response = new Promise(); + var proxy = new Proxy.forPort(replyTo); + proxy.send([response]); + response.complete(seed + message[0]); + this.port.close(); + } + }); + } + +} + +void test(TestExpectation expect) { + Proxy proxy = new Proxy.forIsolate(new TestIsolate()); + proxy.send([42]); // Seed the isolate. + Promise promise = expect.completes(proxy.call([87])).then((int value) { + Expect.equals(42 + 87, value); + return 99; + }); + expect.completes(promise).then((int value) { + Expect.equals(99, value); + expect.succeeded(); + }); +} + +void main() { + runTests([test]); +} diff --git a/tests/isolate/src/RequestReplyTest.dart b/tests/isolate/src/RequestReplyTest.dart new file mode 100644 index 00000000000..4ad0a55d266 --- /dev/null +++ b/tests/isolate/src/RequestReplyTest.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("RequestReplyTest"); +#import("TestFramework.dart"); + +class TestIsolate extends Isolate { + + TestIsolate() : super(); + + void main() { + this.port.receive((message, SendPort replyTo) { + replyTo.send(message + 87, null); + this.port.close(); + }); + } + +} + +void testCall(TestExpectation expect) { + expect.completes(new TestIsolate().spawn()).then((SendPort port) { + port.call(42).receive(expect.runs2((message, replyTo) { + Expect.equals(42 + 87, message); + expect.succeeded(); + })); + }); +} + +void testSend(TestExpectation expect) { + expect.completes(new TestIsolate().spawn()).then((SendPort port) { + ReceivePort reply = new ReceivePort(); + port.send(99, reply.toSendPort()); + reply.receive(expect.runs2((message, replyTo) { + Expect.equals(99 + 87, message); + reply.close(); + expect.succeeded(); + })); + }); +} + +void testSendSingleShot(TestExpectation expect) { + expect.completes(new TestIsolate().spawn()).then((SendPort port) { + ReceivePort reply = new ReceivePort.singleShot(); + port.send(99, reply.toSendPort()); + reply.receive(expect.runs2((message, replyTo) { + Expect.equals(99 + 87, message); + expect.succeeded(); + })); + }); +} + +void main() { + runTests([testCall, testSend, testSendSingleShot]); +} diff --git a/tests/isolate/src/SerializationTest.dart b/tests/isolate/src/SerializationTest.dart new file mode 100644 index 00000000000..0f71af77312 --- /dev/null +++ b/tests/isolate/src/SerializationTest.dart @@ -0,0 +1,92 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing serialization of messages without spawning +// isolates. + +// --------------------------------------------------------------------------- +// Serialization test. +// --------------------------------------------------------------------------- +#library('SerializationTest'); +#import("dart:coreimpl"); + +main() { + testAllTypes(copy); + testAllTypes(serialize); +} + +copy(x) { + return new Copier().traverse(x); +} + +serialize(x) { + Serializer serializer = new Serializer(); + Deserializer deserializer = new Deserializer(); + return deserializer.deserialize(serializer.traverse(x)); +} + +void testAllTypes(Function f) { + copyAndVerify(0, f); + copyAndVerify(499, f); + copyAndVerify(true, f); + copyAndVerify(false, f); + copyAndVerify("", f); + copyAndVerify("foo", f); + copyAndVerify([], f); + copyAndVerify([1, 2], f); + copyAndVerify([[]], f); + copyAndVerify([1, []], f); + copyAndVerify({}, f); + copyAndVerify({ 'a': 3 }, f); + copyAndVerify({ 'a': 3, 'b': 5, 'c': 8 }, f); + copyAndVerify({ 'a': [1, 2] }, f); + copyAndVerify({ 'b': { 'c' : 99 } }, f); + copyAndVerify([ { 'a': 499 }, { 'b': 42 } ], f); + + var port = new ReceivePort(); + var transformed = f(port); + Expect.equals(port.toSendPort(), transformed); + port.close(); + + port = new ReceivePort.singleShot(); + transformed = f(port); + Expect.equals(port.toSendPort(), transformed); + port.close(); + + var a = [ 1, 3, 5 ]; + var b = { 'b': 49 }; + var c = [ a, b, a, b, a ]; + var copied = f(c); + verify(c, copied); + Expect.isFalse(c === copied); + Expect.isTrue(copied[0] === copied[2]); + Expect.isTrue(copied[0] === copied[4]); + Expect.isTrue(copied[1] === copied[3]); +} + +void copyAndVerify(o, Function f) { + var copy = f(o); + verify(o, copy); +} + +void verify(o, copy) { + if ((o is bool) || (o is num) || (o is String)) { + Expect.equals(o, copy); + } else if (o is List) { + Expect.isTrue(copy is List); + Expect.equals(o.length, copy.length); + for (int i = 0; i < o.length; i++) { + verify(o[i], copy[i]); + } + } else if (o is Map) { + Expect.isTrue(copy is Map); + Expect.equals(o.length, copy.length); + o.forEach((key, value) { + Expect.isTrue(copy.containsKey(key)); + verify(value, copy[key]); + }); + } else { + Expect.fail("Unexpected object encountered"); + } +} diff --git a/tests/isolate/src/SpawnTest.dart b/tests/isolate/src/SpawnTest.dart new file mode 100644 index 00000000000..efa823343c4 --- /dev/null +++ b/tests/isolate/src/SpawnTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("SpawnTest"); +#import("TestFramework.dart"); + +void test(TestExpectation expect) { + SpawnedIsolate isolate = new SpawnedIsolate(); + expect.completes(isolate.spawn()).then((SendPort port) { + port.call(42).receive(expect.runs2((message, replyTo) { + Expect.equals(42, message); + expect.succeeded(); + })); + }); +} + +class SpawnedIsolate extends Isolate { + + SpawnedIsolate() : super() { } + + void main() { + this.port.receive((message, SendPort replyTo) { + Expect.equals(42, message); + replyTo.send(42, null); + this.port.close(); + }); + } + +} + +main() { + runTests([test]); +} diff --git a/tests/isolate/src/StaticStateTest.dart b/tests/isolate/src/StaticStateTest.dart new file mode 100644 index 00000000000..3b1292a9d70 --- /dev/null +++ b/tests/isolate/src/StaticStateTest.dart @@ -0,0 +1,50 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("StaticStateTest"); +#import("TestFramework.dart"); + +class TestIsolate extends Isolate { + + TestIsolate() : super(); + + void main() { + Expect.equals(null, state); + this.port.receive((var message, SendPort replyTo) { + String old = state; + state = message; + replyTo.send(old, null); + if (message == "exit") { + this.port.close(); + } + }); + } + + static String state; + +} + +void test(TestExpectation expect) { + Expect.equals(null, TestIsolate.state); + TestIsolate.state = "foo"; + Expect.equals("foo", TestIsolate.state); + + expect.completes(new TestIsolate().spawn()).then((SendPort remote) { + remote.call("bar").receive(expect.runs2((reply, replyTo) { + Expect.equals("foo", TestIsolate.state); + Expect.equals(null, reply); + + TestIsolate.state = "baz"; + remote.call("exit").receive(expect.runs2((reply, replyTo) { + Expect.equals("baz", TestIsolate.state); + Expect.equals("bar", reply); + expect.succeeded(); + })); + })); + }); +} + +void main() { + runTests([test]); +} diff --git a/tests/isolate/src/TestFramework.dart b/tests/isolate/src/TestFramework.dart new file mode 100644 index 00000000000..3cd960f8974 --- /dev/null +++ b/tests/isolate/src/TestFramework.dart @@ -0,0 +1,279 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("TestFramework"); +#import("dart:coreimpl"); + + +typedef void AsynchronousTestFunction(TestExpectation check); + + +void runTests(List tests) { + TestRunner runner = new TestRunner(new TestSuite(tests)); + TestResult result = new TestResult(runner); + runner.run(result); +} + + +class TestSuite { + + TestSuite([List tests = const []]) : testCases = [] { + for (var test in tests) { + addTest(test); + } + } + + void addTest(var test) { + if (test is Function) { + addAsynchronousTestCase(test); + } else { + test.addToTestSuite(this); + } + } + + void addTestCase(TestCase test) { + testCases.add(test); + } + + void addAsynchronousTestCase(AsynchronousTestFunction test) { + addTestCase(new AsynchronousTestCase(test)); + } + + void run(TestResult result) { + for (TestCase test in testCases) { + test.run(result); + } + } + + final List testCases; + +} + + +class TestCase { + + TestCase(); + + void setUp() { } + abstract void performTest(); + void tearDown() { } + + void run(TestResult result) { + setUp(); + result.runGuarded(this, () { + performTest(); + tearDown(); + }); + } + + void addToTestSuite(TestSuite suite) { + suite.addTestCase(this); + } + +} + + +class TestResult { + + TestResult(this.runner) : errors = [], failures = []; + + void error(String message, TestCase testCase) { + errors.add([message, testCase]); + } + + void failure(String message, TestCase testCase) { + failures.add([message, testCase]); + } + + runGuarded(TestCase testCase, Function fn) { + var result = null; + try { + result = fn(); + } catch (ExpectException exception) { + failure(exception.toString(), testCase); + testCase.tearDown(); + } catch (var exception) { + error(exception.toString(), testCase); + testCase.tearDown(); + } + return result; + } + + bool hasDefects() { + return !(errors.isEmpty() && failures.isEmpty()); + } + + final TestRunner runner; + final List errors; + final List failures; + +} + + +class TestRunner { + + TestRunner(this.suite); + + void run(TestResult result) { + if (waitForDoneCallback !== null) { + waitForDoneCallback(); + } + suite.run(result); + if (AsynchronousTestCase.running == 0) { + done(result); + } + } + + void done(TestResult result) { + if (result.hasDefects()) { + printDefects(result); + Expect.fail("Test suite failed."); + } + if (doneCallback !== null) { + doneCallback(); + } + } + + void printDefects(TestResult result) { + printDefectList("Errors", result.errors); + printDefectList("Failures", result.failures); + } + + static void printDefectList(String type, List defects) { + if (!defects.isEmpty()) { + print("$type #${defects.length}:"); + for (List defect in defects) { + print(" - ${defect[0]}"); + } + } + } + + final TestSuite suite; + static Function waitForDoneCallback; + static Function doneCallback; + +} + + +class TestExpectation { + + TestExpectation(this.testCase, this.result); + + void succeeded() { + Expect.equals(0, pendingCallbacks); + hasSucceeded = true; + testCase.tearDown(); + } + + void failed() { + testCase.tearDown(); + } + + Promise completes(Promise promise) { + Promise result = new TestPromise(this); + promise.then((value) { result.complete(value); }); + return result; + } + + Function runs0(Function fn) { + bool ran = false; // We only check that the function is executed once. + pendingCallbacks++; + return () { + if (!ran) pendingCallbacks--; + ran = true; + return result.runGuarded(testCase, () => fn()); + }; + } + + Function runs1(Function fn) { + bool ran = false; // We only check that the function is executed once. + pendingCallbacks++; + return (a0) { + if (!ran) pendingCallbacks--; + ran = true; + return result.runGuarded(testCase, () => fn(a0)); + }; + } + + Function runs2(Function fn) { + bool ran = false; // We only check that the function is executed once. + pendingCallbacks++; + return (a0, a1) { + if (!ran) pendingCallbacks--; + ran = true; + return result.runGuarded(testCase, () => fn(a0, a1)); + }; + } + + bool hasPendingCallbacks() { + return pendingCallbacks > 0; + } + + final AsynchronousTestCase testCase; + final TestResult result; + + int pendingCallbacks = 0; + bool hasSucceeded = false; + +} + + +class AsynchronousTestCase extends TestCase { + + AsynchronousTestCase(this.test) : super(); + + void run(TestResult result) { + setUp(); + result.runGuarded(this, () { + addRunning(result); + TestExpectation expect = new TestExpectation(this, result); + test(expect); + if (!expect.hasPendingCallbacks()) { + Expect.isTrue(expect.hasSucceeded); + tearDown(); + } + }); + } + + void tearDown() { + removeRunning(); + } + + void addRunning(TestResult result) { + if (running++ == 0) { + keepalive = new ReceivePort.singleShot(); + keepalive.receive((message, replyTo) { + result.runner.done(result); + }); + } + } + + void removeRunning() { + if (--running == 0) { + keepalive.toSendPort().send(null, null); + keepalive = null; + } + } + + AsynchronousTestFunction test; + + static int running = 0; + static ReceivePort keepalive = null; + +} + + +class TestPromise extends PromiseImpl { + + TestPromise(this.expect) : super(); + + void addCompleteHandler(void completeHandler(T result)) { + super.addCompleteHandler(expect.runs1((T result) { + completeHandler(result); + })); + } + + final TestExpectation expect; + +} diff --git a/tests/isolate/testcfg.py b/tests/isolate/testcfg.py new file mode 100644 index 00000000000..2df39433e47 --- /dev/null +++ b/tests/isolate/testcfg.py @@ -0,0 +1,8 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import testing + +def GetConfiguration(context, root): + return testing.StandardTestConfiguration(context, root) diff --git a/tests/language/language.status b/tests/language/language.status new file mode 100644 index 00000000000..d940b457f71 --- /dev/null +++ b/tests/language/language.status @@ -0,0 +1,265 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +# This directory contains tests that are intended to show the +# current state of the language. + +# In order to maintain maximum test coverage for all builds, +# please use the following procedure to mark a test +# failed on an architecture other than the one you are working on. +# +# 1) Copy the old version of the test to [runtime|compiler]/tests/dart/src +# 2) Rename the file with a 'Legacy' prefix. +# 3) File a bug for the failure due to the language change. +# 4) Update the dart.status and language.status files appropriately. +# 5) Update the language/src directory with the updated test. + +prefix language + + +[ $arch == ia32 || $arch == dartium ] +ClassTest: Fail # Bug 4504458 (pseudo keyword) +NamingTest: Fail # Bug 4504458 (pseudo keyword) +SuperTest: Fail # Bug 4995181 +TypeVariableBoundsTest/none: Fail # Bug 5257789 +TypeVariableBoundsTest/02: Fail # Bug 5257789 +TypeVariableBoundsTest/03: Fail # Bug 5257789 +TypeVariableBoundsTest/04: Fail # Bug 5257789 +TypeVariableBoundsTest/07: Fail # Bug 5257789 +TypeVariableScopeTest/03: Fail # Bug 5349550, was 5316513 +TypeVariableScopeTest/04: Fail # Bug 5349550, was 5316513 +FauxverrideTest/01: Fail # Bug 5328413 +FauxverrideTest/02: Fail # Bug 5328413 +FauxverrideTest/03: Fail # Bug 5328413 +ImpliedInterfaceTest: Fail # Bug 5349944 +OverrideMethodWithFieldTest: Fail # Bug 5384453 +FieldOverrideTest/none: Fail # Bug 5384222 +FieldOverrideTest/01: Fail # Bug 5384222 +CallThroughNullGetterTest: Fail # Bug 4968741 + +# These bugs refer currently ongoing language discussions. +ExampleConstructorTest: Fail # Bug 4995181 + + +# Regular bugs which should be fixed. +SuperNegativeTest: Fail # Bug 4400118 - Language still in flux. +ManyEchoServerTest: Skip # Bug 5103754 +CanonicalConstTest: Fail # Bug 5270133 +OverrideFieldTest/none: Fail # Bug 5384222 +GenericParameterizedExtendsTest: Skip # Bug 5391643 + +# Problems specific to dartc optimized mode +[ ($arch == dartc || $arch == chromium) && $mode == release ] +MethodInvocationTest: Fail # Bug 5392266 +Label2NegativeTest: Crash # Bug 5318228 +NullPointerExceptionTest: Fail # Bug 5391976 +CallThroughNullGetterTest: Fail # Bug 5391976 +Private3Test: Fail # Bug 5391976 +Switch3NegativeTest: Crash # Bug 5318228 + +# Tests that pass in release mode but fail in debug mode +[ ($arch == dartc || $arch == chromium) && $mode == debug ] + + +[ $arch == dartc || $arch == chromium ] +Prefix1NegativeTest: Skip # Bug 5406175 +Prefix2NegativeTest: Skip # Bug 5406175 +Prefix3NegativeTest: Skip # Bug 5406175 +Prefix4NegativeTest: Skip # Bug 5406175 +Prefix5NegativeTest: Skip # Bug 5406175 +Prefix6NegativeTest: Skip # Bug 5406175 +Prefix7NegativeTest: Skip # Bug 5406175 +Prefix8NegativeTest: Skip # Bug 5406175 +Prefix9NegativeTest: Skip # Bug 5406175 +Prefix10NegativeTest: Skip # Bug 5406175 +Prefix11NegativeTest: Skip # Bug 5406175 +Prefix12NegativeTest: Skip # Bug 5406175 +PrefixTest: Skip # Bug 5406175 +Prefix10Test: Skip # Bug 5406175 +Prefix11Test: Skip # Bug 5406175 +Prefix12Test: Skip # Bug 5406175 +LibraryPrefixesTest: Skip # Bug 5406175 +TopLevelNonPrefixedLibraryTest: Skip # Bug 5406175 +DefaultFactoryTest: Fail # Bug 5009110 +FunctionTypeParameterNegativeTest: Fail # Bug 4568007 +ImplicitScopeTest: FAIL # Nested statements can be declarations +ResolveTest: FAIL # 4254120 (implicit constructors) +ConstConstructor1NegativeTest: FAIL # 5142545 +ConstConstructor2NegativeTest: FAIL # 5142545 +MathTest: FAIL # 5165080 +StringConcatTest: FAIL # 5196164 +NamedParametersTest: Fail # Implementation in progress. +NamedParametersTypeTest: Fail # Implementation in progress. +NamedParametersWithConversionsTest: Fail # Implementation in progress. +BadNamedParameters2Test: Fail # Implementation in progress. +NamedParametersNegativeTest: Skip # Implementation in progress. +NamedParameters2NegativeTest: Skip # Implementation in progress. +NamedParameters3NegativeTest: Skip # Implementation in progress. +NamedParameters4NegativeTest: Skip # Implementation in progress. +NamedParameters5NegativeTest: Skip # Implementation in progress. +NamedParameters6NegativeTest: Skip # Implementation in progress. +NamedParameters7NegativeTest: Skip # Implementation in progress. +NamedParameters8NegativeTest: Skip # Implementation in progress. +ScopeVariableTest: Fail # 5244704 +Field1NegativeTest: Fail # 5253031 +InstFieldInitializerTest: Fail # Cannot deal with static final values in const expression. +RegExp3Test: Fail # 5299683 +InterfaceFactory3NegativeTest: Fail # 5387405 +GenericParameterizedExtendsTest: Skip # Bug 5392297 +InterfaceFactoryMultiTest: Fail # Bug 5399939 + +# Crashes in dartc. +FunctionTypeAliasTest: Crash # Bug 4519208. + +# Other bugs (or unimplemented features) in dartc. +GenericTest: Fail # Bug 5393302 (missing call to super constructor) +GenericInheritanceTest: Fail # Bug 4562150 (implicit constructors). +Throw7NegativeTest: Fail # Bug 4208459. +Throw3Test: Fail # Bug 4205624. +SwitchLabelTest: Fail # Bug 4208467. +Switch7NegativeTest: Fail # Bug 4208467. +StackOverflowTest: Fail # Bug 4591172. +ScopeNegativeTest: Fail # Bug 4207538. +PseudoKWNegativeTest: Fail # Bug 4979760. +OverriddenNoSuchMethodTest: Fail # Bug 4202974. +ManyOverriddenNoSuchMethodTest: Fail # Bug 4202974. +NoSuchMethodTest: Fail # Bug 4202974. +BadNamedParametersTest: Fail # Bug 4202974. +NumbersTest: Fail # Fails because numbers are mapped to doubles. +LocalFunctionTest: Fail # Bug in test. Bug 4202989 (shadowing). +LocalFunction3Test: Fail # Bug 4202974. + +FieldNegativeTest: Fail # Bug 4207626. +FunctionTypeAliasNegativeTest: Fail # Bug 5231617. +ExampleConstructorTest: Fail # Bug 4205742. +CTConstTest: Fail # Bug 4510015. +Constructor2NegativeTest: Fail # Bug 4208594. +ClassOverrideNegativeTest: Fail # Bug 4205768. +BitOperationsTest: Fail # Uses bignums. +ListLiteral3Test: Fail # Bug 4510015. +ListTest: Fail # Bug 5146975. +StackTraceTest: Fail # Bug 4971920. +ExpectTest: Fail # Missing extensions to class Expect. +DivByZeroTest: Fail # Bug 5184183 +OverrideFieldMethod1NegativeTest: Fail # Bug 5215249 +OverrideFieldMethod2NegativeTest: Fail # Bug 5215249 +OverrideFieldMethod3NegativeTest: Fail # Bug 5215249 +OverrideFieldMethod4NegativeTest: Fail # Bug 5215249 +OverrideFieldMethod5NegativeTest: Fail # Bug 5215249 +OverrideFieldMethod6NegativeTest: Fail # Bug 5215249 +DeoptimizationTest: Fail # Bug 4254120 +CharEscapeTest: Fail +FunctionTypeParameter2NegativeTest: Fail # Bug 4568007 + +# The following tests use missing error classes. Bug 4385894. +TypeTest: Fail # Uses TypeError class. +AssertTest: Fail # Uses AssertError class. + +ThirdTest: Fail # Bug 5339586 + + + +[ $arch == chromium ] +ApplicationTest: Fail # Bug 5145731 +TopLevelMultipleFilesTest: Fail # Bug 5145731 +TopLevelNonPrefixedLibraryTest: Fail # Bug 5145731 +TopLevelPrefixedLibraryTest: Fail # Bug 5145731 +TopLevelEntryTest: Fail # Bug 5145731 +PrivateTest: Fail # Bug 5145731 +Private3Test: Fail # Bug 5145731 + +[ $arch == chromium && $mode == release ] +Instanceof2Test: Fail, Pass # Bug 5275232 + + +[ $arch == ia32 ] + +[ $arch == dartium ] +Prefix1NegativeTest: Skip # Bug 5072252 +Prefix2NegativeTest: Skip # Bug 5072252 +Prefix3NegativeTest: Skip # Bug 5072252 +Prefix4NegativeTest: Skip # Bug 5072252 +Prefix5NegativeTest: Skip # Bug 5072252 +Prefix6NegativeTest: Skip # Bug 5072252 +Prefix7NegativeTest: Skip # Bug 5072252 +Prefix8NegativeTest: Skip # Bug 5072252 +Prefix9NegativeTest: Skip # Bug 5072252 +Prefix10NegativeTest: Skip # Bug 5072252 +Prefix11NegativeTest: Skip # Bug 5072252 +Prefix12NegativeTest: Skip # Bug 5072252 +PrefixTest: Skip # Bug 5072252 +Prefix10Test: Skip # Bug 5072252 +Prefix11Test: Skip # Bug 5072252 +Prefix12Test: Skip # Bug 5072252 +LibraryPrefixesTest: Skip # Bug 5072252 +TopLevelNonPrefixedLibraryTest: Skip # Bug 5072252 +ApplicationTest: Fail # Bug 5072252 +TopLevelEntryTest: Fail # Bug 5072252 +TopLevelMultipleFilesTest: Fail # Bug 5072252 +AbstractStaticNegativeTest: Skip # Bug 5408067 + +# print and println are not implemented yet +Throw5Test: Skip +ExceptionTest: Skip +MathTest: Skip +ExpectTest: Skip +StringInterpolateTest: Skip +ExecuteFinally7Test: Skip +SavannahTest: Skip +Throw2Test: Skip +Throw3Test: Skip +HelloDartTest: Skip +ThrowTest: Skip +TryCatch3Test: Skip +StackTraceTest: Skip +Throw1Test: Skip +RegExp2Test: Skip +FannkuchTest: Skip +RichardsTest: Skip +Throw6Test: Skip +RegEx2Test: Skip +DivByZeroTest: Skip +UnboundGetterTest: Skip +NativeTest: Skip +Throw4Test: Skip +ImplicitClosure1Test: Skip +Private2Test: Skip + +TypedMessageTest: Skip # Bug 5246195 + +# Expect is not available +Private3Test: Skip +Library1Test :Skip + +[ $arch == dartium || $arch == chromium ] +PrivateTest: Fail # Bug 5382463 +HelloScriptTest: Fail # Bug 5072252 +ImportCoreImplNoPrefixTest: Fail # Bug 5382463 +ImportCoreNoPrefixTest: Fail # Bug 5382463 + +# Bug 5293748 +GenericInstanceofTest: Skip +GenericInheritanceTest: Skip +GenericParameterizedExtendsTest: Skip +MultiPassTest: Skip +OverriddenNoSuchMethodTest: Skip +BinaryTreesTest: Skip +NBodyTest: Skip +Library1Test: Skip +ManyGenericInstanceofTest: Skip +DeltaBlueTest: Skip +MandelbrotTest: Skip +DeltaBlueClosureTest: Skip +ManyOverriddenNoSuchMethodTest: Skip +MultiPass2Test: Skip +RichardsTest: Skip + +[ $arch == x64 ] +*: Skip + +[ $arch == simarm ] +*: Skip + +[ $arch == arm ] +*: Skip diff --git a/tests/language/src/AbstractStaticNegativeTest.dart b/tests/language/src/AbstractStaticNegativeTest.dart new file mode 100644 index 00000000000..e13f70136ea --- /dev/null +++ b/tests/language/src/AbstractStaticNegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + abstract static foo(); // Illegal. +} + +main() { + A.foo(); +} diff --git a/tests/language/src/AckermannTest.dart b/tests/language/src/AckermannTest.dart new file mode 100644 index 00000000000..4d95f810c08 --- /dev/null +++ b/tests/language/src/AckermannTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart version of two-argument Ackermann-Peter function. + +class AckermannTest { + static ack(m, n) { + return m == 0 ? + n + 1 : ((n == 0) ? + ack(m - 1, 1) : ack(m - 1, ack(m, n - 1))); + } + + static testMain() { + Expect.equals(253, ack(3, 5)); + } +} + +main() { + AckermannTest.testMain(); +} diff --git a/tests/language/src/AllocateLargeObject.dart b/tests/language/src/AllocateLargeObject.dart new file mode 100644 index 00000000000..54347cedb61 --- /dev/null +++ b/tests/language/src/AllocateLargeObject.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + int a; + double d1; + double d2; + double d3; + double d4; + double d5; + double d6; + double d7; + double d8; + double d9; + double d10; + double d11; + double d12; + double d13; + double d14; + static var s; + + static foo() { + return s; + } + + A(this.a) { } + + value() { + return a + foo(); + } +} + +class AllocateLargeObject { + static testMain() { + var a = new A(1); + A.s = 4; + Expect.equals(5, a.value()); + } +} + +main() { + AllocateLargeObject.testMain(); +} diff --git a/tests/language/src/AllocateTest.dart b/tests/language/src/AllocateTest.dart new file mode 100644 index 00000000000..db621672d54 --- /dev/null +++ b/tests/language/src/AllocateTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +class MyAllocate { + const MyAllocate([int value = 0]) : value_ = value; + int getValue() { return value_; } + final int value_; +} + +class AllocateTest { + static testMain() { + Expect.equals(900, (new MyAllocate(900)).getValue()); + } +} + +main() { + AllocateTest.testMain(); +} diff --git a/tests/language/src/ApplicationNegativeTest.dart b/tests/language/src/ApplicationNegativeTest.dart new file mode 100644 index 00000000000..1759facb910 --- /dev/null +++ b/tests/language/src/ApplicationNegativeTest.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source('FailingMain.dart'); diff --git a/tests/language/src/ApplicationTest.dart b/tests/language/src/ApplicationTest.dart new file mode 100644 index 00000000000..1418075721c --- /dev/null +++ b/tests/language/src/ApplicationTest.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source('EmptyMain.dart'); diff --git a/tests/language/src/ArithmeticTest.dart b/tests/language/src/ArithmeticTest.dart new file mode 100644 index 00000000000..564a501effb --- /dev/null +++ b/tests/language/src/ArithmeticTest.dart @@ -0,0 +1,395 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test arithmetic operations. + +class ArithmeticTest { + + static bool exceptionCaughtParseInt(String s) { + try { + Math.parseInt(s); + return false; + } catch (BadNumberFormatException e) { + return true; + } + } + + static bool exceptionCaughtParseDouble(String s) { + try { + Math.parseDouble(s); + return false; + } catch (BadNumberFormatException e) { + return true; + } + } + + static bool toIntThrowsBadNumberFormatException(String str) { + // No exception allowed for parse double. + double d = Math.parseDouble(str); + try { + var a = d.toInt(); + return false; + } catch (BadNumberFormatException e) { + return true; + } + } + + static testMain() { + var a = 22; + var b = 4; + // Smi & smi. + Expect.equals(26, a + b); + Expect.equals(18, a - b); + Expect.equals(88, a * b); + Expect.equals(5, a ~/ b); + Expect.equals(5.5, a / b); + Expect.equals(2.0, 10 / 5); + Expect.equals(2, a % b); + Expect.equals(2, a.remainder(b)); + a = 22; + b = 4.0; + // Smi & double. + Expect.equals(26.0, a + b); + Expect.equals(18.0, a - b); + Expect.equals(88.0, a * b); + Expect.equals(5.0, a ~/ b); + Expect.equals(5.5, a / b); + Expect.equals(2.0, a % b); + Expect.equals(2.0, a.remainder(b)); + a = 22.0; + b = 4; + // Double & smi. + Expect.equals(26.0, a + b); + Expect.equals(18.0, a - b); + Expect.equals(88.0, a * b); + Expect.equals(5.0, a ~/ b); + Expect.equals(5.5, a / b); + Expect.equals(2.0, a % b); + Expect.equals(2.0, a.remainder(b)); + a = 22.0; + b = 4.0; + // Double & double. + Expect.equals(26.0, a + b); + Expect.equals(18.0, a - b); + Expect.equals(88.0, a * b); + Expect.equals(5.0, a ~/ b); + Expect.equals(5.5, a / b); + Expect.equals(2.0, a % b); + Expect.equals(2.0, a.remainder(b)); + + // Special int operations. + Expect.equals(2, (2).floor()); + Expect.equals(2, (2).ceil()); + Expect.equals(2, (2).round()); + Expect.equals(2, (2).truncate()); + + Expect.equals(-2, (-2).floor()); + Expect.equals(-2, (-2).ceil()); + Expect.equals(-2, (-2).round()); + Expect.equals(-2, (-2).truncate()); + + // Note that this number fits into 53 bits of a double. + int big = 123456789012345; + + Expect.equals(big, big.floor()); + Expect.equals(big, big.ceil()); + Expect.equals(big, big.round()); + Expect.equals(big, big.truncate()); + big = -big; + Expect.equals(big, big.floor()); + Expect.equals(big, big.ceil()); + Expect.equals(big, big.round()); + Expect.equals(big, big.truncate()); + + // Test if double is contagious. The assignment will check the type. + { double d = 1 + 1.0; } + { double d = 1.0 + 1; } + { double d = 1 * 1.0; } + { double d = 0 * 1.0; } + { double d = 1.0 * 0; } + { double d = 1 / 1.0; } + { double d = 1.0 / 0; } + { double d = 1 - 1.0; } + { double d = 1.0 - 1; } + { double d = big * 1.0; } + { double d = 1.0 * big; } + + // Reset big to positive value. + big = 123456789012345; + // -- isNegative --. + // Smi. + Expect.equals(false, (0).isNegative()); + Expect.equals(false, (1).isNegative()); + Expect.equals(true, (-1).isNegative()); + // Big. + Expect.equals(false, big.isNegative()); + Expect.equals(true, (-big).isNegative()); + // Double. + // TODO(srdjan): enable the following test once isNegative works. + // Expect.equals(true, (-0.0).isNegative()); + Expect.equals(false, (0.0).isNegative()); + Expect.equals(false, (2.0).isNegative()); + Expect.equals(true, (-2.0).isNegative()); + + // Constants. + final nan = 0.0/0.0; + final infinity = 1.0/0.0; + + // -- isInfinite --. + // Smi. + Expect.equals(false, (0).isInfinite()); + Expect.equals(false, (1).isInfinite()); + Expect.equals(false, (-1).isInfinite()); + // Big. + Expect.equals(false, big.isInfinite()); + Expect.equals(false, (-big).isInfinite()); + // Double. + Expect.equals(false, (0.0).isInfinite()); + Expect.equals(true, infinity.isInfinite()); + Expect.equals(true, (-infinity).isInfinite()); + Expect.equals(false, (12.0).isInfinite()); + Expect.equals(false, (-12.0).isInfinite()); + Expect.equals(false, nan.isInfinite()); + + // -- isNaN --. + // Smi. + Expect.equals(false, (0).isNaN()); + Expect.equals(false, (1).isNaN()); + Expect.equals(false, (-1).isNaN()); + // Big. + Expect.equals(false, big.isNaN()); + Expect.equals(false, (-big).isNaN()); + // Double. + Expect.equals(true, nan.isNaN()); + Expect.equals(false, (12.0).isNaN()); + Expect.equals(false, infinity.isNaN()); + + // -- abs --. + // Smi. + Expect.equals(0, (0).abs()); + Expect.equals(2, (2).abs()); + Expect.equals(2, (-2).abs()); + // Big. + Expect.equals(big, big.abs()); + Expect.equals(big, (-big).abs()); + // Double. + Expect.equals(false, (0.0).abs().isNegative()); + Expect.equals(false, (-0.0).abs().isNegative()); + Expect.equals(2.0, (2.0).abs()); + Expect.equals(2.0, (-2.0).abs()); + + // -- ceil --. + // Smi. + Expect.equals(0, (0).ceil()); + Expect.equals(1, (1).ceil()); + Expect.equals(-1, (-1).ceil()); + // Big. + Expect.equals(big, big.ceil()); + Expect.equals(-big, (-big).ceil()); + // Double. + Expect.equals(0.0, (0.0).ceil()); + Expect.equals(false, (0.0).ceil().isNegative()); + Expect.equals(1.0, (0.1).ceil()); + Expect.equals(-0.0, (-0.0).ceil()); + Expect.equals(-0.0, (-0.3).ceil()); + // TODO(srdjan): enable the following tests once isNegative works. + // Expect.equals(true, (-0.0).ceil().isNegative()); + // Expect.equals(true, (-0.3).ceil().isNegative()); + Expect.equals(3.0, (2.1).ceil()); + Expect.equals(-2.0, (-2.1).ceil()); + + // -- floor --. + // Smi. + Expect.equals(0, (0).floor()); + Expect.equals(1, (1).floor()); + Expect.equals(-1, (-1).floor()); + // Big. + Expect.equals(big, big.floor()); + Expect.equals(-big, (-big).floor()); + // Double. + Expect.equals(0.0, (0.0).floor()); + Expect.equals(0.0, (0.1).floor()); + Expect.equals(false, (0.0).floor().isNegative()); + Expect.equals(false, (0.1).floor().isNegative()); + Expect.equals(-0.0, (-0.0).floor()); + // TODO(srdjan): enable the following tests once isNegative works. + // Expect.equals(true, (-0.0).floor().isNegative()); + Expect.equals(-1.0, (-0.1).floor()); + Expect.equals(2.0, (2.1).floor()); + Expect.equals(-3.0, (-2.1).floor()); + + // -- truncate --. + // Smi. + Expect.equals(0, (0).truncate()); + Expect.equals(1, (1).truncate()); + Expect.equals(-1, (-1).truncate()); + // Big. + Expect.equals(big, big.truncate()); + Expect.equals(-big, (-big).truncate()); + // Double. + Expect.equals(0.0, (0.0).truncate()); + Expect.equals(0.0, (0.1).truncate()); + Expect.equals(false, (0.0).truncate().isNegative()); + Expect.equals(false, (0.1).truncate().isNegative()); + Expect.equals(-0.0, (-0.0).truncate()); + Expect.equals(-0.0, (-0.3).truncate()); + // TODO(srdjan): enable the following tests once isNegative works. + // Expect.equals(true, (-0.0).truncate().isNegative()); + // Expect.equals(true, (-0.3).truncate().isNegative()); + Expect.equals(2.0, (2.1).truncate()); + Expect.equals(-2.0, (-2.1).truncate()); + + double b1 = (1234567890123.0).truncate(); + double b2 = (1234567890124.0).truncate(); + Expect.equals(b2, b1 + 1.0); + + // -- round --. + // Smi. + Expect.equals(0, (0).round()); + Expect.equals(1, (1).round()); + Expect.equals(-1, (-1).round()); + // Big. + Expect.equals(big, big.round()); + Expect.equals(-big, (-big).round()); + // Double. + Expect.equals(3.0, (2.6).round()); + Expect.equals(-3.0, (-2.6).round()); + Expect.equals(0.0, (0.0).round()); + Expect.equals(0.0, (0.1).round()); + Expect.equals(false, (0.0).round().isNegative()); + Expect.equals(false, (0.1).round().isNegative()); + Expect.equals(-0.0, (-0.0).round()); + Expect.equals(-0.0, (-0.3).round()); + Expect.equals(2.0, (2.1).round()); + Expect.equals(-2.0, (-2.1).round()); + Expect.equals(1.0, (0.5).round()); + // TODO(floitsch): enable or adapt test, once we reached conclusion on + // b/4539188. + // Expect.equals(-0.0, (-0.5).round()); + // TODO(srdjan): enable the following tests once isNegative works. + // Expect.equals(true, (-0.0).round().isNegative()); + // Expect.equals(true, (-0.3).round().isNegative()); + // Expect.equals(true, (-0.5).round().isNegative()); + Expect.equals(2.0, (1.5).round()); + // TODO(floitsch): enable or adapt test, once we reached conclusion on + // b/4539188. + // Expect.equals(-1.0, (-1.5).round()); + Expect.equals(1.0, (0.99).round()); + + // -- toInt --. + // Smi. + Expect.equals(0, (0).toInt()); + Expect.equals(1, (1).toInt()); + Expect.equals(-1, (-1).toInt()); + // Type checks. + { int i = (0).toInt(); } + { int i = (1).toInt(); } + { int i = (-1).toInt(); } + // Big. + Expect.equals(big, big.toInt()); + Expect.equals(-big, (-big).toInt()); + { int i = big.toInt(); } + { int i = (-big).toInt(); } + // Double. + Expect.equals(1234567890123, (1234567890123.0).toInt()); + Expect.equals(-1234567890123, (-1234567890123.0).toInt()); + { int i = (1234567890123.0).toInt(); } + { int i = (-1234567890123.0).toInt(); } + // 32bit Smi border cases. + Expect.equals(-1073741824, (-1073741824.0).toInt()); + Expect.equals(-1073741825, (-1073741825.0).toInt()); + Expect.equals(1073741823, (1073741823.0).toInt()); + Expect.equals(1073741824, (1073741824.0).toInt()); + { int i = (-1073741824.0).toInt(); } + { int i = (-1073741825.0).toInt(); } + { int i = (1073741823.0).toInt(); } + { int i = (1073741824.0).toInt(); } + + // -- toDouble --. + // Smi. + Expect.equals(0.0, (0).toDouble()); + Expect.equals(1.0, (1).toDouble()); + Expect.equals(-1.0, (-1).toDouble()); + // Type checks. + { double d = (0).toDouble(); } + { double d = (1).toDouble(); } + { double d = (-1).toDouble(); } + // Big. + Expect.equals(big, big.toInt()); + Expect.equals(-big, (-big).toInt()); + { int i = big.toInt(); } + { int i = (-big).toInt(); } + + // Math functions. + Expect.equals(2.0, Math.sqrt(4.0)); + Expect.equals(1.0, Math.sin(3.14159265 / 2.0)); + Expect.equals(-1.0, Math.cos(3.14159265)); + + Expect.equals(12, Math.parseInt("12")); + Expect.equals(-12, Math.parseInt("-12")); + Expect.equals(12345678901234567890, + Math.parseInt("12345678901234567890")); + Expect.equals(-12345678901234567890, + Math.parseInt("-12345678901234567890")); + // Type checks. + { int i = Math.parseInt("12"); } + { int i = Math.parseInt("-12"); } + { int i = Math.parseInt("12345678901234567890"); } + { int i = Math.parseInt("-12345678901234567890"); } + + Expect.equals(1.2, Math.parseDouble("1.2")); + Expect.equals(-1.2, Math.parseDouble("-1.2")); + // Type checks. + { double d = Math.parseDouble("1.2"); } + { double d = Math.parseDouble("-1.2"); } + { double d = Math.parseDouble("0"); } + + // Random + { double d = Math.random(); } + + Expect.equals(false, exceptionCaughtParseInt("22")); + Expect.equals(true, exceptionCaughtParseInt("alpha")); + Expect.equals(true, exceptionCaughtParseInt("-alpha")); + Expect.equals(false, exceptionCaughtParseDouble("22.2")); + Expect.equals(true, exceptionCaughtParseDouble("alpha")); + Expect.equals(true, exceptionCaughtParseDouble("-alpha")); + + Expect.equals(false, Math.parseDouble("1.2").isNaN()); + Expect.equals(false, Math.parseDouble("1.2").isInfinite()); + + Expect.equals(true, Math.parseDouble("NaN").isNaN()); + Expect.equals(true, Math.parseDouble("Infinity").isInfinite()); + Expect.equals(true, Math.parseDouble("-Infinity").isInfinite()); + + Expect.equals(false, Math.parseDouble("NaN").isNegative()); + Expect.equals(false, Math.parseDouble("Infinity").isNegative()); + Expect.equals(true, Math.parseDouble("-Infinity").isNegative()); + + Expect.equals("NaN", Math.parseDouble("NaN").toString()); + Expect.equals("Infinity", Math.parseDouble("Infinity").toString()); + Expect.equals("-Infinity", Math.parseDouble("-Infinity").toString()); + + Expect.equals(false, toIntThrowsBadNumberFormatException("1.2")); + Expect.equals(true, toIntThrowsBadNumberFormatException("Infinity")); + Expect.equals(true, toIntThrowsBadNumberFormatException("-Infinity")); + Expect.equals(true, toIntThrowsBadNumberFormatException("NaN")); + + // Min/max + Expect.equals(1, Math.min(1, 12)); + Expect.equals(12, Math.max(1, 12)); + Expect.equals(1.0, Math.min(1.0, 12.0)); + Expect.equals(12.0, Math.max(1.0, 12.0)); + Expect.equals(false, 1.0 < Math.min(1.0, 12.0)); + Expect.equals(true, 1.0 < Math.max(1.0, 12.0)); + + // Hashcode + Expect.equals(false, (3.4).hashCode() == (1.2).hashCode()); + Expect.equals(true, (1.2).hashCode() == (1.2).hashCode()); + Expect.equals(false, (3).hashCode() == (1).hashCode()); + Expect.equals(true, (10).hashCode() == (10).hashCode()); + } +} + +main() { + ArithmeticTest.testMain(); +} diff --git a/tests/language/src/AssertKeywordNegativeTest.dart b/tests/language/src/AssertKeywordNegativeTest.dart new file mode 100644 index 00000000000..b7b2a911330 --- /dev/null +++ b/tests/language/src/AssertKeywordNegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class AssertKeywordNegativeTest { + + static void testMain() { + assert(true); + "assert"(true); + } + +} + +main() { + AssertKeywordNegativeTest.testMain(); +} diff --git a/tests/language/src/AssertTest.dart b/tests/language/src/AssertTest.dart new file mode 100644 index 00000000000..ec00d8744a5 --- /dev/null +++ b/tests/language/src/AssertTest.dart @@ -0,0 +1,54 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_asserts +// +// Dart test program testing assert statements. + +class AssertTest { + static test() { + int i = 0; + try { + assert(false); + } catch (AssertError error) { + i = 1; + Expect.equals("false", error.failedAssertion); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("AssertTest.dart", subs); + Expect.equals(12, error.line); + Expect.equals(14, error.column); + } + return i; + } + static testClosure() { + int i = 0; + try { + assert(() => false); + } catch (AssertError error) { + i = 1; + Expect.equals("() => false", error.failedAssertion); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("AssertTest.dart", subs); + Expect.equals(30, error.line); + Expect.equals(14, error.column); + } + return i; + } + + static testMain() { + Expect.equals(1, test()); + Expect.equals(1, testClosure()); + } +} + +main() { + AssertTest.testMain(); +} diff --git a/tests/language/src/AssignInstanceMethodNegativeTest.dart b/tests/language/src/AssignInstanceMethodNegativeTest.dart new file mode 100644 index 00000000000..f426fca7713 --- /dev/null +++ b/tests/language/src/AssignInstanceMethodNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + A() {} + imethod() { return 0; } +} + +class AssignInstanceMethodNegativeTest { + + static testMain() { + var a = new A(); + // Illegal, can't change a member method + a.imethod = () { return 1; }; + } +} + +main() { + AssignInstanceMethodNegativeTest.testMain(); +} diff --git a/tests/language/src/AssignOpTest.dart b/tests/language/src/AssignOpTest.dart new file mode 100644 index 00000000000..248aae9a278 --- /dev/null +++ b/tests/language/src/AssignOpTest.dart @@ -0,0 +1,76 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing assign operators. + + +class AssignOpTest { + AssignOpTest() {} + + static testMain() { + var b = 0; + b += 1; + Expect.equals(1, b); + b *= 5; + Expect.equals(5, b); + b -= 1; + Expect.equals(4, b); + b ~/= 2; + Expect.equals(2, b); + + f = 0; + f += 1; + Expect.equals(1, f); + f *= 5; + Expect.equals(5, f); + f -= 1; + Expect.equals(4, f); + f ~/= 2; + Expect.equals(2, f); + f /= 4; + Expect.equals(.5, f); + + AssignOpTest.f = 0; + AssignOpTest.f += 1; + Expect.equals(1, AssignOpTest.f); + AssignOpTest.f *= 5; + Expect.equals(5, AssignOpTest.f); + AssignOpTest.f -= 1; + Expect.equals(4, AssignOpTest.f); + AssignOpTest.f ~/= 2; + Expect.equals(2, AssignOpTest.f); + AssignOpTest.f /= 4; + Expect.equals(.5, f); + + var o = new AssignOpTest(); + o.instf = 0; + o.instf += 1; + Expect.equals(1, o.instf); + o.instf *= 5; + Expect.equals(5, o.instf); + o.instf -= 1; + Expect.equals(4, o.instf); + o.instf ~/= 2; + Expect.equals(2, o.instf); + o.instf /= 4; + Expect.equals(.5, o.instf); + + var x = 0xFF; + x >>= 3; + Expect.equals(0x1F, x); + x <<= 3; + Expect.equals(0xF8, x); + x |= 0xF00; + Expect.equals(0xFF8, x); + x &=0xF0; + Expect.equals(0xF0, x); + x ^=0x11; + Expect.equals(0xE1, x); + } + + static var f; + var instf; +} +main() { + AssignOpTest.testMain(); +} diff --git a/tests/language/src/BadInitializer1NegativeTest.dart b/tests/language/src/BadInitializer1NegativeTest.dart new file mode 100644 index 00000000000..efabb93cbb2 --- /dev/null +++ b/tests/language/src/BadInitializer1NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Variable initializer must not reference the initialized variable. + +class BadInitializer1NegativeTest { + static testMain() { + final List elems = const [ + const [1, 2.0, true, false, 0xffffffffff, elems], "a", "b"]; + } +} + +main() { + BadInitializer1NegativeTest.testMain(); +} diff --git a/tests/language/src/BadInitializer2NegativeTest.dart b/tests/language/src/BadInitializer2NegativeTest.dart new file mode 100644 index 00000000000..c554002a12f --- /dev/null +++ b/tests/language/src/BadInitializer2NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Variable initializer must not reference the initialized variable. + +class BadInitializer2NegativeTest { + static testMain() { + var foo = (int n) { + if (n == 0) { + return 0; + } else { + return 1 + foo(n - 1); // <-- self-reference to closure foo. + } + }; + Expect.equals(4, foo(4)); + } +} + +main() { + BadInitializer2NegativeTest.testMain(); +} diff --git a/tests/language/src/BadNamedConstructorNegativeTest.dart b/tests/language/src/BadNamedConstructorNegativeTest.dart new file mode 100644 index 00000000000..a28b37d9b1e --- /dev/null +++ b/tests/language/src/BadNamedConstructorNegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class BadNamedConstructorNegativeTest { + A.foo() {} +} + +main() { + BadNamedConstructorNegativeTest.testMain(); +} diff --git a/tests/language/src/BadNamedParameters2Test.dart b/tests/language/src/BadNamedParameters2Test.dart new file mode 100644 index 00000000000..c8f0dd41468 --- /dev/null +++ b/tests/language/src/BadNamedParameters2Test.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing bad named parameters. + + +class BadNamedParameters2Test { + + int foo(int a) { + // Although no optional named parameters are declared, we must check that + // no named arguments are passed in, either here or in the resolving stub. + return a; + } + + static testMain() { + BadNamedParameters2Test np = new BadNamedParameters2Test(); + + // Verify that NoSuchMethod is called after an error is detected. + bool caught; + try { + caught = false; + np.foo(b:25); // No formal parameter named b. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + } +} + +main() { + BadNamedParameters2Test.testMain(); +} diff --git a/tests/language/src/BadNamedParametersTest.dart b/tests/language/src/BadNamedParametersTest.dart new file mode 100644 index 00000000000..16cbb91015c --- /dev/null +++ b/tests/language/src/BadNamedParametersTest.dart @@ -0,0 +1,62 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing bad named parameters. + + +class BadNamedParametersTest { + + int f42(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + int f52(int a, [int b = 20, int c, int d = 40]) { + return 100*(100*(100*a + b) + (c == null ? 0 : c)) + d; + } + + static testMain() { + BadNamedParametersTest np = new BadNamedParametersTest(); + + // Verify that NoSuchMethod is called after an error is detected. + bool caught; + try { + caught = false; + np.f42(10, 25, b:25); // Parameter b passed twice. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + try { + caught = false; + np.f42(10, 25, x:99); // Parameter x does not exist. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + try { + caught = false; + np.f52(10, b:25, b1:99, c:35); // Parameter b1 does not exist. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + try { + caught = false; + np.f42(10, 20, 30, 40); // Too many parameters. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + try { + caught = false; + np.f42(b:25); // Too few parameters. + } catch (NoSuchMethodException e) { + caught = true; + } + Expect.equals(true, caught); + } +} + +main() { + BadNamedParametersTest.testMain(); +} diff --git a/tests/language/src/BitOperationsTest.dart b/tests/language/src/BitOperationsTest.dart new file mode 100644 index 00000000000..b8199dab381 --- /dev/null +++ b/tests/language/src/BitOperationsTest.dart @@ -0,0 +1,92 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing bitwise operations. + +class BitOperationsTest { + static testMain() { + Expect.equals(3, (3 & 7)); + Expect.equals(7, (3 | 7)); + Expect.equals(4, (3 ^ 7)); + Expect.equals(25, (100 >> 2)); + Expect.equals(400, (100 << 2)); + Expect.equals(-25, (-100 >> 2)); + Expect.equals(-101, ~100); + Expect.equals(0x10000000000000000, 1 << 64); + Expect.equals(-0x10000000000000000, -1 << 64); + Expect.equals(0, ~-1); + Expect.equals(-1, ~0); + + Expect.equals(0, 1 >> 160); + Expect.equals(-1, -1 >> 160); + + Expect.equals(0x100000000000000001, + 0x100000000000000001 & 0x100000100F00000001); + Expect.equals(0x1, 0x1 & 0x100000100F00000001); + Expect.equals(0x1, 0x100000100F00000001 & 0x1); + + Expect.equals(0x100000100F00000001, + 0x100000000000000001 | 0x100000100F00000001); + Expect.equals(0x100000100F00000011, 0x11 | 0x100000100F00000001); + Expect.equals(0x100000100F00000011, 0x100000100F00000001 | 0x11); + + Expect.equals(0x0F000F00000000000000, + 0x0F00F00000000000001 ^ 0xFF00000000000000001); + Expect.equals(0x31, 0xF00F00000000000001 ^ 0xF00F00000000000030); + Expect.equals(0xF00F00000000000031, 0xF00F00000000000001 ^ 0x30); + Expect.equals(0xF00F00000000000031, 0x30 ^ 0xF00F00000000000001); + + Expect.equals(0xF0000000000000000F, 0xF0000000000000000F7 >> 4); + Expect.equals(15, 0xF00000000 >> 32); + Expect.equals(1030792151040, 16492674416655 >> 4); + + Expect.equals(0xF0000000000000000F0, 0xF0000000000000000F << 4); + Expect.equals(0xF00000000, 15 << 32); + + TestNegativeValueShifts(); + TestPositiveValueShifts(); + TestNoMaskingOfShiftCount(); + } + + static void TestNegativeValueShifts() { + for (int value = 0; value > -100; value--) { + for (int i = 0; i < 300; i++) { + int b = (value << i) >> i; + Expect.equals(value, b); + } + } + } + + static void TestPositiveValueShifts() { + for (int value = 0; value < 100; value++) { + for (int i = 0; i < 300; i++) { + int b = (value << i) >> i; + Expect.equals(value, b); + } + } + } + + static void TestNoMaskingOfShiftCount() { + // Shifts which would behave differently if shift count was masked into a + // range. + Expect.equals(0, 0 >> 256); + Expect.equals(0, 1 >> 256); + Expect.equals(0, 2 >> 256); + Expect.equals(0, ShiftRight(0, 256)); + Expect.equals(0, ShiftRight(1, 256)); + Expect.equals(0, ShiftRight(2, 256)); + + for (int shift = 1; shift <= 256; shift++) { + Expect.equals(0, ShiftRight(1, shift)); + Expect.equals(-1, ShiftRight(-1, shift)); + Expect.equals(true, ShiftLeft(1, shift) > ShiftLeft(1, shift - 1)); + } + } + + static int ShiftLeft(int a, int b) { return a << b; } + static int ShiftRight(int a, int b) { return a >> b; } +} + +main() { + BitOperationsTest.testMain(); +} diff --git a/tests/language/src/BoolTest.dart b/tests/language/src/BoolTest.dart new file mode 100644 index 00000000000..c13fbf649ca --- /dev/null +++ b/tests/language/src/BoolTest.dart @@ -0,0 +1,115 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing basic boolean properties. + +class BoolTest { + static void testEquality() { + Expect.equals(true, true); + Expect.equals(false, false); + Expect.equals(true, true === true); + Expect.equals(false, true === false); + Expect.equals(true, false === false); + Expect.equals(false, false === true); + Expect.equals(false, true !== true); + Expect.equals(true, true !== false); + Expect.equals(false, false !== false); + Expect.equals(true, false !== true); + Expect.equals(true, true == true); + Expect.equals(false, true == false); + Expect.equals(true, false == false); + Expect.equals(false, false == true); + Expect.equals(false, true != true); + Expect.equals(true, true != false); + Expect.equals(false, false != false); + Expect.equals(true, false != true); + Expect.equals(true, true === (true == true)); + Expect.equals(true, false === (true == false)); + Expect.equals(true, true === (false == false)); + Expect.equals(true, false === (false == true)); + Expect.equals(false, true !== (true == true)); + Expect.equals(false, false !== (true == false)); + Expect.equals(false, true !== (false == false)); + Expect.equals(false, false !== (false == true)); + Expect.equals(false, false === (true == true)); + Expect.equals(false, true === (true == false)); + Expect.equals(false, false === (false == false)); + Expect.equals(false, true === (false == true)); + Expect.equals(true, false !== (true == true)); + Expect.equals(true, true !== (true == false)); + Expect.equals(true, false !== (false == false)); + Expect.equals(true, true !== (false == true)); + // Expect.equals could rely on a broken boolean equality. + if (true == false) { + throw "Expect.equals broken"; + } + if (false == true) { + throw "Expect.equals broken"; + } + if (true === false) { + throw "Expect.equals broken"; + } + if (false === true) { + throw "Expect.equals broken"; + } + if (true == true) { + } else { + throw "Expect.equals broken"; + } + if (false == false) { + } else { + throw "Expect.equals broken"; + } + if (true === true) { + } else { + throw "Expect.equals broken"; + } + if (false === false) { + } else { + throw "Expect.equals broken"; + } + if (true != false) { + } else { + throw "Expect.equals broken"; + } + if (false != true) { + } else { + throw "Expect.equals broken"; + } + if (true !== false) { + } else { + throw "Expect.equals broken"; + } + if (false !== true) { + } else { + throw "Expect.equals broken"; + } + if (true != true) { + throw "Expect.equals broken"; + } + if (false != false) { + throw "Expect.equals broken"; + } + if (true !== true) { + throw "Expect.equals broken"; + } + if (false !== false) { + throw "Expect.equals broken"; + } + } + + static void testToString() { + Expect.equals("true", true.toString()); + Expect.equals("false", false.toString()); + } + + static void testMain() { + testEquality(); + testToString(); + } +} + +main() { + BoolTest.testMain(); +} diff --git a/tests/language/src/BootstrapTest.dart b/tests/language/src/BootstrapTest.dart new file mode 100644 index 00000000000..444e5ed8e75 --- /dev/null +++ b/tests/language/src/BootstrapTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing binary operations. +// VMOptions=--verify_implements + +class BootstrapTest { + + static testMain() { + var obj = new Object(); + + return obj; + } + +} + +main() { + BootstrapTest.testMain(); +} diff --git a/tests/language/src/BranchesTest.dart b/tests/language/src/BranchesTest.dart new file mode 100644 index 00000000000..d893cbcd366 --- /dev/null +++ b/tests/language/src/BranchesTest.dart @@ -0,0 +1,156 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for branches. Make sure that shortcuts work, even if they have +// to jump over several expressions. + +class BranchesTest { + static bool f() { + Expect.equals("Never reached", 0); + return true; + } + + static void testMain() { + int checkPointCounter = 1; + int checkPoint1 = 0; + int checkPoint2 = 0; + int checkPoint3 = 0; + int checkPoint4 = 0; + int checkPoint5 = 0; + int checkPoint6 = 0; + int i = 0; + for (int i = 0; i < 2; i++) { + if (i == 0) { + checkPoint1 += checkPointCounter++; + if (true || // Test branch-if-true. + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f() || + f()) { + checkPoint2 += checkPointCounter++; + } + } else { // Test branch (jumping over the else branch). + checkPoint3 += checkPointCounter++; + if (false) { + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + checkPoint4 = checkPointCounter++; // Never reached. + } + } + checkPoint5 += checkPointCounter++; + } + checkPoint6 += checkPointCounter++; + Expect.equals(1, checkPoint1); + Expect.equals(2, checkPoint2); + Expect.equals(4, checkPoint3); + Expect.equals(0, checkPoint4); + Expect.equals(8, checkPoint5); + Expect.equals(6, checkPoint6); + } +} + +main() { + BranchesTest.testMain(); +} diff --git a/tests/language/src/BreakTest.dart b/tests/language/src/BreakTest.dart new file mode 100644 index 00000000000..68cd63c3151 --- /dev/null +++ b/tests/language/src/BreakTest.dart @@ -0,0 +1,51 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for breaks in for, do/while and while loops. + +class BreakTest { + static testMain() { + int i; + int forCounter = 0; + for (i = 0; i < 10; i++) { + forCounter++; + if (i > 3) break; + } + Expect.equals(5, forCounter); + Expect.equals(4, i); + + i = 0; + int doWhileCounter = 0; + do { + i++; + doWhileCounter++; + if (i > 3) break; + } while (i < 10); + Expect.equals(4, doWhileCounter); + Expect.equals(4, i); + + i = 0; + int whileCounter = 0; + while (i < 10) { + i++; + whileCounter++; + if (i > 3) break; + } + Expect.equals(4, whileCounter); + Expect.equals(4, i); + + // Use a label to break to the outer loop. + i = 0; + L: while (i < 10) { + i++; + while (i > 5) { + break L; + } + } + Expect.equals(6, i); + } +} + +main() { + BreakTest.testMain(); +} diff --git a/tests/language/src/CTConstTest.dart b/tests/language/src/CTConstTest.dart new file mode 100644 index 00000000000..dfeab8ed009 --- /dev/null +++ b/tests/language/src/CTConstTest.dart @@ -0,0 +1,123 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// All things regarding compile time constant expressions. + +interface Roman { + static final I = 1; + static final II = 2; + static final III = 3; + static final IV = 4; + static final V = 5; + + static final VivaItalia = const {"green": 1, "red": 3, "white": 2}; +} + + +class Point { + static final int zero = 0; + + static final origin = const Point(0, 0); + static final origin2 = const Point(zero, Roman.IV - 4); + + const Point(x, y) : x_= x, y_ = y; + const Point.X(x) : x_ = x, y_ = Roman.V - Roman.II - 3; + + bool operator ==(final Point other) { + return (this.x_ == other.x_) && (this.y_ == other.y_); + } + + final int x_, y_; +} + + +class Line { + const Line(Point begin, Point end) : beg_ = begin, end_ = end; + final Point beg_; + final Point end_; +} + + +class CTConstTest { + static int getZero() { return 0; } + static final naught = null; + + static testMain() { + Expect.equals(0, Point.zero); + Expect.equals(0, Point.origin.x_); + Expect.equals(true, Point.origin === Point.origin2); + var p1 = const Point(0, 0); + Expect.equals(true, Point.origin === p1); + + Expect.equals(false, Point.origin == const Point(1, 1)); + Expect.equals(false, Point.origin === const Point(1, 1)); + + var p2 = new Point(0, getZero()); + Expect.equals(true, Point.origin == p2); // Point.operator== + + Expect.equals(true, const Point.X(5) === const Point(5, 0)); + + Line l1 = const Line(Point.origin, const Point(1, 1)); + Line l2 = const Line(const Point(0, 0), const Point(1, 1)); + Line l3 = new Line(const Point(0, 0), const Point(1, 1)); + Expect.equals(true, l1 === l2); + + final evenNumbers = const [2, 2*2, 2*3, 2*4, 2*5]; + Expect.equals(true, evenNumbers === const [2, 4, 6, 8, 10]); + + final c11dGermany1 = const {"black": 1, "red": 2, "yellow": 3}; + Expect.equals(true, + c11dGermany1 === const {"black": 1, "red": 2, "yellow": 3}); + + final c11dGermany2 = const {"black": 1, "red": 2, "yellow": 3}; + Expect.equals(true, c11dGermany1 === c11dGermany2); + + final c11dBelgium = const {"black": 1, "yellow": 2, "red": 3}; + Expect.equals(false, c11dGermany1 == c11dBelgium); + Expect.equals(false, c11dGermany1 === c11dBelgium); + + final c11dItaly = const {"green": 1, "red": 3, "white": 2}; + Expect.equals(true, + c11dItaly === const {"green": 1, "red": 3, "white": 2}); + Expect.equals(true, c11dItaly === Roman.VivaItalia); + + Expect.equals(3, c11dItaly.length); + Expect.equals(3, c11dItaly.getKeys().length); + Expect.equals(true, c11dItaly.containsKey("white")); + Expect.equals(false, c11dItaly.containsKey("black")); + + // Make sure the map object is immutable. + bool caughtException = false; + try { + c11dItaly["green"] = 0; + } catch (IllegalAccessException e) { + caughtException = true; + } + Expect.equals(true, caughtException); + Expect.equals(1, c11dItaly["green"]); + + caughtException = false; + try { + c11dItaly.clear(); + } catch (IllegalAccessException e) { + caughtException = true; + } + Expect.equals(true, caughtException); + Expect.equals(1, c11dItaly["green"]); + + caughtException = false; + try { + c11dItaly.remove("orange"); + } catch (IllegalAccessException e) { + caughtException = true; + } + Expect.equals(true, caughtException); + Expect.equals(1, c11dItaly["green"]); + + Expect.equals(true, null === naught); + } +} + +main() { + CTConstTest.testMain(); +} diff --git a/tests/language/src/CallThroughGetterTest.dart b/tests/language/src/CallThroughGetterTest.dart new file mode 100644 index 00000000000..ef22f8d5e61 --- /dev/null +++ b/tests/language/src/CallThroughGetterTest.dart @@ -0,0 +1,161 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests that we can call functions through getters. + +final TOP_LEVEL_CONST = 1; +final TOP_LEVEL_CONST_REF = TOP_LEVEL_CONST; +final TOP_LEVEL_NULL = null; + +var topLevel; + +class CallThroughGetterTest { + + static void testMain() { + testTopLevel(); + testField(); + testGetter(); + testMethod(); + testEvaluationOrder(); + } + + static void testTopLevel() { + topLevel = function() { + return 2; + }; + Expect.equals(1, TOP_LEVEL_CONST); + Expect.equals(1, TOP_LEVEL_CONST_REF); + Expect.equals(2, topLevel()); + + expectThrowsNotClosure(() { TOP_LEVEL_CONST(); }); + expectThrowsNotClosure(() { (TOP_LEVEL_CONST)(); }); + } + + static void testField() { + A a = new A(); + a.field = () => 42; + Expect.equals(42, a.field()); + Expect.equals(42, (a.field)()); + + a.field = () => 87; + Expect.equals(87, a.field()); + Expect.equals(87, (a.field)()); + + a.field = 99; + expectThrowsNotClosure(() { a.field(); }); + expectThrowsNotClosure(() { (a.field)(); }); + } + + static void testGetter() { + A a = new A(); + a.field = () => 42; + Expect.equals(42, a.getter()); + Expect.equals(42, (a.getter)()); + + a.field = () => 87; + Expect.equals(87, a.getter()); + Expect.equals(87, (a.getter)()); + + a.field = 99; + expectThrowsNotClosure(() { a.getter(); }); + expectThrowsNotClosure(() { (a.getter)(); }); + } + + static void testMethod() { + A a = new A(); + a.field = () => 42; + Expect.equals(true, a.method() is Function); + Expect.equals(42, a.method()()); + + a.field = () => 87; + Expect.equals(true, a.method() is Function); + Expect.equals(87, a.method()()); + + a.field = null; + Expect.equals(null, a.method()); + } + + static void testEvaluationOrder() { + B b = new B(); + Expect.equals("gf", b.g0()); + b = new B(); + Expect.equals("gf", (b.g0)()); + + b = new B(); + Expect.equals("xgf", b.g1(b.x)); + b = new B(); + Expect.equals("gxf", (b.g1)(b.x)); + + b = new B(); + Expect.equals("xygf", b.g2(b.x, b.y)); + b = new B(); + Expect.equals("gxyf", (b.g2)(b.x, b.y)); + + b = new B(); + Expect.equals("xyzgf", b.g3(b.x, b.y, b.z)); + b = new B(); + Expect.equals("gxyzf", (b.g3)(b.x, b.y, b.z)); + + b = new B(); + Expect.equals("yzxgf", b.g3(b.y, b.z, b.x)); + b = new B(); + Expect.equals("gyzxf", (b.g3)(b.y, b.z, b.x)); + } + + static void expectThrowsNotClosure(fn) { + var exception = catchException(fn); + if (!(exception is ObjectNotClosureException)) { + Expect.fail("Wrong exception. Expected: ObjectNotClosureException" + + " got: ${exception}"); + } + } + + static catchException(fn) { + bool caught = false; + var result = null; + try { + fn(); + Expect.equals(true, false); // Shouldn't reach this. + } catch (var e) { + caught = true; + result = e; + } + Expect.equals(true, caught); + return result; + } + +} + + +class A { + + A() { } + var field; + get getter() { return field; } + method() { return field; } + +} + + +class B { + + B() : _order = "" { } + + get g0() { _mark('g'); return f0() { return _mark('f'); }; } + get g1() { _mark('g'); return f1(x) { return _mark('f'); }; } + get g2() { _mark('g'); return f2(x, y) { return _mark('f'); }; } + get g3() { _mark('g'); return f3(x, y, z) { return _mark('f'); }; } + + get x() { _mark('x'); return 0; } + get y() { _mark('y'); return 1; } + get z() { _mark('z'); return 2; } + + _mark(m) { _order += m; return _order; } + String _order; + +} + +main() { + CallThroughGetterTest.testMain(); +} diff --git a/tests/language/src/CallThroughNullGetterTest.dart b/tests/language/src/CallThroughNullGetterTest.dart new file mode 100644 index 00000000000..cc5eec360ce --- /dev/null +++ b/tests/language/src/CallThroughNullGetterTest.dart @@ -0,0 +1,87 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests that we can call functions through getters which return null. + +final TOP_LEVEL_NULL = null; + +var topLevel; + +class CallThroughNullGetterTest { + + static void testMain() { + testTopLevel(); + testField(); + testGetter(); + testMethod(); + } + + static void testTopLevel() { + topLevel = null; + expectThrowsNullPointerException(() { topLevel(); }); + expectThrowsNullPointerException(() { (topLevel)(); }); + expectThrowsNullPointerException(() { TOP_LEVEL_NULL(); }); + expectThrowsNullPointerException(() { (TOP_LEVEL_NULL)(); }); + } + + static void testField() { + A a = new A(); + + a.field = null; + expectThrowsNullPointerException(() { a.field(); }); + expectThrowsNullPointerException(() { (a.field)(); }); + } + + static void testGetter() { + A a = new A(); + + a.field = null; + expectThrowsNullPointerException(() { a.getter(); }); + expectThrowsNullPointerException(() { (a.getter)(); }); + } + + static void testMethod() { + A a = new A(); + + a.field = null; + expectThrowsNullPointerException(() { a.method()(); }); + } + + static void expectThrowsNullPointerException(fn) { + var exception = catchException(fn); + if (!(exception is NullPointerException)) { + Expect.fail("Wrong exception. Expected: NullPointerException" + + " got: ${exception}"); + } + } + + static catchException(fn) { + bool caught = false; + var result = null; + try { + fn(); + Expect.equals(true, false); // Shouldn't reach this. + } catch (var e) { + caught = true; + result = e; + } + Expect.equals(true, caught); + return result; + } + +} + + +class A { + + A() { } + var field; + get getter() { return field; } + method() { return field; } + +} + +main() { + CallThroughNullGetterTest.testMain(); +} diff --git a/tests/language/src/CanonicalConstTest.dart b/tests/language/src/CanonicalConstTest.dart new file mode 100644 index 00000000000..640f39af5aa --- /dev/null +++ b/tests/language/src/CanonicalConstTest.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that initializers of static const fields are compile time constants. + +class CanonicalConstTest { + static final A = const C1(); + static final B = const C2(); + + static testMain() { + Expect.isTrue(null===null); + Expect.isTrue(null!==0); + Expect.isTrue(1===1); + Expect.isTrue(1!==2); + Expect.isTrue(true===true); + Expect.isTrue("so"==="so"); + Expect.isTrue(const Object()===const Object()); + Expect.isTrue(const Object()!==const C1()); + Expect.isTrue(const C1()===const C1()); + Expect.isTrue(A===const C1()); + Expect.isTrue(const C1()!==const C2()); + Expect.isTrue(B===const C2()); + // TODO(johnlenz): these two values don't currently have the same type + // Expect.isTrue(const [1,2] === const List[1,2]); + Expect.isTrue(const [2,1] !== const[1,2]); + Expect.isTrue(const [1,2] === const [1,2]); + Expect.isTrue(const [1,2] === const [1,2]); + Expect.isTrue(const [1,2] !== const [1,2]); + Expect.isTrue(const {"a":1, "b":2} === const {"a":1, "b":2}); + Expect.isTrue(const {"a":1, "b":2} !== const {"a":2, "b":2}); + } +} + +class C1 { + const C1(); +} + +class C2 extends C1 { + const C2() : super(); +} + +main() { + CanonicalConstTest.testMain(); +} diff --git a/tests/language/src/CharEscapeTest.dart b/tests/language/src/CharEscapeTest.dart new file mode 100644 index 00000000000..18a0f471a47 --- /dev/null +++ b/tests/language/src/CharEscapeTest.dart @@ -0,0 +1,531 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for reading escape sequences in string literals + +class CharEscapeTest { + static testMain() { + var x00 = "\x00"; + var u0000 = "\u0000"; + var v0 = "\u{0}"; + var v00 = "\u{00}"; + var v000 = "\u{000}"; + var v0000 = "\u{0000}"; + var v00000 = "\u{00000}"; + var v000000 = "\u{000000}"; + Expect.equals(1, x00.length); + Expect.equals(1, u0000.length); + Expect.equals(1, v0.length); + Expect.equals(1, v00.length); + Expect.equals(1, v000.length); + Expect.equals(1, v0000.length); + Expect.equals(1, v00000.length); + Expect.equals(1, v000000.length); + Expect.equals(0, x00.charCodeAt(0)); + Expect.equals(0, u0000.charCodeAt(0)); + Expect.equals(0, v0.charCodeAt(0)); + Expect.equals(0, v00.charCodeAt(0)); + Expect.equals(0, v000.charCodeAt(0)); + Expect.equals(0, v0000.charCodeAt(0)); + Expect.equals(0, v00000.charCodeAt(0)); + Expect.equals(0, v000000.charCodeAt(0)); + Expect.equals("\x00", new String.fromCharCodes([0])); + Expect.equals("\u0000", new String.fromCharCodes([0])); + Expect.equals("\u{0}", new String.fromCharCodes([0])); + Expect.equals("\u{00}", new String.fromCharCodes([0])); + Expect.equals("\u{000}", new String.fromCharCodes([0])); + Expect.equals("\u{0000}", new String.fromCharCodes([0])); + Expect.equals("\u{00000}", new String.fromCharCodes([0])); + Expect.equals("\u{000000}", new String.fromCharCodes([0])); + + var x01 = "\x01"; + var u0001 = "\u0001"; + var v1 = "\u{1}"; + var v01 = "\u{01}"; + var v001 = "\u{001}"; + var v0001 = "\u{0001}"; + var v00001 = "\u{00001}"; + var v000001 = "\u{000001}"; + Expect.equals(1, x01.length); + Expect.equals(1, u0001.length); + Expect.equals(1, v1.length); + Expect.equals(1, v01.length); + Expect.equals(1, v001.length); + Expect.equals(1, v0001.length); + Expect.equals(1, v00001.length); + Expect.equals(1, v000001.length); + Expect.equals(1, x01.charCodeAt(0)); + Expect.equals(1, u0001.charCodeAt(0)); + Expect.equals(1, v1.charCodeAt(0)); + Expect.equals(1, v01.charCodeAt(0)); + Expect.equals(1, v001.charCodeAt(0)); + Expect.equals(1, v0001.charCodeAt(0)); + Expect.equals(1, v00001.charCodeAt(0)); + Expect.equals(1, v000001.charCodeAt(0)); + Expect.equals("\x01", new String.fromCharCodes([1])); + Expect.equals("\u0001", new String.fromCharCodes([1])); + Expect.equals("\u{1}", new String.fromCharCodes([1])); + Expect.equals("\u{01}", new String.fromCharCodes([1])); + Expect.equals("\u{001}", new String.fromCharCodes([1])); + Expect.equals("\u{0001}", new String.fromCharCodes([1])); + Expect.equals("\u{00001}", new String.fromCharCodes([1])); + Expect.equals("\u{000001}", new String.fromCharCodes([1])); + + var x55 = "\x55"; + var u0055 = "\u0055"; + var v55 = "\u{55}"; + var v055 = "\u{055}"; + var v0055 = "\u{0055}"; + var v00055 = "\u{00055}"; + var v000055 = "\u{000055}"; + Expect.equals(1, x55.length); + Expect.equals(1, u0055.length); + Expect.equals(1, v55.length); + Expect.equals(1, v055.length); + Expect.equals(1, v0055.length); + Expect.equals(1, v00055.length); + Expect.equals(1, v000055.length); + Expect.equals(0x55, x55.charCodeAt(0)); + Expect.equals(0x55, u0055.charCodeAt(0)); + Expect.equals(0x55, v55.charCodeAt(0)); + Expect.equals(0x55, v055.charCodeAt(0)); + Expect.equals(0x55, v0055.charCodeAt(0)); + Expect.equals(0x55, v00055.charCodeAt(0)); + Expect.equals(0x55, v000055.charCodeAt(0)); + Expect.equals("\x55", new String.fromCharCodes([0x55])); + Expect.equals("\u0055", new String.fromCharCodes([0x55])); + Expect.equals("\u{55}", new String.fromCharCodes([0x55])); + Expect.equals("\u{055}", new String.fromCharCodes([0x55])); + Expect.equals("\u{0055}", new String.fromCharCodes([0x55])); + Expect.equals("\u{00055}", new String.fromCharCodes([0x55])); + Expect.equals("\u{000055}", new String.fromCharCodes([0x55])); + + var x7F = "\x7F"; + var u007F = "\u007F"; + var v7F = "\u{7F}"; + var v07F = "\u{07F}"; + var v007F = "\u{007F}"; + var v0007F = "\u{0007F}"; + var v00007F = "\u{00007F}"; + Expect.equals(1, x7F.length); + Expect.equals(1, u007F.length); + Expect.equals(1, v7F.length); + Expect.equals(1, v07F.length); + Expect.equals(1, v007F.length); + Expect.equals(1, v0007F.length); + Expect.equals(1, v00007F.length); + Expect.equals(0x7F, x7F.charCodeAt(0)); + Expect.equals(0x7F, u007F.charCodeAt(0)); + Expect.equals(0x7F, v7F.charCodeAt(0)); + Expect.equals(0x7F, v07F.charCodeAt(0)); + Expect.equals(0x7F, v007F.charCodeAt(0)); + Expect.equals(0x7F, v0007F.charCodeAt(0)); + Expect.equals(0x7F, v00007F.charCodeAt(0)); + Expect.equals("\x7F", new String.fromCharCodes([0x7F])); + Expect.equals("\u007F", new String.fromCharCodes([0x7F])); + Expect.equals("\u{7F}", new String.fromCharCodes([0x7F])); + Expect.equals("\u{07F}", new String.fromCharCodes([0x7F])); + Expect.equals("\u{007F}", new String.fromCharCodes([0x7F])); + Expect.equals("\u{0007F}", new String.fromCharCodes([0x7F])); + Expect.equals("\u{00007F}", new String.fromCharCodes([0x7F])); + + var x80 = "\x80"; + var u0080 = "\u0080"; + var v80 = "\u{80}"; + var v080 = "\u{080}"; + var v0080 = "\u{0080}"; + var v00080 = "\u{00080}"; + var v000080 = "\u{000080}"; + Expect.equals(1, x80.length); + Expect.equals(1, u0080.length); + Expect.equals(1, v80.length); + Expect.equals(1, v080.length); + Expect.equals(1, v0080.length); + Expect.equals(1, v00080.length); + Expect.equals(1, v000080.length); + Expect.equals(0x80, x80.charCodeAt(0)); + Expect.equals(0x80, u0080.charCodeAt(0)); + Expect.equals(0x80, v80.charCodeAt(0)); + Expect.equals(0x80, v080.charCodeAt(0)); + Expect.equals(0x80, v0080.charCodeAt(0)); + Expect.equals(0x80, v00080.charCodeAt(0)); + Expect.equals(0x80, v000080.charCodeAt(0)); + Expect.equals("\x80", new String.fromCharCodes([0x80])); + Expect.equals("\u0080", new String.fromCharCodes([0x80])); + Expect.equals("\u{80}", new String.fromCharCodes([0x80])); + Expect.equals("\u{080}", new String.fromCharCodes([0x80])); + Expect.equals("\u{0080}", new String.fromCharCodes([0x80])); + Expect.equals("\u{00080}", new String.fromCharCodes([0x80])); + Expect.equals("\u{000080}", new String.fromCharCodes([0x80])); + + var xAA = "\xAA"; + var u00AA = "\u00AA"; + var vAA = "\u{AA}"; + var v0AA = "\u{0AA}"; + var v00AA = "\u{00AA}"; + var v000AA = "\u{000AA}"; + var v0000AA = "\u{0000AA}"; + Expect.equals(1, xAA.length); + Expect.equals(1, u00AA.length); + Expect.equals(1, vAA.length); + Expect.equals(1, v0AA.length); + Expect.equals(1, v00AA.length); + Expect.equals(1, v000AA.length); + Expect.equals(1, v0000AA.length); + Expect.equals(0xAA, xAA.charCodeAt(0)); + Expect.equals(0xAA, u00AA.charCodeAt(0)); + Expect.equals(0xAA, vAA.charCodeAt(0)); + Expect.equals(0xAA, v0AA.charCodeAt(0)); + Expect.equals(0xAA, v00AA.charCodeAt(0)); + Expect.equals(0xAA, v000AA.charCodeAt(0)); + Expect.equals(0xAA, v0000AA.charCodeAt(0)); + Expect.equals("\xAA", new String.fromCharCodes([0xAA])); + Expect.equals("\u00AA", new String.fromCharCodes([0xAA])); + Expect.equals("\u{AA}", new String.fromCharCodes([0xAA])); + Expect.equals("\u{0AA}", new String.fromCharCodes([0xAA])); + Expect.equals("\u{00AA}", new String.fromCharCodes([0xAA])); + Expect.equals("\u{000AA}", new String.fromCharCodes([0xAA])); + Expect.equals("\u{0000AA}", new String.fromCharCodes([0xAA])); + + var xFE = "\xFE"; + var u00FE = "\u00FE"; + var vFE = "\u{FE}"; + var v0FE = "\u{0FE}"; + var v00FE = "\u{00FE}"; + var v000FE = "\u{000FE}"; + var v0000FE = "\u{0000FE}"; + Expect.equals(1, xFE.length); + Expect.equals(1, u00FE.length); + Expect.equals(1, vFE.length); + Expect.equals(1, v0FE.length); + Expect.equals(1, v00FE.length); + Expect.equals(1, v000FE.length); + Expect.equals(1, v0000FE.length); + Expect.equals(0xFE, xFE.charCodeAt(0)); + Expect.equals(0xFE, u00FE.charCodeAt(0)); + Expect.equals(0xFE, vFE.charCodeAt(0)); + Expect.equals(0xFE, v0FE.charCodeAt(0)); + Expect.equals(0xFE, v00FE.charCodeAt(0)); + Expect.equals(0xFE, v000FE.charCodeAt(0)); + Expect.equals(0xFE, v0000FE.charCodeAt(0)); + Expect.equals("\xFE", new String.fromCharCodes([0xFE])); + Expect.equals("\u00FE", new String.fromCharCodes([0xFE])); + Expect.equals("\u{FE}", new String.fromCharCodes([0xFE])); + Expect.equals("\u{0FE}", new String.fromCharCodes([0xFE])); + Expect.equals("\u{00FE}", new String.fromCharCodes([0xFE])); + Expect.equals("\u{000FE}", new String.fromCharCodes([0xFE])); + Expect.equals("\u{0000FE}", new String.fromCharCodes([0xFE])); + + var xFF = "\xFF"; + var u00FF = "\u00FF"; + var vFF = "\u{FF}"; + var v0FF = "\u{0FF}"; + var v00FF = "\u{00FF}"; + var v000FF = "\u{000FF}"; + var v0000FF = "\u{0000FF}"; + Expect.equals(1, xFF.length); + Expect.equals(1, u00FF.length); + Expect.equals(1, vFF.length); + Expect.equals(1, v0FF.length); + Expect.equals(1, v00FF.length); + Expect.equals(1, v000FF.length); + Expect.equals(1, v0000FF.length); + Expect.equals(0xFF, xFF.charCodeAt(0)); + Expect.equals(0xFF, u00FF.charCodeAt(0)); + Expect.equals(0xFF, vFF.charCodeAt(0)); + Expect.equals(0xFF, v0FF.charCodeAt(0)); + Expect.equals(0xFF, v00FF.charCodeAt(0)); + Expect.equals(0xFF, v000FF.charCodeAt(0)); + Expect.equals(0xFF, v0000FF.charCodeAt(0)); + Expect.equals("\xFF", new String.fromCharCodes([0xFF])); + Expect.equals("\u00FF", new String.fromCharCodes([0xFF])); + Expect.equals("\u{FF}", new String.fromCharCodes([0xFF])); + Expect.equals("\u{0FF}", new String.fromCharCodes([0xFF])); + Expect.equals("\u{00FF}", new String.fromCharCodes([0xFF])); + Expect.equals("\u{000FF}", new String.fromCharCodes([0xFF])); + Expect.equals("\u{0000FF}", new String.fromCharCodes([0xFF])); + + var u1000 = "\u1000"; + var v1000 = "\u{1000}"; + var v01000 = "\u{01000}"; + var v001000 = "\u{001000}"; + Expect.equals(1, u1000.length); + Expect.equals(1, v1000.length); + Expect.equals(1, v01000.length); + Expect.equals(1, v001000.length); + Expect.equals(0x1000, u1000.charCodeAt(0)); + Expect.equals(0x1000, v1000.charCodeAt(0)); + Expect.equals(0x1000, v01000.charCodeAt(0)); + Expect.equals(0x1000, v001000.charCodeAt(0)); + Expect.equals("\u1000", new String.fromCharCodes([0x1000])); + Expect.equals("\u{1000}", new String.fromCharCodes([0x1000])); + Expect.equals("\u{01000}", new String.fromCharCodes([0x1000])); + Expect.equals("\u{001000}", new String.fromCharCodes([0x1000])); + + var u5555 = "\u5555"; + var v5555 = "\u{5555}"; + var v05555 = "\u{05555}"; + var v005555 = "\u{005555}"; + Expect.equals(1, u5555.length); + Expect.equals(1, v5555.length); + Expect.equals(1, v05555.length); + Expect.equals(1, v005555.length); + Expect.equals(0x5555, u5555.charCodeAt(0)); + Expect.equals(0x5555, v5555.charCodeAt(0)); + Expect.equals(0x5555, v05555.charCodeAt(0)); + Expect.equals(0x5555, v005555.charCodeAt(0)); + Expect.equals("\u5555", new String.fromCharCodes([0x5555])); + Expect.equals("\u{5555}", new String.fromCharCodes([0x5555])); + Expect.equals("\u{05555}", new String.fromCharCodes([0x5555])); + Expect.equals("\u{005555}", new String.fromCharCodes([0x5555])); + + var u7FFF = "\u7FFF"; + var v7FFF = "\u{7FFF}"; + var v07FFF = "\u{07FFF}"; + var v007FFF = "\u{007FFF}"; + Expect.equals(1, u7FFF.length); + Expect.equals(1, v7FFF.length); + Expect.equals(1, v07FFF.length); + Expect.equals(1, v007FFF.length); + Expect.equals(0x7FFF, u7FFF.charCodeAt(0)); + Expect.equals(0x7FFF, v7FFF.charCodeAt(0)); + Expect.equals(0x7FFF, v07FFF.charCodeAt(0)); + Expect.equals(0x7FFF, v007FFF.charCodeAt(0)); + Expect.equals("\u7FFF", new String.fromCharCodes([0x7FFF])); + Expect.equals("\u{7FFF}", new String.fromCharCodes([0x7FFF])); + Expect.equals("\u{07FFF}", new String.fromCharCodes([0x7FFF])); + Expect.equals("\u{007FFF}", new String.fromCharCodes([0x7FFF])); + + var u8000 = "\u8000"; + var v8000 = "\u{8000}"; + var v08000 = "\u{08000}"; + var v008000 = "\u{008000}"; + Expect.equals(1, u8000.length); + Expect.equals(1, v8000.length); + Expect.equals(1, v08000.length); + Expect.equals(1, v008000.length); + Expect.equals(0x8000, u8000.charCodeAt(0)); + Expect.equals(0x8000, v8000.charCodeAt(0)); + Expect.equals(0x8000, v08000.charCodeAt(0)); + Expect.equals(0x8000, v008000.charCodeAt(0)); + Expect.equals("\u8000", new String.fromCharCodes([0x8000])); + Expect.equals("\u{8000}", new String.fromCharCodes([0x8000])); + Expect.equals("\u{08000}", new String.fromCharCodes([0x8000])); + Expect.equals("\u{008000}", new String.fromCharCodes([0x8000])); + + var uAAAA = "\uAAAA"; + var vAAAA = "\u{AAAA}"; + var v0AAAA = "\u{0AAAA}"; + var v00AAAA = "\u{00AAAA}"; + Expect.equals(1, uAAAA.length); + Expect.equals(1, vAAAA.length); + Expect.equals(1, v0AAAA.length); + Expect.equals(1, v00AAAA.length); + Expect.equals(0xAAAA, uAAAA.charCodeAt(0)); + Expect.equals(0xAAAA, vAAAA.charCodeAt(0)); + Expect.equals(0xAAAA, v0AAAA.charCodeAt(0)); + Expect.equals(0xAAAA, v00AAAA.charCodeAt(0)); + Expect.equals("\uAAAA", new String.fromCharCodes([0xAAAA])); + Expect.equals("\u{AAAA}", new String.fromCharCodes([0xAAAA])); + Expect.equals("\u{0AAAA}", new String.fromCharCodes([0xAAAA])); + Expect.equals("\u{00AAAA}", new String.fromCharCodes([0xAAAA])); + + var uFFFE = "\uFFFE"; + var vFFFE = "\u{FFFE}"; + var v0FFFE = "\u{0FFFE}"; + var v00FFFE = "\u{00FFFE}"; + Expect.equals(1, uFFFE.length); + Expect.equals(1, vFFFE.length); + Expect.equals(1, v0FFFE.length); + Expect.equals(1, v00FFFE.length); + Expect.equals(0xFFFE, uFFFE.charCodeAt(0)); + Expect.equals(0xFFFE, vFFFE.charCodeAt(0)); + Expect.equals(0xFFFE, v0FFFE.charCodeAt(0)); + Expect.equals(0xFFFE, v00FFFE.charCodeAt(0)); + Expect.equals("\uFFFE", new String.fromCharCodes([0xFFFE])); + Expect.equals("\u{FFFE}", new String.fromCharCodes([0xFFFE])); + Expect.equals("\u{0FFFE}", new String.fromCharCodes([0xFFFE])); + Expect.equals("\u{00FFFE}", new String.fromCharCodes([0xFFFE])); + + var uFFFF = "\uFFFF"; + var vFFFF = "\u{FFFF}"; + var v0FFFF = "\u{0FFFF}"; + var v00FFFF = "\u{00FFFF}"; + Expect.equals(1, uFFFF.length); + Expect.equals(1, vFFFF.length); + Expect.equals(1, v0FFFF.length); + Expect.equals(1, v00FFFF.length); + Expect.equals(0xFFFF, uFFFF.charCodeAt(0)); + Expect.equals(0xFFFF, vFFFF.charCodeAt(0)); + Expect.equals(0xFFFF, v0FFFF.charCodeAt(0)); + Expect.equals(0xFFFF, v00FFFF.charCodeAt(0)); + Expect.equals("\uFFFF", new String.fromCharCodes([0xFFFF])); + Expect.equals("\u{FFFF}", new String.fromCharCodes([0xFFFF])); + Expect.equals("\u{0FFFF}", new String.fromCharCodes([0xFFFF])); + Expect.equals("\u{00FFFF}", new String.fromCharCodes([0xFFFF])); + + var v10000 = "\u{10000}"; + var v010000 = "\u{010000}"; + Expect.equals(1, v10000.length); + Expect.equals(1, v010000.length); + Expect.equals("\u{10000}", new String.fromCharCodes([0x10000])); + Expect.equals("\u{010000}", new String.fromCharCodes([0x10000])); + + var v1FFFF = "\u{1FFFF}"; + var v01FFFF = "\u{01FFFF}"; + Expect.equals(1, v1FFFF.length); + Expect.equals(1, v01FFFF.length); + Expect.equals("\u{1FFFF}", new String.fromCharCodes([0x1FFFF])); + Expect.equals("\u{01FFFF}", new String.fromCharCodes([0x1FFFF])); + + var v105555 = "\u{105555}"; + Expect.equals(1, v105555.length); + Expect.equals("\u{105555}", new String.fromCharCodes([0x105555])); + + var v10FFFF = "\u{10FFFF}"; + Expect.equals(1, v10FFFF.length); + Expect.equals("\u{10FFFF}", new String.fromCharCodes([0x10FFFF])); + + var bs = "\b"; + Expect.isTrue(bs != "b"); + Expect.equals(1, bs.length); + Expect.equals(0x08, bs.charCodeAt(0)); + Expect.equals(bs, new String.fromCharCodes([0x08])); + Expect.equals("\x08", bs); + Expect.equals("\u0008", bs); + Expect.equals("\u{8}", bs); + Expect.equals("\u{08}", bs); + Expect.equals("\u{008}", bs); + Expect.equals("\u{0008}", bs); + Expect.equals("\u{00008}", bs); + Expect.equals("\u{000008}", bs); + + var ht = "\t"; + Expect.isTrue(ht != "t"); + Expect.equals(1, ht.length); + Expect.equals(0x09, ht.charCodeAt(0)); + Expect.equals(ht, new String.fromCharCodes([0x09])); + Expect.equals("\x09", ht); + Expect.equals("\u0009", ht); + Expect.equals("\u{9}", ht); + Expect.equals("\u{09}", ht); + Expect.equals("\u{009}", ht); + Expect.equals("\u{0009}", ht); + Expect.equals("\u{00009}", ht); + Expect.equals("\u{000009}", ht); + + var lf = "\n"; + Expect.isTrue(lf != "n"); + Expect.equals(1, lf.length); + Expect.equals(0x0A, lf.charCodeAt(0)); + Expect.equals(lf, new String.fromCharCodes([0x0A])); + Expect.equals("\x0A", lf); + Expect.equals("\u000A", lf); + Expect.equals("\u{A}", lf); + Expect.equals("\u{0A}", lf); + Expect.equals("\u{00A}", lf); + Expect.equals("\u{000A}", lf); + Expect.equals("\u{0000A}", lf); + Expect.equals("\u{00000A}", lf); + + var vt = "\v"; + Expect.isTrue(vt != "v"); + Expect.equals(1, vt.length); + Expect.equals(0x0B, vt.charCodeAt(0)); + Expect.equals(vt, new String.fromCharCodes([0x0B])); + Expect.equals("\x0B", vt); + Expect.equals("\u000B", vt); + Expect.equals("\u{B}", vt); + Expect.equals("\u{0B}", vt); + Expect.equals("\u{00B}", vt); + Expect.equals("\u{000B}", vt); + Expect.equals("\u{0000B}", vt); + Expect.equals("\u{00000B}", vt); + + var ff = "\f"; + Expect.isTrue(ff != "f"); + Expect.equals(1, ff.length); + Expect.equals(0x0C, ff.charCodeAt(0)); + Expect.equals(ff, new String.fromCharCodes([0x0C])); + Expect.equals("\x0C", ff); + Expect.equals("\u000C", ff); + Expect.equals("\u{C}", ff); + Expect.equals("\u{0C}", ff); + Expect.equals("\u{00C}", ff); + Expect.equals("\u{000C}", ff); + Expect.equals("\u{0000C}", ff); + Expect.equals("\u{00000C}", ff); + + var cr = "\r"; + Expect.isTrue(cr != "r"); + Expect.equals(1, cr.length); + Expect.equals(0x0D, cr.charCodeAt(0)); + Expect.equals(cr, new String.fromCharCodes([0x0D])); + Expect.equals("\x0D", cr); + Expect.equals("\u000D", cr); + Expect.equals("\u{D}", cr); + Expect.equals("\u{0D}", cr); + Expect.equals("\u{00D}", cr); + Expect.equals("\u{000D}", cr); + Expect.equals("\u{0000D}", cr); + Expect.equals("\u{00000D}", cr); + + Expect.equals("\a", "a"); + // \b U+0006 BS + Expect.equals("\c", "c"); + Expect.equals("\d", "d"); + Expect.equals("\e", "e"); + // \f U+000C FF + Expect.equals("\g", "g"); + Expect.equals("\h", "h"); + Expect.equals("\i", "i"); + Expect.equals("\j", "j"); + Expect.equals("\k", "k"); + Expect.equals("\l", "l"); + Expect.equals("\m", "m"); + // \n U+000A LF + Expect.equals("\o", "o"); + Expect.equals("\p", "p"); + Expect.equals("\q", "q"); + // \r U+000D CR + Expect.equals("\s", "s"); + // \t U+0009 HT + // \u code point escape + // \v U+000B VT + Expect.equals("\w", "w"); + // \x code point escape + Expect.equals("\y", "y"); + Expect.equals("\z", "z"); + + Expect.equals("\A", "A"); + Expect.equals("\B", "B"); + Expect.equals("\C", "C"); + Expect.equals("\D", "D"); + Expect.equals("\E", "E"); + Expect.equals("\F", "F"); + Expect.equals("\G", "G"); + Expect.equals("\H", "H"); + Expect.equals("\I", "I"); + Expect.equals("\J", "J"); + Expect.equals("\K", "K"); + Expect.equals("\L", "L"); + Expect.equals("\M", "M"); + Expect.equals("\N", "N"); + Expect.equals("\O", "O"); + Expect.equals("\P", "P"); + Expect.equals("\Q", "Q"); + Expect.equals("\R", "R"); + Expect.equals("\S", "S"); + Expect.equals("\T", "T"); + Expect.equals("\U", "U"); + Expect.equals("\V", "V"); + Expect.equals("\W", "W"); + Expect.equals("\X", "X"); + Expect.equals("\Y", "Y"); + Expect.equals("\Z", "Z"); + } +} + +main() { + CharEscapeTest.testMain(); +} diff --git a/tests/language/src/ClassCycleNegativeTest.dart b/tests/language/src/ClassCycleNegativeTest.dart new file mode 100644 index 00000000000..f54b9f853e7 --- /dev/null +++ b/tests/language/src/ClassCycleNegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check fail because of cycles in super class relationship. + +class C extends B { + +} + +class A extends B { + +} + +class B extends A { + +} + +class ClassCycleNegativeTest { + static testMain() { + } +} +main() { + ClassCycleNegativeTest.testMain(); +} diff --git a/tests/language/src/ClassExtendsNegativeTest.dart b/tests/language/src/ClassExtendsNegativeTest.dart new file mode 100644 index 00000000000..f3eb7bf861e --- /dev/null +++ b/tests/language/src/ClassExtendsNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check fails because class extends from interface. + +interface InterfaceA { + +} + +class ClassA extends InterfaceA { + +} + +class ClassExtendsNegativeTest { + static testMain() { + } +} + +main() { + ClassExtendsNegativeTest.testMain(); +} diff --git a/tests/language/src/ClassLiteralTest.dart b/tests/language/src/ClassLiteralTest.dart new file mode 100644 index 00000000000..2c70ec10186 --- /dev/null +++ b/tests/language/src/ClassLiteralTest.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that classes cannot be used as expressions. + +class Class { + static fisk() => 42; +} + +foo(x) {} + +main() { + if (false) { + Class; /// 01: compile-time error + Class(); /// 02: compile-time error + Class.method(); /// 03: compile-time error + Class.field; /// 04: compile-time error + Class[0]; /// 05: compile-time error + var x = Class; /// 06: compile-time error + var x = Class(); /// 07: compile-time error + var x = Class.method(); /// 08: compile-time error + var x = Class.field; /// 09: compile-time error + var x = Class[0]; /// 10: compile-time error + var x = Class[0].field; /// 11: compile-time error + var x = Class[0].method(); /// 12: compile-time error + foo(Class); /// 13: compile-time error + foo(Class()); /// 14: compile-time error + foo(Class.method()); /// 15: compile-time error + foo(Class.field); /// 16: compile-time error + foo(Class[0]); /// 17: compile-time error + foo(Class[0].field); /// 18: compile-time error + foo(Class[0].method()); /// 19: compile-time error + Class === null; /// 20: compile-time error + null === Class; /// 21: compile-time error + Class[0] = 91; /// 22: compile-time error + Class++; /// 23: compile-time error + ++Class; /// 24: compile-time error + Class / 3; /// 25: compile-time error + Class += 3; /// 26: compile-time error + Class[0] += 3; /// 27: compile-time error + ++Class[0]; /// 28: compile-time error + Class[0]++; /// 29: compile-time error + } + Expect.equals(42, Class.fisk()); + Expect.equals(null, foo(Class.fisk())); +} diff --git a/tests/language/src/ClassOverrideNegativeTest.dart b/tests/language/src/ClassOverrideNegativeTest.dart new file mode 100644 index 00000000000..aa4ce8a9bdb --- /dev/null +++ b/tests/language/src/ClassOverrideNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check fail because incompatible overriding method + +class A { + foo() {} +} + +class B extends A { + foo(a) { } +} + +class ClassOverrideNegativeTest { + static testMain() { + } +} + +main() { + ClassOverrideNegativeTest.testMain(); +} diff --git a/tests/language/src/ClassTest.dart b/tests/language/src/ClassTest.dart new file mode 100644 index 00000000000..7c092fe2129 --- /dev/null +++ b/tests/language/src/ClassTest.dart @@ -0,0 +1,170 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests basic classes and methods. +class ClassTest { + ClassTest() {} + + static testMain() { + var test = new ClassTest(); + test.testSuperCalls(); + test.testVirtualCalls(); + test.testStaticCalls(); + test.testInheritedField(); + test.testMemberRefInClosure(); + test.testFactory(); + test.testNamedConstructors(); + test.testDefaultImplementation(); + test.testFunctionParameter((int a) { return a;}); + } + + testFunctionParameter(int func(int a)) { + Expect.equals(1, func(1)); + } + + testSuperCalls() { + var sub = new Sub(); + Expect.equals(43, sub.methodX()); + Expect.equals(84, sub.methodK()); + } + + testVirtualCalls() { + var sub = new Sub(); + Expect.equals(41, sub.method2()); + Expect.equals(41, sub.method3()); + } + + testStaticCalls() { + var sub = new Sub(); + Expect.equals(-42, Sub.method4()); + Expect.equals(-41, sub.method5()); + } + + testInheritedField() { + var sub = new Sub(); + Expect.equals(42, sub.method6()); + } + + testMemberRefInClosure() { + var sub = new Sub(); + Expect.equals(1, sub.closureRef()); + Expect.equals(2, sub.closureRef()); + // Make sure it is actually on the object, not the global 'this'. + sub = new Sub(); + Expect.equals(1, sub.closureRef()); + Expect.equals(2, sub.closureRef()); + } + + testFactory() { + var sup = new Sup.named(); + Expect.equals(43, sup.methodX()); + Expect.equals(84, sup.methodK()); + } + + testNamedConstructors() { + var sup = new Sup.fromInt(4); + Expect.equals(4, sup.methodX()); + Expect.equals(0, sup.methodK()); + } + + testDefaultImplementation() { + var x = new Inter(4); + Expect.equals(4, x.methodX()); + Expect.equals(8, x.methodK()); + + x = new Inter.fromInt(4); + Expect.equals(4, x.methodX()); + Expect.equals(0, x.methodK()); + + x = new Inter.named(); + Expect.equals(43, x.methodX()); + Expect.equals(84, x.methodK()); + + x = new Inter.factory(); + Expect.equals(43, x.methodX()); + Expect.equals(84, x.methodK()); + } +} + +interface Inter factory Sup { + Inter.named(); + Inter.fromInt(int x); + Inter(int x); + Inter.factory(); + int methodX(); + int methodK(); + int x_; +} + +class Sup implements Inter { + int x_; + int k_; + + factory Sup.named() { + return new Sub(); + } + + factory Inter.factory() { + return new Sub(); + } + + Sup.fromInt(int x) { + x_ = x; + k_ = 0; + } + + int methodX() { + return x_; + } + + int methodK() { + return k_; + } + + Sup(int x) : this.x_ = x { + k_ = x * 2; + } + + int method2() { + return x_ - 1; + } +} + +class Sub extends Sup { + int y_; + + // Override + int methodX() { + return super.methodX() + 1; + } + + int method3() { + return method2(); + } + + static int method4() { + return -42; + } + + int method5() { + return method4() + 1; + } + + int method6() { + return x_ + y_; + } + + int closureRef() { + var f = () {y_ += 1; return y_;}; + return f(); + } + + Sub() : super(42) { + y_ = 0; + } +} + +main() { + ClassTest.testMain(); +} diff --git a/tests/language/src/ClosureBreak1Test.dart b/tests/language/src/ClosureBreak1Test.dart new file mode 100644 index 00000000000..5f5ead7c415 --- /dev/null +++ b/tests/language/src/ClosureBreak1Test.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for closures. + +class ClosureBreak1 { + ClosureBreak1(this.field); + int field; +} + +class ClosureBreak1Test { + static testMain() { + var o1 = new ClosureBreak1(3); + String newstr = "abcdefgh"; + foo() { + o1.field++; + Expect.equals(8, newstr.length); + } + bool loop = true; + L: + while (loop) { + String newstr1 = "abcd"; + var o2 = new ClosureBreak1(3); + foo1() { + o2.field++; + Expect.equals(4, newstr1.length); + } + Expect.equals(4, newstr1.length); + while (loop) { + int newint = 0; + var o3 = new ClosureBreak1(3); + foo2() { + o3.field++; + Expect.equals(0, newint); + } + foo2(); + break L; + } + } + foo(); + Expect.equals(4, o1.field); + } +} + +main() { + ClosureBreak1Test.testMain(); +} diff --git a/tests/language/src/ClosureBreak2Test.dart b/tests/language/src/ClosureBreak2Test.dart new file mode 100644 index 00000000000..38b1c859baf --- /dev/null +++ b/tests/language/src/ClosureBreak2Test.dart @@ -0,0 +1,37 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for closures. + +class ClosureBreak2 { + ClosureBreak2(this.field); + int field; +} + +class ClosureBreak2Test { + static testMain() { + var o1 = new ClosureBreak2(3); + String newstr = "abcdefgh"; + foo() { + o1.field++; + Expect.equals(8, newstr.length); + } + bool loop = true; + L: + while (loop) { + String newstr1 = "abcd"; + Expect.equals(4, newstr1.length); + while (loop) { + int newint = 0; + Expect.equals(4, newstr1.length); + break L; + } + } + foo(); + Expect.equals(4, o1.field); + } +} + +main() { + ClosureBreak2Test.testMain(); +} diff --git a/tests/language/src/ClosureBreakTest.dart b/tests/language/src/ClosureBreakTest.dart new file mode 100644 index 00000000000..0aca64418fb --- /dev/null +++ b/tests/language/src/ClosureBreakTest.dart @@ -0,0 +1,49 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for closures. + +class ClosureBreak { + ClosureBreak(this.field); + int field; +} + +class ClosureBreakTest { + static testMain() { + var o1 = new ClosureBreak(3); + String newstr = "abcdefgh"; + foo() { + o1.field++; + Expect.equals(8, newstr.length); + } + bool loop = true; + L1: while (loop) { + String newstr1 = "abcd"; + var o2 = new ClosureBreak(3); + foo1() { + o2.field++; + Expect.equals(4, newstr1.length); + } + Expect.equals(4, newstr1.length); + L2: while (loop) { + int newint = 0; + var o3 = new ClosureBreak(3); + foo2() { + o3.field++; + Expect.equals(0, newint); + } + foo2(); + break L2; + } + foo1(); + Expect.equals(4, newstr1.length); + break L1; + } + foo(); + Expect.equals(4, o1.field); + } +} + +main() { + ClosureBreakTest.testMain(); +} diff --git a/tests/language/src/ClosureCallWrongArgumentCountNegativeTest.dart b/tests/language/src/ClosureCallWrongArgumentCountNegativeTest.dart new file mode 100644 index 00000000000..ad9e4ec2da4 --- /dev/null +++ b/tests/language/src/ClosureCallWrongArgumentCountNegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test mismatch in argument counts. + +class ClosureCallWrongArgumentCountNegativeTest { + + static int melke(var f) { + return f(1, 2, 3); + } + + static void testMain() { + kuh(int a, int b) { + return a + b; + } + melke(kuh); + } +} + +main() { + ClosureCallWrongArgumentCountNegativeTest.testMain(); +} diff --git a/tests/language/src/ClosureTest.dart b/tests/language/src/ClosureTest.dart new file mode 100644 index 00000000000..0d7220bfd83 --- /dev/null +++ b/tests/language/src/ClosureTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for closures. + +class A { + var field; + A(this.field) {} +} + +class ClosureTest { + static testMain() { + var o = new A(3); + foo() => o.field++; + Expect.equals(3, foo()); + Expect.equals(4, o.field); + } +} + +main() { + ClosureTest.testMain(); +} diff --git a/tests/language/src/ComparisonTest.dart b/tests/language/src/ComparisonTest.dart new file mode 100644 index 00000000000..18ac9df803e --- /dev/null +++ b/tests/language/src/ComparisonTest.dart @@ -0,0 +1,324 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing comparison operators. + +class Helper { + static bool STRICT_EQ(a, b) { + return a === b; + } + + static bool STRICT_NE(a, b) { + return a !== b; + } + + static bool EQ(a, b) { + return a == b; + } + + static bool NE(a, b) { + return a != b; + } + + static bool LT(a, b) { + return a < b; + } + + static bool LE(a,b) { + return a <= b; + } + + static bool GT(a, b) { + return a > b; + } + + static bool GE(a, b) { + return a >= b; + } +} + +class A { + var b; + + A(x) : b = x { } +} + +class ComparisonTest { + static testMain() { + var a = new A(0); + var b = new A(1); + Expect.equals(true, Helper.STRICT_EQ(a, a)); + Expect.equals(false, Helper.STRICT_EQ(a, b)); + Expect.equals(false, Helper.STRICT_EQ(b, a)); + Expect.equals(true, Helper.STRICT_EQ(b, b)); + + Expect.equals(false, Helper.STRICT_NE(a, a)); + Expect.equals(true, Helper.STRICT_NE(a, b)); + Expect.equals(true, Helper.STRICT_NE(b, a)); + Expect.equals(false, Helper.STRICT_NE(b, b)); + + Expect.equals(true, Helper.STRICT_EQ(false, false)); + Expect.equals(false, Helper.STRICT_EQ(false, true)); + Expect.equals(false, Helper.STRICT_EQ(true, false)); + Expect.equals(true, Helper.STRICT_EQ(true, true)); + + Expect.equals(false, Helper.STRICT_NE(false, false)); + Expect.equals(true, Helper.STRICT_NE(false, true)); + Expect.equals(true, Helper.STRICT_NE(true, false)); + Expect.equals(false, Helper.STRICT_NE(true, true)); + + Expect.equals(true, Helper.STRICT_EQ(false, false)); + Expect.equals(false, Helper.STRICT_EQ(false, true)); + Expect.equals(false, Helper.STRICT_EQ(true, false)); + Expect.equals(true, Helper.STRICT_EQ(true, true)); + + Expect.equals(false, Helper.STRICT_NE(false, false)); + Expect.equals(true, Helper.STRICT_NE(false, true)); + Expect.equals(true, Helper.STRICT_NE(true, false)); + Expect.equals(false, Helper.STRICT_NE(true, true)); + + Expect.equals(true, Helper.EQ(false, false)); + Expect.equals(false, Helper.EQ(false, true)); + Expect.equals(false, Helper.EQ(true, false)); + Expect.equals(true, Helper.EQ(true, true)); + + Expect.equals(false, Helper.NE(false, false)); + Expect.equals(true, Helper.NE(false, true)); + Expect.equals(true, Helper.NE(true, false)); + Expect.equals(false, Helper.NE(true, true)); + + Expect.equals(true, Helper.STRICT_EQ(-1, -1)); + Expect.equals(true, Helper.STRICT_EQ(0, 0)); + Expect.equals(true, Helper.STRICT_EQ(1, 1)); + Expect.equals(false, Helper.STRICT_EQ(-1, 0)); + Expect.equals(false, Helper.STRICT_EQ(-1, 1)); + Expect.equals(false, Helper.STRICT_EQ(0, 1)); + + Expect.equals(false, Helper.STRICT_NE(-1, -1)); + Expect.equals(false, Helper.STRICT_NE(0, 0)); + Expect.equals(false, Helper.STRICT_NE(1, 1)); + Expect.equals(true, Helper.STRICT_NE(-1, 0)); + Expect.equals(true, Helper.STRICT_NE(-1, 1)); + Expect.equals(true, Helper.STRICT_NE(0, 1)); + + Expect.equals(true, Helper.EQ(-1, -1)); + Expect.equals(true, Helper.EQ(0, 0)); + Expect.equals(true, Helper.EQ(1, 1)); + Expect.equals(false, Helper.EQ(-1, 0)); + Expect.equals(false, Helper.EQ(-1, 1)); + Expect.equals(false, Helper.EQ(0, 1)); + + Expect.equals(false, Helper.NE(-1, -1)); + Expect.equals(false, Helper.NE(0, 0)); + Expect.equals(false, Helper.NE(1, 1)); + Expect.equals(true, Helper.NE(-1, 0)); + Expect.equals(true, Helper.NE(-1, 1)); + Expect.equals(true, Helper.NE(0, 1)); + + Expect.equals(false, Helper.LT(-1, -1)); + Expect.equals(false, Helper.LT(0, 0)); + Expect.equals(false, Helper.LT(1, 1)); + Expect.equals(true, Helper.LT(-1, 0)); + Expect.equals(true, Helper.LT(-1, 1)); + Expect.equals(true, Helper.LT(0, 1)); + Expect.equals(false, Helper.LT(0, -1)); + Expect.equals(false, Helper.LT(1, -1)); + Expect.equals(false, Helper.LT(1, 0)); + + Expect.equals(true, Helper.LE(-1, -1)); + Expect.equals(true, Helper.LE(0, 0)); + Expect.equals(true, Helper.LE(1, 1)); + Expect.equals(true, Helper.LE(-1, 0)); + Expect.equals(true, Helper.LE(-1, 1)); + Expect.equals(true, Helper.LE(0, 1)); + Expect.equals(false, Helper.LE(0, -1)); + Expect.equals(false, Helper.LE(1, -1)); + Expect.equals(false, Helper.LE(1, 0)); + + Expect.equals(false, Helper.GT(-1, -1)); + Expect.equals(false, Helper.GT(0, 0)); + Expect.equals(false, Helper.GT(1, 1)); + Expect.equals(false, Helper.GT(-1, 0)); + Expect.equals(false, Helper.GT(-1, 1)); + Expect.equals(false, Helper.GT(0, 1)); + Expect.equals(true, Helper.GT(0, -1)); + Expect.equals(true, Helper.GT(1, -1)); + Expect.equals(true, Helper.GT(1, 0)); + + Expect.equals(true, Helper.GE(-1, -1)); + Expect.equals(true, Helper.GE(0, 0)); + Expect.equals(true, Helper.GE(1, 1)); + Expect.equals(false, Helper.GE(-1, 0)); + Expect.equals(false, Helper.GE(-1, 1)); + Expect.equals(false, Helper.GE(0, 1)); + Expect.equals(true, Helper.GE(0, -1)); + Expect.equals(true, Helper.GE(1, -1)); + Expect.equals(true, Helper.GE(1, 0)); + + // TODO(regis): Double literals are not yet canonicalized. + // Expect.equals(true, Helper.STRICT_EQ(-1.0, -1.0)); + // Expect.equals(true, Helper.STRICT_EQ(0.0, 0.0)); + // Expect.equals(true, Helper.STRICT_EQ(1.0, 1.0)); + // Expect.equals(false, Helper.STRICT_EQ(-1.0, 0.0)); + // Expect.equals(false, Helper.STRICT_EQ(-1.0, 1.0)); + // Expect.equals(false, Helper.STRICT_EQ(0.0, 1.0)); + + // Expect.equals(false, Helper.STRICT_NE(-1.0, -1.0)); + // Expect.equals(false, Helper.STRICT_NE(0.0, 0.0)); + // Expect.equals(false, Helper.STRICT_NE(1.0, 1.0)); + // Expect.equals(true, Helper.STRICT_NE(-1.0, 0.0)); + // Expect.equals(true, Helper.STRICT_NE(-1.0, 1.0)); + // Expect.equals(true, Helper.STRICT_NE(0.0, 1.0)); + + Expect.equals(true, Helper.EQ(-1.0, -1.0)); + Expect.equals(true, Helper.EQ(0.0, 0.0)); + Expect.equals(true, Helper.EQ(1.0, 1.0)); + Expect.equals(false, Helper.EQ(-1.0, 0.0)); + Expect.equals(false, Helper.EQ(-1.0, 1.0)); + Expect.equals(false, Helper.EQ(0.0, 1.0)); + + Expect.equals(false, Helper.NE(-1.0, -1.0)); + Expect.equals(false, Helper.NE(0.0, 0.0)); + Expect.equals(false, Helper.NE(1.0, 1.0)); + Expect.equals(true, Helper.NE(-1.0, 0.0)); + Expect.equals(true, Helper.NE(-1.0, 1.0)); + Expect.equals(true, Helper.NE(0.0, 1.0)); + + Expect.equals(false, Helper.LT(-1.0, -1.0)); + Expect.equals(false, Helper.LT(0.0, 0.0)); + Expect.equals(false, Helper.LT(1.0, 1.0)); + Expect.equals(true, Helper.LT(-1.0, 0.0)); + Expect.equals(true, Helper.LT(-1.0, 1.0)); + Expect.equals(true, Helper.LT(0.0, 1.0)); + Expect.equals(false, Helper.LT(0.0, -1.0)); + Expect.equals(false, Helper.LT(1.0, -1.0)); + Expect.equals(false, Helper.LT(1.0, 0.0)); + + Expect.equals(true, Helper.LE(-1.0, -1.0)); + Expect.equals(true, Helper.LE(0.0, 0.0)); + Expect.equals(true, Helper.LE(1.0, 1.0)); + Expect.equals(true, Helper.LE(-1.0, 0.0)); + Expect.equals(true, Helper.LE(-1.0, 1.0)); + Expect.equals(true, Helper.LE(0.0, 1.0)); + Expect.equals(false, Helper.LE(0.0, -1.0)); + Expect.equals(false, Helper.LE(1.0, -1.0)); + Expect.equals(false, Helper.LE(1.0, 0.0)); + + Expect.equals(false, Helper.GT(-1.0, -1.0)); + Expect.equals(false, Helper.GT(0.0, 0.0)); + Expect.equals(false, Helper.GT(1.0, 1.0)); + Expect.equals(false, Helper.GT(-1.0, 0.0)); + Expect.equals(false, Helper.GT(-1.0, 1.0)); + Expect.equals(false, Helper.GT(0.0, 1.0)); + Expect.equals(true, Helper.GT(0.0, -1.0)); + Expect.equals(true, Helper.GT(1.0, -1.0)); + Expect.equals(true, Helper.GT(1.0, 0.0)); + + Expect.equals(true, Helper.GE(-1.0, -1.0)); + Expect.equals(true, Helper.GE(0.0, 0.0)); + Expect.equals(true, Helper.GE(1.0, 1.0)); + Expect.equals(false, Helper.GE(-1.0, 0.0)); + Expect.equals(false, Helper.GE(-1.0, 1.0)); + Expect.equals(false, Helper.GE(0.0, 1.0)); + Expect.equals(true, Helper.GE(0.0, -1.0)); + Expect.equals(true, Helper.GE(1.0, -1.0)); + Expect.equals(true, Helper.GE(1.0, 0.0)); + + Expect.equals(true, Helper.EQ(null, null)); + Expect.equals(false, Helper.EQ(null, "Str")); + Expect.equals(true, Helper.NE(null, 2)); + Expect.equals(false, Helper.NE(null, null)); + + Expect.equals(true, Helper.STRICT_EQ(null, null)); + Expect.equals(false, Helper.STRICT_EQ(null, "Str")); + Expect.equals(true, Helper.STRICT_NE(null, 2)); + Expect.equals(false, Helper.STRICT_NE(null, null)); + + Expect.equals(false, Helper.GT(1, 1.2)); + Expect.equals(true, Helper.GT(3, 1.2)); + Expect.equals(true, Helper.GT(2.0, 1)); + Expect.equals(false, Helper.GT(3.1, 4)); + + Expect.equals(false, Helper.GE(1, 1.2)); + Expect.equals(true, Helper.GE(3, 1.2)); + Expect.equals(true, Helper.GE(2.0, 1)); + Expect.equals(false, Helper.GE(3.1, 4)); + Expect.equals(true, Helper.GE(2.0, 2)); + Expect.equals(true, Helper.GE(2, 2.0)); + + Expect.equals(true, Helper.LT(1, 1.2)); + Expect.equals(false, Helper.LT(3, 1.2)); + Expect.equals(false, Helper.LT(2.0, 1)); + Expect.equals(true, Helper.LT(3.1, 4)); + + Expect.equals(true, Helper.LE(1, 1.2)); + Expect.equals(false, Helper.LE(3, 1.2)); + Expect.equals(false, Helper.LE(2.0, 1)); + Expect.equals(true, Helper.LE(3.1, 4)); + Expect.equals(true, Helper.LE(2.0, 2)); + Expect.equals(true, Helper.LE(2, 2.0)); + + // Bignums. + Expect.equals(true, Helper.LE(0xF00000000005, 0xF00000000006)); + Expect.equals(true, Helper.LE(0xF00000000005, 0xF00000000005)); + Expect.equals(false, Helper.LE(0xF00000000006, 0xF00000000005)); + Expect.equals(true, Helper.LE(12, 0xF00000000005)); + Expect.equals(true, Helper.LE(12.2, 0xF00000000005)); + + Expect.equals(true, Helper.EQ(4294967295, 4.294967295e9)); + Expect.equals(true, Helper.EQ(4.294967295e9, 4294967295)); + Expect.equals(false, Helper.EQ(4.294967295e9, 42)); + Expect.equals(false, Helper.EQ(42, 4.294967295e9)); + Expect.equals(false, Helper.EQ(4294967295, 42)); + Expect.equals(false, Helper.EQ(42, 4294967295)); + + // Fractions & mixed + Expect.equals(true, Helper.EQ(1.0, 1)); + Expect.equals(true, Helper.EQ(1.0, 1)); + Expect.equals(true, Helper.EQ(1, 1.0)); + Expect.equals(true, Helper.EQ(1, 1.0)); + Expect.equals(true, Helper.EQ(1.1, 1.1)); + Expect.equals(true, Helper.EQ(1.1, 1.1)); + Expect.equals(true, Helper.EQ(1.1, 1.1)); + + Expect.equals(false, Helper.GT(1, 1.2)); + Expect.equals(true, Helper.GT(1.2, 1)); + Expect.equals(true, Helper.GT(1.2, 1.1)); + Expect.equals(true, Helper.GT(1.2, 1.1)); + Expect.equals(true, Helper.GT(1.2, 1.1)); + + Expect.equals(true, Helper.LT(1, 1.2)); + Expect.equals(false, Helper.LT(1.2, 1)); + Expect.equals(false, Helper.LT(1.2, 1.1)); + Expect.equals(false, Helper.LT(1.2, 1.1)); + Expect.equals(false, Helper.LT(1.2, 1.1)); + + Expect.equals(false, Helper.GE(1.1, 1.2)); + Expect.equals(false, Helper.GE(1.1, 1.2)); + Expect.equals(true, Helper.GE(1.2, 1.2)); + Expect.equals(true, Helper.GE(1.2, 1.2)); + + // With non-number classes. + Expect.equals(false, Helper.EQ(1, "eeny")); + Expect.equals(false, Helper.EQ("meeny", 1)); + Expect.equals(false, Helper.EQ(1.1, "miny")); + Expect.equals(false, Helper.EQ("moe", 1.1)); + Expect.equals(false, Helper.EQ(1.1, "catch")); + Expect.equals(false, Helper.EQ("the", 1.1)); + + // With null. + Expect.equals(false, Helper.EQ(1, null)); + Expect.equals(false, Helper.EQ(null, 1)); + Expect.equals(false, Helper.EQ(1.1, null)); + Expect.equals(false, Helper.EQ(null, 1.1)); + Expect.equals(false, Helper.EQ(1.1, null)); + Expect.equals(false, Helper.EQ(null, 1.1)); + + // TODO(srdjan): Clarify behaviour of greater/less comparisons + // between numbers and non-numbers. + } +} + +main() { + ComparisonTest.testMain(); +} diff --git a/tests/language/src/CompoundAssignmentOperatorTest.dart b/tests/language/src/CompoundAssignmentOperatorTest.dart new file mode 100644 index 00000000000..9ed3e5da5f3 --- /dev/null +++ b/tests/language/src/CompoundAssignmentOperatorTest.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Tests that lhs of a compound assignement is executed only once. + + +class Indexed { + Indexed() : _f = new List(10), count = 0 { + _f[0] = 100; + _f[1] = 200; + } + operator [](i) { + count++; + return _f; + } + var count; + var _f; +} + +class CompoundAssignmentOperatorTest { + + static void testIndexed() { + Indexed indexed = new Indexed(); + Expect.equals(0, indexed.count); + var tmp = indexed[0]; + Expect.equals(1, indexed.count); + Expect.equals(100, indexed[4][0]); + Expect.equals(2, indexed.count); + Expect.equals(100, indexed[4][0]++); + Expect.equals(3, indexed.count); + Expect.equals(101, indexed[4][0]); + Expect.equals(4, indexed.count); + indexed[4][0] += 10; + Expect.equals(5, indexed.count); + Expect.equals(111, indexed[4][0]); + var i = 0; + indexed[3][i++] += 1; + Expect.equals(1, i); + } + + static void testMain() { + testIndexed(); + } +} +main() { + CompoundAssignmentOperatorTest.testMain(); +} diff --git a/tests/language/src/ConstConstructor1NegativeTest.dart b/tests/language/src/ConstConstructor1NegativeTest.dart new file mode 100644 index 00000000000..1f0f0c477e3 --- /dev/null +++ b/tests/language/src/ConstConstructor1NegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that class allocated via 'const' has a const constructor. + +interface I factory C { + I(int i); +} + +class C implements I { + C(int this.i) {} // <- missing const constructor. + final int i; +} + + +class ConstConstructor1NegativeTest { + static testMain() { + var i = const I(5); + print("Expected compilation failure: ${i.i}"); + } +} + +main() { + ConstConstructor1NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstConstructor2NegativeTest.dart b/tests/language/src/ConstConstructor2NegativeTest.dart new file mode 100644 index 00000000000..e55a09aae58 --- /dev/null +++ b/tests/language/src/ConstConstructor2NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that the const "allocated" class has a const constructor. + +class C { + C() {} +} + +class ConstConstructor2NegativeTest { + static testMain() { + var c = const C(); // Error: "const" requires const constructor. + } +} +main() { + ConstConstructor2NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstConstructorNegativeTest.dart b/tests/language/src/ConstConstructorNegativeTest.dart new file mode 100644 index 00000000000..b26ddc19156 --- /dev/null +++ b/tests/language/src/ConstConstructorNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that class with const constructor has only final fields. + + +class NixFinal { + const NixFinal(var v): finalField = v; // Expect compile error here. + final finalField; + var nixFinalField; +} + + +class ConstConstructorNegativeTest { + static testMain() { + var o = const NixFinal(5); + Expect.equals(true, false); + } +} + +main() { + ConstConstructorNegativeTest.testMain(); +} diff --git a/tests/language/src/ConstCounterNegativeTest.dart b/tests/language/src/ConstCounterNegativeTest.dart new file mode 100644 index 00000000000..38ba11e0a35 --- /dev/null +++ b/tests/language/src/ConstCounterNegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Bug: 4254106 Constant constructors must have (implicit) const parameters. + +class ConstCounter { + // Incorrect assignment of a non const function to a final field. + const ConstCounter(int i) : nextValue_ = (() => i++); + + final nextValue_; + + int nextValue() { return nextValue_(); } +} + +class ConstCounterNegativeTest { + static testMain() { + ConstCounter cc = const ConstCounter(3); + Expect.equals(3, cc.nextValue()); + } +} + +main() { + ConstCounterNegativeTest.testMain(); +} diff --git a/tests/language/src/ConstFactoryNegativeTest.dart b/tests/language/src/ConstFactoryNegativeTest.dart new file mode 100644 index 00000000000..dd88a6c8c3f --- /dev/null +++ b/tests/language/src/ConstFactoryNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// For Dart VM: tests that a "const factory" with body produces an error. +// For DartC: tests that a "const factory" is illegal. + +class ConstFactoryNegativeTest { + const factory ConstFactoryNegativeTest.one() { + } +} + +main() { + const ConstFactoryNegativeTest.one(); +} diff --git a/tests/language/src/ConstFieldNegativeTest.dart b/tests/language/src/ConstFieldNegativeTest.dart new file mode 100644 index 00000000000..8eaee6f7492 --- /dev/null +++ b/tests/language/src/ConstFieldNegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ConstFieldNegativeTest { + static const int FOO = 42; +} + +main() { + Expect.equals(42, ConstFieldNegativeTest.FOO); +} diff --git a/tests/language/src/ConstInit2NegativeTest.dart b/tests/language/src/ConstInit2NegativeTest.dart new file mode 100644 index 00000000000..05a1f9c5bce --- /dev/null +++ b/tests/language/src/ConstInit2NegativeTest.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that initializer is expected after final variable declaration. + +class Point { + final x_; + final y_; + const Point(x, y) : x_ = x, y_ = y; + operator +(int x) { return x; } +} + +class ConstInit2NegativeTest { + static final N = 1; // ok + static final O = 1 + 3; // ok + static final P = const Point(0, 0); // ok + static final Q = new Point(0, 0) + 1; // Error: not a compile time const. + + static testMain() { + Expect.equals(1, N); + Expect.equals(4, O); + Expect.equals(0, P.x_); + Expect.equals(0, Q.x_); + } +} + +main() { + ConstInit2NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstInit3NegativeTest.dart b/tests/language/src/ConstInit3NegativeTest.dart new file mode 100644 index 00000000000..9f87e51c2d1 --- /dev/null +++ b/tests/language/src/ConstInit3NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing circular initialization errors. + +class ConstInit3NegativeTest { + static final N = O + 1; // ok + static final O = N + 1; // Error: circular reference + + static testMain() { + Expect.equals(null, N); + } +} + +main() { + ConstInit3NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstInit4NegativeTest.dart b/tests/language/src/ConstInit4NegativeTest.dart new file mode 100644 index 00000000000..69b8abe9a52 --- /dev/null +++ b/tests/language/src/ConstInit4NegativeTest.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing circular initialization errors. + +class K { + static final n = 1; + static final p = const P(n, 0); +} + +class P { + const P(this._x, this._y) : _p = K.p; + final _x; + final _y; + final _p; +} + +class ConstInit4NegativeTest { + static testMain() { + var x = K.p; + } +} + +main() { + ConstInit4NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstInitNegativeTest.dart b/tests/language/src/ConstInitNegativeTest.dart new file mode 100644 index 00000000000..f218ab3fb7a --- /dev/null +++ b/tests/language/src/ConstInitNegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that initializer is expected after final variable declaration. + +class ConstInitNegativeTest { + static testMain() { + final int c0 = 5; + final int c1; + Expect.equals(c0, 5); + } +} + +main() { + ConstInitNegativeTest.testMain(); +} diff --git a/tests/language/src/ConstInitTest.dart b/tests/language/src/ConstInitTest.dart new file mode 100644 index 00000000000..9c64e69ee11 --- /dev/null +++ b/tests/language/src/ConstInitTest.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that initializers of static final fields are compile time constants. + +class Point { + final x_; + final y_; + const Point(x, y) : x_ = x, y_ = y; +} + +class ConstInitTest { + static final N = 1; + static final O = 1 + 3; + static final P = 2 * (O - N); + static final Q = const Point(0, 0); + + static final Q2 = const Point(0, 0); + static final P2 = 2 * (O - N); + static final O2 = 1 + 3; + static final N2 = 1; + + static testMain() { + Expect.equals(1, N); + Expect.equals(4, O); + Expect.equals(6, P); + Expect.equals(0, Q.x_); + Expect.equals(0, Q.y_); + + // class order doesn't matter. + Expect.equals(1, C2.N); + Expect.equals(4, C2.O); + Expect.equals(6, C2.P); + Expect.equals(0, C2.Q.x_); + Expect.equals(0, C2.Q.y_); + + // Nor the order of top level constants + Expect.equals(1, X.x_); + Expect.equals(4, X.y_); + } +} + +class C2 { + static final Q = const Point(0, 0); + static final P = 2 * (O - N); + static final O = 1 + 3; + static final N = 1; +} + +// Top level final +final X = const Point(C2.N, C2.O); + +main() { + ConstInitTest.testMain(); +} diff --git a/tests/language/src/ConstListTest.dart b/tests/language/src/ConstListTest.dart new file mode 100644 index 00000000000..e05f7a779bf --- /dev/null +++ b/tests/language/src/ConstListTest.dart @@ -0,0 +1,40 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ConstListTest { + + static testMain() { + List fixedList = new List(4); + List fixedList2 = new List(4); + List growableList = new List(); + List growableList2 = new List(); + for (int i = 0; i < 4; i++) { + fixedList[i] = i; + fixedList2[i] = i; + growableList.add(i); + growableList2.add(i); + } + Expect.equals(true, growableList == growableList); + Expect.equals(false, growableList == growableList2); + Expect.equals(true, fixedList == fixedList); + Expect.equals(false, fixedList == fixedList2); + Expect.equals(false, fixedList == growableList); + growableList.add(4); + Expect.equals(false, fixedList == growableList); + Expect.equals(4, growableList.removeLast()); + Expect.equals(false, fixedList == growableList); + fixedList[3] = 0; + Expect.equals(false, fixedList == growableList); + var a = [1, 2, 3.1]; + var b = [1, 2, 3.1]; + Expect.equals(false, a == b); + a = const [1, 2, 3.1]; + b = const [1, 2, 3.1]; + Expect.equals(true, a == b); + } +} + +main() { + ConstListTest.testMain(); +} diff --git a/tests/language/src/ConstTest.dart b/tests/language/src/ConstTest.dart new file mode 100644 index 00000000000..fad86ccd761 --- /dev/null +++ b/tests/language/src/ConstTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check const classes. + +class AConst { + const AConst() : b_ = 3 ; + final int b_; +} + + +class ConstTest { + static testMain() { + var o = const AConst(); + Expect.equals(3, o.b_); + } +} + +main() { + ConstTest.testMain(); +} diff --git a/tests/language/src/Constructor2NegativeTest.dart b/tests/language/src/Constructor2NegativeTest.dart new file mode 100644 index 00000000000..013ffc011f8 --- /dev/null +++ b/tests/language/src/Constructor2NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that all final instance fields of a class are initialized by constructors. + + +class Klass { + Klass(var v): field_ = v { } + final uninitializedFinalField_; + var field_; +} + + +class Constructor2NegativeTest { + static testMain() { + var o = new Klass(5); + } +} + +main() { + Constructor2NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorBodyTest.dart b/tests/language/src/ConstructorBodyTest.dart new file mode 100644 index 00000000000..e3658555544 --- /dev/null +++ b/tests/language/src/ConstructorBodyTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for constructors without function bodies. + +// Test a non-const constructor works without a body. +class First { + First(int this.value); + First.named(int this.value); + int value; +} + +// Test a const constructor works without a body. +class Second { + const Second(int this.value); + const Second.named(int this.value); + final int value; +} + +class ConstructorBodyTest { + static testMain() { + Expect.equals(4, new First(4).value); + Expect.equals(5, new First.named(5).value); + Expect.equals(6, new Second(6).value); + Expect.equals(7, new Second.named(7).value); + } +} + +main() { + ConstructorBodyTest.testMain(); +} diff --git a/tests/language/src/ConstructorCallWrongArgumentCountNegativeTest.dart b/tests/language/src/ConstructorCallWrongArgumentCountNegativeTest.dart new file mode 100644 index 00000000000..183a640d398 --- /dev/null +++ b/tests/language/src/ConstructorCallWrongArgumentCountNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test mismatch in argument counts. + +class ConstructorCallWrongArgumentCountNegativeTest { + static void testMain() { + Stockhorn nh = new Stockhorn(1); + nh.goodCall(1, 2, 3); + nh = new Stockhorn(); + } +} + +class Stockhorn { + Stockhorn(int a) {} + int goodCall(int a, int b, int c) { + return a + b; + } +} + +main() { + ConstructorCallWrongArgumentCountNegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorNegativeTest.dart b/tests/language/src/ConstructorNegativeTest.dart new file mode 100644 index 00000000000..864f7a7cfbe --- /dev/null +++ b/tests/language/src/ConstructorNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to make sure we catch missing new or const +// when allocating a new object. + + +class Point { + const Point(this.x, this.y); + final int x; + final int y; +} + + +class ConstructorNegativeTest { + static testMain() { + Point p = Point(1, 2); // should be const or new before Point(1,2). + } +} + +main() { + ConstructorNegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirect1NegativeTest.dart b/tests/language/src/ConstructorRedirect1NegativeTest.dart new file mode 100644 index 00000000000..55f36bd0ffc --- /dev/null +++ b/tests/language/src/ConstructorRedirect1NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Redirection constructors must not be cyclic. + +class A { + var x; + A(x) : this.named(x, 0); + A.named(x, int y) : this(x + y); +} + +class ConstructorRedirect1NegativeTest { + static testMain() { + } +} + +main() { + ConstructorRedirect1NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirect2NegativeTest.dart b/tests/language/src/ConstructorRedirect2NegativeTest.dart new file mode 100644 index 00000000000..a61fb96b42f --- /dev/null +++ b/tests/language/src/ConstructorRedirect2NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Redirection constructors must not be cyclic. + +class A { + var x; + A(x) : this(0); +} + +class ConstructorRedirect2NegativeTest { + static testMain() { + } +} + +main() { + ConstructorRedirect2NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirect3NegativeTest.dart b/tests/language/src/ConstructorRedirect3NegativeTest.dart new file mode 100644 index 00000000000..5904d4de7c6 --- /dev/null +++ b/tests/language/src/ConstructorRedirect3NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Redirection constructors must not initialize any fields. + +class A { + var x; + A(this.x) {} + A.named() : this(3), x = 5 {} +} + +class ConstructorRedirect3NegativeTest { + static testMain() { + } +} + +main() { + ConstructorRedirect3NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirect4NegativeTest.dart b/tests/language/src/ConstructorRedirect4NegativeTest.dart new file mode 100644 index 00000000000..36b7651e7f8 --- /dev/null +++ b/tests/language/src/ConstructorRedirect4NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Redirection constructors must not initialize any fields. + +class A { + var x; + A(this.x) {} + A.named(this.x) : this(3) {} +} + +class ConstructorRedirect4NegativeTest { + static testMain() { + } +} + +main() { + ConstructorRedirect4NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirect5NegativeTest.dart b/tests/language/src/ConstructorRedirect5NegativeTest.dart new file mode 100644 index 00000000000..3a29f807b27 --- /dev/null +++ b/tests/language/src/ConstructorRedirect5NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Redirection constructors must not call any super constructors. + +class A { + var x; + A(this.x) {} + A.named(x) : this(3), super() {} +} + +class ConstructorRedirect5NegativeTest { + static testMain() { + } +} + +main() { + ConstructorRedirect5NegativeTest.testMain(); +} diff --git a/tests/language/src/ConstructorRedirectTest.dart b/tests/language/src/ConstructorRedirectTest.dart new file mode 100644 index 00000000000..68603654f84 --- /dev/null +++ b/tests/language/src/ConstructorRedirectTest.dart @@ -0,0 +1,61 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for redirection constructors. + +class A { + var x; + A(this.x) {} + A.named(x, int y) : this(x + y); + A.named2(int x, int y, z) : this.named(staticFun(x, y), z); + + int staticFun(int v1, int v2) { + return v1 * v2; + } +} + +class B extends A { + B(y) : super(y + 1) {} + B.named(y) : super.named(y, y + 1) {} +} + +class C { + final x; + const C(this.x); + const C.named(x, int y) : this(x + y); +} + +class D extends C { + const D(y) : super(y + 1); + const D.named(y) : super.named(y, y + 1); +} + +class ConstructorRedirectTest { + static testMain() { + var a = new A(499); + Expect.equals(499, a.x); + a = new A.named(349, 499); + Expect.equals(349 + 499, a.x); + a = new A.named2(11, 42, 99); + Expect.equals(11 * 42 + 99, a.x); + + var b = new B(498); + Expect.equals(499, b.x); + b = new B.named(249); + Expect.equals(499, b.x); + + C c = const C(499); + Expect.equals(499, c.x); + c = const C.named(249, 250); + Expect.equals(499, c.x); + + D d = const D(498); + Expect.equals(499, d.x); + d = const D.named(249); + Expect.equals(499, d.x); + } +} + +main() { + ConstructorRedirectTest.testMain(); +} diff --git a/tests/language/src/ConstructorTest.dart b/tests/language/src/ConstructorTest.dart new file mode 100644 index 00000000000..4ca57b155f9 --- /dev/null +++ b/tests/language/src/ConstructorTest.dart @@ -0,0 +1,60 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for constructors and initializers. + +class A extends B { + A(x, y) : super(y), a = x { } + + var a; +} + + +class B { + var b; + + B(x) : b = x { } + + B.namedB(var x) : b = x {} +} + + +// Test the order of initialization: first the instance variable then +// the super constructor. +class Alpha { + Alpha(v) { + this.foo(v); + } +} + +class Beta extends Alpha { + Beta(v) : super(v), b = 1 {} + + foo(v) { + // Check that 'b' was initialized. + Expect.equals(1, b); + b = v; + } + + var b; +} + +class ConstructorTest { + static testMain() { + var o = new A(10, 2); + Expect.equals(10, o.a); + Expect.equals(2, o.b); + + var o1 = new B.namedB(10); + Expect.equals(10, o1.b); + + Expect.equals(22, o.a + o.b + o1.b); + + var beta = new Beta(3); + Expect.equals(3, beta.b); + } +} + +main() { + ConstructorTest.testMain(); +} diff --git a/tests/language/src/ContextArgsWithDefaultsTest.dart b/tests/language/src/ContextArgsWithDefaultsTest.dart new file mode 100644 index 00000000000..08c36ac54b4 --- /dev/null +++ b/tests/language/src/ContextArgsWithDefaultsTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ContextArgsWithDefaultsTest { + static void testMain() { + crasher(1, 'foo')(); + } + + static void crasher(int fixed, [String optional = '']) { + return () { + Expect.equals(1, fixed); + Expect.equals('foo', optional); + }; + } + +} + +main() { + ContextArgsWithDefaultsTest.testMain(); +} diff --git a/tests/language/src/ContextTest.dart b/tests/language/src/ContextTest.dart new file mode 100644 index 00000000000..ec59c94bb93 --- /dev/null +++ b/tests/language/src/ContextTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for capturing. + +class ContextTest { + static foo(Function f) { + return f(); + } + + static void testMain() { + int x = 42; + bar() { return x; } + x++; + Expect.equals(43, foo(bar)); + } +} + +main() { + ContextTest.testMain(); +} diff --git a/tests/language/src/ContinueTest.dart b/tests/language/src/ContinueTest.dart new file mode 100644 index 00000000000..312a00b00ea --- /dev/null +++ b/tests/language/src/ContinueTest.dart @@ -0,0 +1,58 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for continue in for, do/while and while loops. + +class ContinueTest { + static testMain() { + int i; + int forCounter = 0; + for (i = 0; i < 10; i++) { + if (i > 3) continue; + forCounter++; + } + Expect.equals(4, forCounter); + Expect.equals(10, i); + + i = 0; + int doWhileCounter = 0; + do { + i++; + if (i > 3) continue; + doWhileCounter++; + } while (i < 10); + Expect.equals(3, doWhileCounter); + Expect.equals(10, i); + + i = 0; + int whileCounter = 0; + while (i < 10) { + i++; + if (i > 3) continue; + whileCounter++; + } + Expect.equals(3, whileCounter); + Expect.equals(10, i); + + // Use a label to continue to the outer loop. + i = 0; + L: while (i < 50) { + i += 3; + while (i < 30) { + i += 2; + if (i < 10) { + continue L; + } else { + i++; + break; + } + } + break; + } + Expect.equals(11, i); + } +} + +main() { + ContinueTest.testMain(); +} diff --git a/tests/language/src/DefaultFactoryTest.dart b/tests/language/src/DefaultFactoryTest.dart new file mode 100644 index 00000000000..417b36bcc73 --- /dev/null +++ b/tests/language/src/DefaultFactoryTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program for testing default factories. + +interface Vehicle factory GoogleOne { + Vehicle(); +} + + +class Bike implements Vehicle { + Bike.redOne() {} +} + + +interface SpaceShip factory GoogleOne { + SpaceShip(); +} + + +class GoogleOne implements SpaceShip { + GoogleOne.internal_() {} + factory GoogleOne() { return new GoogleOne.internal_(); } + factory Vehicle() { return new Bike.redOne(); } +} + + +class DefaultFactoryTest { + static testMain() { + Expect.equals(true, (new Bike.redOne()) is Bike); + Expect.equals(true, (new SpaceShip()) is GoogleOne); + Expect.equals(true, (new Vehicle()) is Bike); + } +} + +main() { + DefaultFactoryTest.testMain(); +} diff --git a/tests/language/src/DefaultImplementationTest.dart b/tests/language/src/DefaultImplementationTest.dart new file mode 100644 index 00000000000..937ba1e87ba --- /dev/null +++ b/tests/language/src/DefaultImplementationTest.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to verify that factory classes are working. + +interface Point factory PointImplementation { + Point(x, y); + + final int x; + final int y; +} + +class PointImplementation implements Point { + const PointImplementation(int x, int y) : this.x = x, this.y = y; + final int x; + final int y; +} + +class DefaultImplementationTest { + static void testMain() { + Point point = new Point(4, 2); + Expect.equals(4, point.x); + Expect.equals(2, point.y); + } +} + +main() { + DefaultImplementationTest.testMain(); +} diff --git a/tests/language/src/DefaultInitTest.dart b/tests/language/src/DefaultInitTest.dart new file mode 100644 index 00000000000..5113277865f --- /dev/null +++ b/tests/language/src/DefaultInitTest.dart @@ -0,0 +1,64 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests static and instance fields initialization. +class DefaultInitTest { + static testMain() { + Expect.equals(0, A.a); + Expect.equals(2, A.b); + Expect.equals(null, A.c); + + A a1 = new A(42); + Expect.equals(42, a1.d); + Expect.equals(null, a1.e); + + A a2 = new A.named(43); + Expect.equals(null, a2.d); + Expect.equals(43, a2.e); + + Expect.equals(42, B.instance.x); + Expect.equals(3, C.instance.z); + } +} + +class A { + static final int a = 0; + static final int b = 2; + static int c; + int d; + int e; + + A(int val) { + d = val; + } + + A.named(int val) { + e = val; + } +} + +// The following tests cover cases described in b/4101270 + +class B { + static final B instance = const B(); + // by putting this field after the static initializer above, the JS code gen + // was calling the constructor before the setter of this property was defined. + final int x; + const B() : this.x = (41 + 1); +} + +class C { + // forward reference to another class + static final D instance = const D(); + C() {} +} + +class D { + const D(): this.z = 3; + final int z; +} + +main() { + DefaultInitTest.testMain(); +} diff --git a/tests/language/src/DeoptimizationTest.dart b/tests/language/src/DeoptimizationTest.dart new file mode 100644 index 00000000000..7f138f4cc61 --- /dev/null +++ b/tests/language/src/DeoptimizationTest.dart @@ -0,0 +1,173 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test deoptimization. + +class SmiCompares { + // Test deoptimization when one argument is known to be Smi. + static bool smiCompareLessThan2(a) { + return a < 2; + } + + // Test deoptimization when one argument is known to be Smi. + static bool smiCompareGreaterThan2(a) { + return 2 < a; + } + + // Test deoptimization when both arguments unknown. + static bool smiCompareLessThan(a, b) { + return a < b; + } + + // Test deoptimization when both arguments unknown. + static bool smiCompareGreaterThan(a, b) { + return a > b; + } + + static smiComparesTest() { + for (int i = 0; i < 2000; i++) { + Expect.equals(true, smiCompareLessThan2(1)); + Expect.equals(false, smiCompareLessThan2(3)); + Expect.equals(false, smiCompareGreaterThan2(1)); + Expect.equals(true, smiCompareGreaterThan2(3)); + Expect.equals(true, smiCompareLessThan(1, 2)); + Expect.equals(false, smiCompareGreaterThan(1, 2)); + } + // Deoptimize by passing a double instead of Smi + Expect.equals(true, smiCompareLessThan2(1.0)); + Expect.equals(false, smiCompareGreaterThan2(1.0)); + Expect.equals(true, smiCompareLessThan(1.0, 2)); + Expect.equals(false, smiCompareGreaterThan(1, 2.0)); + } +} + + +class SmiBinop { + static subWithLiteral(a) { + return a - 1; + } + + static void smiBinopTest() { + for (int i = 0; i < 2000; i++) { + Expect.equals(2, subWithLiteral(3)); + } + // Deoptimize. + Expect.equals(2.0, subWithLiteral(3.0)); + } +} + + +class ObjectsEquality { + static bool compareEqual(a, b) { + return a == b; + } + + static bool compareNotEqual(a, b) { + return a != b; + } + + // Use only Object.==. + static void objectsEqualityTest() { + var a = new ObjectsEquality(); + var b = new ObjectsEquality(); + final nan = 0.0/0.0; + for (int i = 0; i < 1000; i++) { + Expect.equals(true, compareEqual(a, a)); + Expect.equals(true, compareEqual(null, null)); + Expect.equals(false, compareEqual(null, a)); + Expect.equals(false, compareEqual(a, null)); + Expect.equals(true, compareEqual(b, b)); + Expect.equals(false, compareEqual(a, b)); + + Expect.equals(false, compareNotEqual(a, a)); + Expect.equals(false, compareNotEqual(null, null)); + Expect.equals(true, compareNotEqual(null, a)); + Expect.equals(true, compareNotEqual(a, null)); + Expect.equals(false, compareNotEqual(b, b)); + Expect.equals(true, compareNotEqual(a, b)); + } + var c = new SmiBinop(); + // Deoptimize. + Expect.equals(true, compareEqual(c, c)); + Expect.equals(false, compareEqual(c, null)); + Expect.equals(false, compareNotEqual(c, c)); + Expect.equals(true, compareNotEqual(c, null)); + } +} + +class DeoptimizationTest { + static foo(a, b) { + return a - b; + } + + static test1() { + for (int i = 0; i < 2000; i++) { + Expect.equals(2, foo(3, 1)); // <-- Optimizes 'foo', + } + Expect.equals(2.2, foo(1.2, -1.0)); // <-- Deoptimizes 'foo'. + for (int i = 0; i < 10000; i++) { + Expect.equals(2, foo(3, 1)); // <-- Optimizes 'foo'. + } + Expect.equals(2.2, foo(1.2, -1)); // <-- Deoptimizes 'foo'. + } + + static moo(n) { + return ++n; + } + + static test2() { + for (int i = 0; i < 2000; i++) { + Expect.equals(4, moo(3)); // <-- Optimizes 'moo', + } + Expect.equals(2.2, moo(1.2)); // <-- Deoptimizes 'moo'. + for (int i = 0; i < 10000; i++) { + Expect.equals(4, moo(3)); // <-- Optimizes 'moo'. + } + Expect.equals(2.2, moo(1.2)); // <-- Deoptimizes 'moo'. + } + + static test3() { + for (int i = 0; i < 2000; i++) { + Expect.equals(2.0, foo(3.0, 1.0)); // <-- Optimizes 'foo', + } + Expect.equals(2, foo(1, -1)); // <-- Deoptimizes 'foo'. + for (int i = 0; i < 2000; i++) { + Expect.equals(2.0, foo(3.0, 1.0)); // <-- Optimizes 'foo', + } + Expect.equals(2.2, moo(1.2)); // <-- Deoptimizes 'moo'. + } + + static bool compareInt(a, b) { + return a < b; + } + + static bool compareDouble(a, b) { + return a < b; + } + + static test4() { + for (int i = 0; i < 2000; i++) { + Expect.equals(true, compareInt(1, 2)); + Expect.equals(true, compareDouble(1.0, 2.0)); + } + // Trigger deoptimization in compareInt and compareDouble. + Expect.equals(true, compareInt(1, 2.0)); + Expect.equals(true, compareDouble(1.0, 2)); + } + + + + static void testMain() { + test1(); + test2(); + test3(); + test4(); + SmiCompares.smiComparesTest(); + SmiBinop.smiBinopTest(); + ObjectsEquality.objectsEqualityTest(); + } +} + +main() { + DeoptimizationTest.testMain(); +} diff --git a/tests/language/src/DivByZeroTest.dart b/tests/language/src/DivByZeroTest.dart new file mode 100644 index 00000000000..382d7db85e5 --- /dev/null +++ b/tests/language/src/DivByZeroTest.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test integer div by zero. + +class DivByZeroTest { + + static double divBy(int a, int b) { + var result = a/b; + return 1.0 * result; + } + + static bool moustacheDivBy(int a, int b) { + var val = null; + try { + val = a~/b; + } catch (var e) { + return true; + } + print("Should not have gotten: $val"); + return false; + } + + static void testMain() { + Expect.isTrue(divBy(0, 0).isNaN()); + Expect.isTrue(moustacheDivBy(0, 0)); + } +} + +main() { + DivByZeroTest.testMain(); +} diff --git a/tests/language/src/DoWhileTest.dart b/tests/language/src/DoWhileTest.dart new file mode 100644 index 00000000000..d4edf8672a8 --- /dev/null +++ b/tests/language/src/DoWhileTest.dart @@ -0,0 +1,61 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing do while statement. + +class Helper { + static int f1(bool b) { + do return 1; + while (b); + return 2; + } + + static int f2(bool b) { + do { + return 1; + } while (b); + return 2; + } + + static int f3(bool b) { + do + ; + while (b); + return 2; + } + + static int f4(bool b) { + do { + } while (b); + return 2; + } + + static int f5(int n) { + int i = 0; + do { + i++; + } while (i < n); + return i; + } +} + +class DoWhileTest { + static testMain() { + Expect.equals(1, Helper.f1(true)); + Expect.equals(1, Helper.f1(false)); + Expect.equals(1, Helper.f2(true)); + Expect.equals(1, Helper.f2(false)); + Expect.equals(2, Helper.f3(false)); + Expect.equals(2, Helper.f4(false)); + Expect.equals(1, Helper.f5(-2)); + Expect.equals(1, Helper.f5(-1)); + Expect.equals(1, Helper.f5(0)); + Expect.equals(1, Helper.f5(1)); + Expect.equals(2, Helper.f5(2)); + Expect.equals(3, Helper.f5(3)); + } +} + +main() { + DoWhileTest.testMain(); +} diff --git a/tests/language/src/DoubleComparisonTest.dart b/tests/language/src/DoubleComparisonTest.dart new file mode 100644 index 00000000000..cf00962469c --- /dev/null +++ b/tests/language/src/DoubleComparisonTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Tests VM optimizing compiler negate condition for doubles (bug 5376516). + +loop() { + for (double d = 0.0; d < 1100.0; d++) {} + for (double d = 0.0; d <= 1100.0; d++) {} + for (double d = 1000.0; d > 0.0; d--) {} + for (double d = 1000.0; d >= 0.0; d--) {} +} + +main() { + loop(); + loop(); +} diff --git a/tests/language/src/DynamicCallTest.dart b/tests/language/src/DynamicCallTest.dart new file mode 100644 index 00000000000..07cf6ffc5b8 --- /dev/null +++ b/tests/language/src/DynamicCallTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing dynamic calls. + +class Helper { + Helper() {} + int foo(int i) { + return i; + } +} + +class DynamicCallTest { + static int testMain() { + Helper obj = new Helper(); + Expect.equals(1, obj.foo(1)); + } +} + +main() { + DynamicCallTest.testMain(); +} diff --git a/tests/language/src/EmptyBlockCaseTest.dart b/tests/language/src/EmptyBlockCaseTest.dart new file mode 100644 index 00000000000..4b80d96430a --- /dev/null +++ b/tests/language/src/EmptyBlockCaseTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that a case with an empty block does not fall through. + +class EmptyBlockCaseTest { + + static testMain() { + var exception = null; + try { + switch (1) { + case 1: {} + case 2: Expect.equals(true, false); + } + } catch (FallThroughError e) { + exception = e; + } + Expect.equals(true, exception != null); + } +} + +main() { + EmptyBlockCaseTest.testMain(); +} diff --git a/tests/language/src/EmptyBodyMemberNegativeTest.dart b/tests/language/src/EmptyBodyMemberNegativeTest.dart new file mode 100644 index 00000000000..dbf20668cbc --- /dev/null +++ b/tests/language/src/EmptyBodyMemberNegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class EmptyBodyMemberNegativeTest { + int foo(); + + static testMain() { + } +} + + +main() { + EmptyBodyMemberNegativeTest.testMain(); +} diff --git a/tests/language/src/EmptyMain.dart b/tests/language/src/EmptyMain.dart new file mode 100644 index 00000000000..7def6efcafa --- /dev/null +++ b/tests/language/src/EmptyMain.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() {} diff --git a/tests/language/src/ExampleConstructorTest.dart b/tests/language/src/ExampleConstructorTest.dart new file mode 100644 index 00000000000..6ae7b48bfdc --- /dev/null +++ b/tests/language/src/ExampleConstructorTest.dart @@ -0,0 +1,40 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing order of constructor invocation. + +var trace = ""; + +int rec(int i) { + trace += "$i "; + return i; +} + +class A { + A(int x) : x = rec(2) { + Expect.equals(1, x); // Parameter x + Expect.equals(2, this.x); + rec(5); + } + final int x; +} + +class B extends A { + B(this.a, int y, int z) + : super(rec(1)), z = rec(3), y = rec(4) { + rec(6); + } + int a; + int y; + int z; +} + +main() { + var test = new B(rec(0), 0, 0); + Expect.equals(0, test.a); + Expect.equals(2, test.x); + Expect.equals(4, test.y); + Expect.equals(3, test.z); + Expect.equals("0 1 2 3 4 5 6 ", trace); +} + diff --git a/tests/language/src/ExceptionIdentityTest.dart b/tests/language/src/ExceptionIdentityTest.dart new file mode 100644 index 00000000000..c50475c84a4 --- /dev/null +++ b/tests/language/src/ExceptionIdentityTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that an object when thrown stays the same. + +class A { + A(); +} + +check(exception) { + try { + throw exception; + } catch (var e) { + Expect.equals(exception, e); + } +} + +main() { + check("str"); + check(new A()); + check(1); + check(1.2); +} diff --git a/tests/language/src/ExceptionTest.dart b/tests/language/src/ExceptionTest.dart new file mode 100644 index 00000000000..09f3032108f --- /dev/null +++ b/tests/language/src/ExceptionTest.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +class ExceptionTest { + static testMain() { + int i = 0; + try { + throw "Hello"; + } catch (String s) { + print(s); + i += 10; + } + + try { + throw "bye"; + } catch (String s) { + print(s); + i += 10; + } + Expect.equals(20, i); + } +} + +main() { + ExceptionTest.testMain(); +} diff --git a/tests/language/src/ExecuteFinally1Test.dart b/tests/language/src/ExecuteFinally1Test.dart new file mode 100644 index 00000000000..946f3bb96e5 --- /dev/null +++ b/tests/language/src/ExecuteFinally1Test.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1() { + try { + int j; + j = func(); + i = 1; + return i; // Value of i on return is 1. + } finally { + i = i + 800; // Should get executed on return. + } + return i + 200; // Should not get executed. + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally1Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(1, obj.f1()); + Expect.equals(801, obj.i); + } +} + +main() { + ExecuteFinally1Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally2Test.dart b/tests/language/src/ExecuteFinally2Test.dart new file mode 100644 index 00000000000..ab7e93aebb4 --- /dev/null +++ b/tests/language/src/ExecuteFinally2Test.dart @@ -0,0 +1,50 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1() { + try { + int j; + j = func(); + try { + i = 1; + return i; // Value of i is 1 on return. + } finally { + i = i + 400; // Should get executed when we return. + } + i = 2; // Should not get executed. + return i; + } finally { + i = i + 800; // Should get executed when we return. + } + return i + 200; // Should not get executed. + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally2Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(1, obj.f1()); + Expect.equals(1201, obj.i); + } +} + +main() { + ExecuteFinally2Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally3Test.dart b/tests/language/src/ExecuteFinally3Test.dart new file mode 100644 index 00000000000..122402ade2c --- /dev/null +++ b/tests/language/src/ExecuteFinally3Test.dart @@ -0,0 +1,72 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1() { + try { + try { + int j; + j = func(); + L1: + while (i <= 0) { + if (i == 0) { + try { + i = 1; + func(); + try { + int j; + j = func(); + while (j < 50) { + j += func(); + if (j > 30) { + continue L1; // Break out of nested try blocks. + } + } + i = 200000; // Should not get executed. + } finally { + i = i + 200; // Should get executed when we break out. + } + } finally { + i = i + 400; // Should get executed when we break out. + } + } + } + } finally { + i = i + 800; // Should get executed as normal control flow. + } + return i; // Value of i should be 1401. + } finally { + i = i + 1600; // Should get executed as part of return above. + } + i = i + 2000000; // Should not get executed. + return 1; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally3Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(1401, obj.f1()); + Expect.equals(3001, obj.i); + } +} + +main() { + ExecuteFinally3Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally4Test.dart b/tests/language/src/ExecuteFinally4Test.dart new file mode 100644 index 00000000000..fedf2f05f9a --- /dev/null +++ b/tests/language/src/ExecuteFinally4Test.dart @@ -0,0 +1,49 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1() { + try { + int j; + j = func(); + i = 1; + } finally { + i = i + 10; + } + return i + 200; // Should return here with i = 211. + try { + int j; + j = func(); + } finally { + i = i + 10; // Should not get executed as part of return above. + } + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally4Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(211, obj.f1()); + Expect.equals(11, obj.i); + } +} + +main() { + ExecuteFinally4Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally5Test.dart b/tests/language/src/ExecuteFinally5Test.dart new file mode 100644 index 00000000000..dbdb016612b --- /dev/null +++ b/tests/language/src/ExecuteFinally5Test.dart @@ -0,0 +1,69 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1(int param) { + if (param == 0) { + try { + int j; + j = func(); + try { + i = 1; + return i; // Value of i is 1 on return. + } finally { + i = i + 400; // Should get executed when we return. + } + i = 2; // Should not get executed. + return i; + } finally { + i = i + 800; // Should get executed when we return. + } + return i + 200; // Should not get executed. + } + try { + int j; + j = func(); + try { + i = 4; + return i; // Value of i is 1 on return. + } finally { + i = i + 100; // Should get executed when we return. + } + i = 2; // Should not get executed. + return i; + } finally { + i = i + 200; // Should get executed when we return. + } + return i + 200; // Should not get executed. + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally5Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(1, obj.f1(0)); + Expect.equals(1201, obj.i); + Expect.equals(4, obj.f1(1)); + Expect.equals(304, obj.i); + } +} + +main() { + ExecuteFinally5Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally6Test.dart b/tests/language/src/ExecuteFinally6Test.dart new file mode 100644 index 00000000000..dae478bf093 --- /dev/null +++ b/tests/language/src/ExecuteFinally6Test.dart @@ -0,0 +1,73 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks on +// control flow breaks because of 'return', 'continue' etc. + + +class Helper { + Helper() : i = 0 { } + + int f1() { + try { + try { + int j; + j = func(); + L1: + while (i <= 0) { + if (i == 0) { + try { + i = 1; + func(); + try { + int j; + j = func(); + L1: + while (j < 50) { + j += func(); + if (j > 30) { + break L1; // Break out of nested try blocks. + } + } + i += 200000; // Should get executed. + } finally { + i = i + 200; // Should get executed as normal control flow. + } + } finally { + i = i + 400; // Should get executed as normal control flow. + } + } + } + } finally { + i = i + 800; // Should get executed as normal control flow. + } + return i; // Value of i should be 201401. + } finally { + i = i + 1600; // Should get executed as part of return above. + } + i = i + 2000000; // Should not get executed. + return 1; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } + + int i; +} + +class ExecuteFinally6Test { + static testMain() { + Helper obj = new Helper(); + Expect.equals(201401, obj.f1()); + Expect.equals(203001, obj.i); + } +} + +main() { + ExecuteFinally6Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally7Test.dart b/tests/language/src/ExecuteFinally7Test.dart new file mode 100644 index 00000000000..a87880a57ea --- /dev/null +++ b/tests/language/src/ExecuteFinally7Test.dart @@ -0,0 +1,56 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing execution of finally blocks after an exception +// is thrown from inside a local function capturing a variable. + + +class MyException { + const MyException(String message) : message_ = message; + final String message_; +} + +class Helper { + static int f1(int k) { + var b; + try { + var a = new List(10); + int i = 0; + while (i < 10) { + int j = i; + a[i] = () { + if (j == 5) { + throw new MyException("Test for exception being thrown"); + } + k += 10; + return j; + }; + if (i == 0) { + b = a[i]; + } + i++; + } + for(int i = 0; i < 10; i++) { + a[i](); + } + } catch (MyException exception) { + k += 100; + print(exception.message_); + b(); + } finally { + k += 1000; + b(); + } + return k; + } +} + +class ExecuteFinally7Test { + static testMain() { + Expect.equals(1171, Helper.f1(1)); + } +} + +main() { + ExecuteFinally7Test.testMain(); +} diff --git a/tests/language/src/ExecuteFinally8Test.dart b/tests/language/src/ExecuteFinally8Test.dart new file mode 100644 index 00000000000..ad08c69f66f --- /dev/null +++ b/tests/language/src/ExecuteFinally8Test.dart @@ -0,0 +1,81 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// This test ensures that the finally block executes correctly when +// there are throw, break and return statements in the finally block. + +class Hello { + static var sum; + + static foo() { + sum = 0; + try { + sum += 1; + return 'hi'; + } finally { + sum += 1; + throw 'ball'; + sum += 1; + } + } + + static foo1() { + bool loop = true; + sum = 0; + L: + while (loop) { + try { + sum += 1; + return 'hi'; + } finally { + sum += 1; + break L; + sum += 1; + } + } + } + + static foo2() { + bool loop = true; + sum = 0; + try { + sum += 1; + return 'hi'; + } finally { + sum += 1; + return 10; + sum += 1; + } + } + + static foo3() { + sum = 0; + try { + sum += 1; + return 'hi'; + } finally { + sum += 1; + return 10; + sum += 1; + } + } + + static void main() { + foo1(); + Expect.equals(2, sum); + foo2(); + Expect.equals(2, sum); + foo3(); + Expect.equals(2, sum); + try { + foo(); + } catch (var e) { + } + Expect.equals(2, sum); + } + +} + +main() { + Hello.main(); +} diff --git a/tests/language/src/ExecuteFinally9Test.dart b/tests/language/src/ExecuteFinally9Test.dart new file mode 100644 index 00000000000..6ed739a36cc --- /dev/null +++ b/tests/language/src/ExecuteFinally9Test.dart @@ -0,0 +1,65 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// This test ensures that the finally block executes correctly when +// there are throw, break and return statements in the finally block. + +class Hello { + static var sum; + + static foo() { + sum = 0; + try { + sum += 1; + return 'hi'; + } catch (var e) { + sum += 1; + throw 'ball'; + sum += 1; + } finally { + sum += 1; + throw 'ball'; + sum += 1; + } + } + + static foo1() { + bool loop = true; + sum = 0; + L:while (loop) { + try { + sum += 1; + return 'hi'; + } catch (var ex) { + sum += 1; + } finally { + try { + L1:while (loop) { + sum += 1; + break L; + sum += 1; + } + } catch (var ex) { + sum += 1; + } finally { + sum += 1; + } + } + } + } + + static void main() { + foo1(); + Expect.equals(3, sum); + try { + foo(); + } catch (var e) { + } + Expect.equals(2, sum); + } + +} + +main() { + Hello.main(); +} diff --git a/tests/language/src/ExpectTest.dart b/tests/language/src/ExpectTest.dart new file mode 100644 index 00000000000..a62f63dbd37 --- /dev/null +++ b/tests/language/src/ExpectTest.dart @@ -0,0 +1,77 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Testing the Expect class. + +class ExpectTest { + + static testEquals(a) { + try { + Expect.equals("AB", a, "within testEquals"); + } catch (Exception msg) { + print(msg); + return; + } + Expect.equals("AB", a + "B"); + throw "Expect.equals did not fail"; + } + + static testIsTrue(f) { + try { + Expect.isTrue(f); + } catch (Exception msg) { + print(msg); + return; + } + Expect.isFalse(f); + throw "Expect.isTrue did not fail"; + } + + static testIsFalse(t) { + try { + Expect.isFalse(t); + } catch (Exception msg) { + print(msg); + return; + } + Expect.isTrue(t); + throw "Expect.isFalse did not fail"; + } + + static testIdentical(a) { + var ab = a + "B"; + try { + Expect.identical("AB", ab); + } catch (Exception msg) { + print(msg); + return; + } + Expect.equals("AB", ab); + throw "Expect.identical did not fail"; + } + + static testFail() { + try { + Expect.fail("fail now"); + } catch (Exception msg) { + print(msg); + return; + } + throw "Expect.fail did not fail"; + } + + static void testMain() { + testEquals("A"); + testIsTrue(false); + testIsTrue(1); + testIsFalse(true); + testIsFalse(0); + testIdentical("A"); + testFail(); + } + +} + +main() { + ExpectTest.testMain(); +} diff --git a/tests/language/src/FactoryTest.dart b/tests/language/src/FactoryTest.dart new file mode 100644 index 00000000000..5176eba68e2 --- /dev/null +++ b/tests/language/src/FactoryTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing factories. + +class A { + factory A(n) { + return new A.internal(n); + } + A.internal(n) : n_ = n {} + var n_; +} + +class B { + factory B.my() { + return new B(3); + } + B(n) : n_ = n {} + var n_; +} + +class FactoryTest { + static testMain() { + new B.my(); + var b = new B.my(); + Expect.equals(3, b.n_); + var a = new A(5); + Expect.equals(5, a.n_); + } +} + +main() { + FactoryTest.testMain(); +} diff --git a/tests/language/src/FailingMain.dart b/tests/language/src/FailingMain.dart new file mode 100644 index 00000000000..3b922772f85 --- /dev/null +++ b/tests/language/src/FailingMain.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + Expect.equals(true, false); +} diff --git a/tests/language/src/FannkuchTest.dart b/tests/language/src/FannkuchTest.dart new file mode 100644 index 00000000000..356f20f588f --- /dev/null +++ b/tests/language/src/FannkuchTest.dart @@ -0,0 +1,69 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// The Great Computer Language Shootout +// http://shootout.alioth.debian.org/ +// Ported from JavaScript contributed by Isaac Gouy. +// Description: Repeatedly acccess a tiny integer-sequence. + +class FannkuchTest { + static fannkuch(n) { + var p = new List(n), q = new List(n), s = new List(n); + var sign = 1, maxflips = 0, sum = 0, m = n - 1; + for (var i = 0; i < n; i++) { p[i] = i; q[i] = i; s[i] = i; } + do { + // Copy and flip. + var q0 = p[0]; // Cache 0th element. + if (q0 != 0) { + for (var i = 1; i < n; i++) q[i] = p[i]; // Work on a copy. + var flips = 1; + do { + var qq = q[q0]; + if (qq == 0) { // ... until 0th element is 0. + sum += sign * flips; + if (flips > maxflips) maxflips = flips; // New maximum? + break; + } + q[q0] = q0; + if (q0 >= 3) { + var i = 1, j = q0 - 1, t; + do { t = q[i]; q[i] = q[j]; q[j] = t; i++; j--; } while (i < j); + } + q0 = qq; flips++; + } while (true); + } + if (sign == 1) { + var t = p[1]; p[1] = p[0]; p[0] = t; sign = -1; // Rotate 0<-1. + } else { + // Rotate 0<-1 and 0<-1<-2. + var t = p[1]; + p[1] = p[2]; + p[2] = t; + sign = 1; + for(var i = 2; i < n; i++) { + var sx = s[i]; + if (sx != 0) { s[i] = sx-1; break; } + if (i == m) { + return [sum, maxflips]; + } + s[i] = i; + // Rotate 0<-...<-i+1. + t = p[0]; + for(var j=0; j<=i; j++) { p[j] = p[j+1]; } + p[i+1] = t; + } + } + } while (true); + } + + static testMain() { + var n = 6; + var pf = fannkuch(n); + Expect.equals(49, pf[0]); + Expect.equals(10, pf[1]); + print("${pf[0]}\nPfannkuchen($n) = ${pf[1]}"); + } +} +main() { + FannkuchTest.testMain(); +} diff --git a/tests/language/src/FauxverrideTest.dart b/tests/language/src/FauxverrideTest.dart new file mode 100644 index 00000000000..a50e4acbd3f --- /dev/null +++ b/tests/language/src/FauxverrideTest.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that static members cannot be overridden. + +m() {} + +class Super { + Super() {} + // No error from hiding. + static m() {} + + static var i; + + instanceMethod() {} +} + +class Sub extends Super { + Sub() : super(); + static m() {} /// 01: compile-time error + + static var i; /// 02: compile-time error + + static instanceMethod() {} /// 03: compile-time error + + static i() {} /// 04: compile-time error + + static var instanceMethod; /// 05: compile-time error + + foo() {} +} + +main() { + new Sub().foo(); +} diff --git a/tests/language/src/FiboTest.dart b/tests/language/src/FiboTest.dart new file mode 100644 index 00000000000..28e3eaecaef --- /dev/null +++ b/tests/language/src/FiboTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program calculating the Fibonacci sequence. + +class Helper { + static int fibonacci(int n) { + int a = 0, b = 1, i = 0; + while (i++ < n) { + a = a + b; + b = a - b; + } + return a; + } +} + +class FiboTest { + static testMain() { + Expect.equals(0, Helper.fibonacci(0)); + Expect.equals(1, Helper.fibonacci(1)); + Expect.equals(1, Helper.fibonacci(2)); + Expect.equals(2, Helper.fibonacci(3)); + Expect.equals(3, Helper.fibonacci(4)); + Expect.equals(5, Helper.fibonacci(5)); + Expect.equals(102334155, Helper.fibonacci(40)); + } +} + +main() { + FiboTest.testMain(); +} diff --git a/tests/language/src/Field1NegativeTest.dart b/tests/language/src/Field1NegativeTest.dart new file mode 100644 index 00000000000..78274757fe3 --- /dev/null +++ b/tests/language/src/Field1NegativeTest.dart @@ -0,0 +1,35 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have setter/getter functions and fields +// in the class. + +class C { + var a; + + get a() { + return 1; + } + set a(int val) { + var x = val; + } + + get b() { + return 2; + } + set b(int val) { + var x = val; + } +} + + +class Field1NegativeTest { + static testMain() { + } +} + + +main() { + Field1NegativeTest.testMain(); +} diff --git a/tests/language/src/Field2NegativeTest.dart b/tests/language/src/Field2NegativeTest.dart new file mode 100644 index 00000000000..c80846440fa --- /dev/null +++ b/tests/language/src/Field2NegativeTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have setter/getter functions and fields +// in the class. + +class C { + get a() { + return 1; + } + set a(int val) { + var x = val; + } + + get b() { + return 2; + } + set b(int val) { + var x = val; + } + + var a; +} + + +class Field2NegativeTest { + static testMain() { + } +} + +main() { + Field2NegativeTest.testMain(); +} diff --git a/tests/language/src/Field3NegativeTest.dart b/tests/language/src/Field3NegativeTest.dart new file mode 100644 index 00000000000..5783db3f184 --- /dev/null +++ b/tests/language/src/Field3NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. + +class C { + final var a; // illegal field declaration. +} + + +class Field3NegativeTest { + static testMain() { + } +} + +main() { + Field3NegativeTest.testMain(); +} diff --git a/tests/language/src/Field4NegativeTest.dart b/tests/language/src/Field4NegativeTest.dart new file mode 100644 index 00000000000..f038552a657 --- /dev/null +++ b/tests/language/src/Field4NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a field overriding a function name. + +class A { + int a() { + return 1; + } + var a; +} + +class Field4NegativeTest { + static testMain() { + } +} + +main() { + Field4NegativeTest.testMain(); +} diff --git a/tests/language/src/Field5NegativeTest.dart b/tests/language/src/Field5NegativeTest.dart new file mode 100644 index 00000000000..f388b81be34 --- /dev/null +++ b/tests/language/src/Field5NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a function overriding a field name. + +class A { + var a; + int a() { + return 1; + } +} + +class Field5NegativeTest { + static testMain() { + } +} + +main() { + Field5NegativeTest.testMain(); +} diff --git a/tests/language/src/Field6NegativeTest.dart b/tests/language/src/Field6NegativeTest.dart new file mode 100644 index 00000000000..0c879798f8b --- /dev/null +++ b/tests/language/src/Field6NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a getter overriding a function name. + +class A { + int a() { + return 1; + } + int get a() { + return 10; + } +} + +class Field6NegativeTest { + static testMain() { + } +} + +main() { + Field6NegativeTest.testMain(); +} diff --git a/tests/language/src/Field6aNegativeTest.dart b/tests/language/src/Field6aNegativeTest.dart new file mode 100644 index 00000000000..580a7313121 --- /dev/null +++ b/tests/language/src/Field6aNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a function overriding a getter. + +class A { + int get a() { + return 10; + } + int a() { + return 1; + } +} + +class Field6aNegativeTest { + static testMain() { + } +} + +main() { + Field6aNegativeTest.testMain(); +} diff --git a/tests/language/src/Field7NegativeTest.dart b/tests/language/src/Field7NegativeTest.dart new file mode 100644 index 00000000000..6a043aa1eaf --- /dev/null +++ b/tests/language/src/Field7NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a setter overriding a function name. + +class A { + int a() { + return 1; + } + void set a(var val) { + int i = val; + } +} + +class Field7NegativeTest { + static testMain() { + } +} + +main() { + Field7NegativeTest.testMain(); +} diff --git a/tests/language/src/Field7aNegativeTest.dart b/tests/language/src/Field7aNegativeTest.dart new file mode 100644 index 00000000000..1e26e6864da --- /dev/null +++ b/tests/language/src/Field7aNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs in class fields declarations. +// Should be an error because we have a function overriding a setter name. + +class A { + void set a(var val) { + int i = val; + } + int a() { + return 1; + } +} + +class Field7aNegativeTest { + static testMain() { + } +} + +main() { + Field7aNegativeTest.testMain(); +} diff --git a/tests/language/src/FieldMethod4NegativeTest.dart b/tests/language/src/FieldMethod4NegativeTest.dart new file mode 100644 index 00000000000..97ae4a72766 --- /dev/null +++ b/tests/language/src/FieldMethod4NegativeTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch error reporting bugs when using a field like a method. + +class A { + var foo; + A() { + foo = () { }; + } + void bar(var a) { + a.foo(); // Tries to invoke the non-existing method 'foo'. + /* + 'a.foo()' is a "Regular instance-method invocation". The guide says: + "If no method is found, the result of the invocation expression is + equivalent to: $0.noSuchMethod(@"id", [$1, ..., $N])." + Invoking noSuchMethod on an instance of A will invoke Object's + noSuchMethod (because A doesn't override that method). Object's + noSuchMethod will throw an error. + */ + } +} + +class FieldMethod4NegativeTest { + static testMain() { + var a = new A(); + a.bar(); + } +} + + +main() { + FieldMethod4NegativeTest.testMain(); +} diff --git a/tests/language/src/FieldMethodTest.dart b/tests/language/src/FieldMethodTest.dart new file mode 100644 index 00000000000..9471aafad1f --- /dev/null +++ b/tests/language/src/FieldMethodTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test. Fields can be invoked directly if they are unqualified. + +class A { + var foo; + A() { + foo = () { }; + } + void bar() { + foo(); // <= foo is a field, but can still be invoked without parenthesis. + } +} + +class FieldMethodTest { + static testMain() { + new A().bar(); + } +} + +main() { + FieldMethodTest.testMain(); +} diff --git a/tests/language/src/FieldNegativeTest.dart b/tests/language/src/FieldNegativeTest.dart new file mode 100644 index 00000000000..8d7b15bb288 --- /dev/null +++ b/tests/language/src/FieldNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to catch that we do not override fields. + +class A { + var a_; + var b_; +} + +class B extends A { + var b_; + var c_; +} + +class FieldNegativeTest { + static testMain() { + } +} + +main() { + FieldNegativeTest.testMain(); +} diff --git a/tests/language/src/FieldOverrideTest.dart b/tests/language/src/FieldOverrideTest.dart new file mode 100644 index 00000000000..393b785c468 --- /dev/null +++ b/tests/language/src/FieldOverrideTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test overriding of fields. + +interface A {} +interface B1 extends A {} +interface B2 extends A {} + +class Super { + Super() : super(); + + B1 field; +} + +class Sub extends Super { + Sub() : super(); + + A field; +} + +class SubSub extends Super { + SubSub() : super(); + + B2 field; /// 01: static type error +} + +main() { + new SubSub(); +} diff --git a/tests/language/src/FieldTest.dart b/tests/language/src/FieldTest.dart new file mode 100644 index 00000000000..f4e093d3356 --- /dev/null +++ b/tests/language/src/FieldTest.dart @@ -0,0 +1,71 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing setting/getting of instance fields. + +class First { + First() {} + var a; + var b; + + addFields() { + return a + b; + } + + setValues() { + a = 24; + b = 10; + return a + b; + } +} + +class Second extends First { + // TODO: consider removing once http://b/4254120 is fixed. + Second() : super() {} + var c; + get a() { return -12; } + set b(a) { a.c = 12; } +} + +class FieldTest { + static one() { + var f = new First(); + f.a = 3; + f.b = f.a; + Expect.equals(3, f.a); + Expect.equals(f.a, f.b); + f.b = (f.a = 10); + Expect.equals(10, f.a); + Expect.equals(10, f.b); + f.b = f.a = 15; + Expect.equals(15, f.a); + Expect.equals(15, f.b); + Expect.equals(30, f.addFields()); + Expect.equals(34, f.setValues()); + Expect.equals(24, f.a); + Expect.equals(10, f.b); + } + + static two() { + // The tests below are a little cumbersome because not + // everything is implemented yet. + var o = new Second(); + // 'a' getter is overriden, always returns -12. + Expect.equals(-12, o.a); + o.a = 2; + Expect.equals(-12, o.a); + // 'b' setter is overriden to write 12 to field 'c'. + o.b = o; + Expect.equals(12, o.c); + } + + static testMain() { + // FieldTest.one(); + FieldTest.two(); + } +} + + +main() { + FieldTest.testMain(); +} diff --git a/tests/language/src/FinalParamNegativeTest.dart b/tests/language/src/FinalParamNegativeTest.dart new file mode 100644 index 00000000000..8857735633e --- /dev/null +++ b/tests/language/src/FinalParamNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Disallow assignment of parameters marked as final. + +class A { + static void test(final x) { + x = 2; // <- reassignment not allowed. + } +} + +main() { + A.test(1); +} diff --git a/tests/language/src/FinalVarNegativeTest.dart b/tests/language/src/FinalVarNegativeTest.dart new file mode 100644 index 00000000000..62d4e536f6b --- /dev/null +++ b/tests/language/src/FinalVarNegativeTest.dart @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Disallow re-assignment of a final local variable. + +main() { + final x = 1; + x = 2; // <- reassignment not allowed. + return x; +} diff --git a/tests/language/src/FirstTest.dart b/tests/language/src/FirstTest.dart new file mode 100644 index 00000000000..6dc54a97922 --- /dev/null +++ b/tests/language/src/FirstTest.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// First dart test program. + +class FirstTest { + static testMain() { return 42; } +} + + +main() { + FirstTest.testMain(); +} diff --git a/tests/language/src/ForInTest.dart b/tests/language/src/ForInTest.dart new file mode 100644 index 00000000000..0f910eb2dee --- /dev/null +++ b/tests/language/src/ForInTest.dart @@ -0,0 +1,52 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing for in on a list literal. + +class ForInTest { + + static testMain() { + testSimple(); + testGenericSyntax1(); + testGenericSyntax2(); + testGenericSyntax3(); + testGenericSyntax4(); + } + + static void testSimple() { + var list = [1, 3, 5]; + var sum = 0; + for (var i in list) { + sum += i; + } + Expect.equals(9, sum); + } + + static void testGenericSyntax1() { + List> aCollection = []; + for (List strArrArr in aCollection) {} + } + + static void testGenericSyntax2() { + List> aCollection = []; + List strArrArr; + for (strArrArr in aCollection) {} + } + + static void testGenericSyntax3() { + List>> aCollection = []; + for (List> strArrArr in aCollection) {} + } + + static void testGenericSyntax4() { + List>> aCollection = []; + List> strArrArr; + for (strArrArr in aCollection) {} + } + +} + +main() { + ForInTest.testMain(); +} diff --git a/tests/language/src/ForTest.dart b/tests/language/src/ForTest.dart new file mode 100644 index 00000000000..3aed595c44a --- /dev/null +++ b/tests/language/src/ForTest.dart @@ -0,0 +1,56 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing for statement. + +class Helper { + static int f1() { + for (;;) return 1; + } + + static int f2(var n) { + int i = 0; + for (; i < n; i++); + return i; + } + + static int f3(int n) { + int i = 0; + for (int j = 0; j < n; j++) i = i + j + 1; + return i; + } + + static int f4(n) { + int i = 0; + for (bool stop = false; (i < n) && !stop; i++) { + if (i >= 5) { + stop = true; + } + } + return i; + } +} + +class ForTest { + static testMain() { + Expect.equals(1, Helper.f1()); + Expect.equals(0, Helper.f2(-1)); + Expect.equals(0, Helper.f2(0)); + Expect.equals(10, Helper.f2(10)); + Expect.equals(0, Helper.f3(-1)); + Expect.equals(0, Helper.f3(0)); + Expect.equals(1, Helper.f3(1)); + Expect.equals(3, Helper.f3(2)); + Expect.equals(6, Helper.f3(3)); + Expect.equals(10, Helper.f3(4)); + Expect.equals(0, Helper.f4(-1)); + Expect.equals(0, Helper.f4(0)); + Expect.equals(1, Helper.f4(1)); + Expect.equals(6, Helper.f4(6)); + Expect.equals(6, Helper.f4(10)); + } +} + +main() { + ForTest.testMain(); +} diff --git a/tests/language/src/FunctionArgumentTest.dart b/tests/language/src/FunctionArgumentTest.dart new file mode 100644 index 00000000000..0edeecfd848 --- /dev/null +++ b/tests/language/src/FunctionArgumentTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for function passing. + +class FunctionArgumentTest { + static testMe(Function f) { + return f(); + } + + static void testMain() { + Expect.equals(42, testMe(() { return 42; })); + Expect.equals(314, testMe(f() { return 314; })); + // Test another unnamed function. + Expect.equals(99, testMe(() { return 99; })); + } +} + +main() { + FunctionArgumentTest.testMain(); +} diff --git a/tests/language/src/FunctionLiterals2Test.dart b/tests/language/src/FunctionLiterals2Test.dart new file mode 100644 index 00000000000..4c4157a50cf --- /dev/null +++ b/tests/language/src/FunctionLiterals2Test.dart @@ -0,0 +1,76 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Dart test for new function type alias. + +class FunctionLiteralsTest { + + static void testMain() { + f(x) { return x * 2;} + f(42); // make sure it is parsed as a function call + Expect.equals(20, f(10)); + + int g(x) { return x * 2;} + g(42); // make sure it is parsed as a function call + Expect.equals(20, g(10)); + + h(x) { return x * 2;} + h(42); // make sure it is parsed as a function call + Expect.equals(20, h(10)); + + var a = int _(x) {return x + 2;}; + Expect.equals(7, a(5)); + + Expect.equals(10, apply((k) { return k << 1;}, 5)); + Expect.equals(20, apply((k) => k << 1, 10)); + + a = new A(3); + Expect.equals(-1, a.f); + Expect.equals(-3, a.f2); + + a = new A.n(5); + Expect.equals(-2, a.f); + Expect.equals(2, a.f2); + + Expect.equals(true, isOdd(5)); + Expect.equals(false, isOdd(8)); + + var b = new B(10); + Expect.equals(10, b.n); + Expect.equals(100, (b.f)(10)); + + b = new B.n(10); + Expect.equals(10, b.n); + Expect.equals(101, (b.f)(10)); + + int x = 0; + int y = 1; + // make sure this isn't parsed as a generic type + Expect.isTrue(x b % 2 == 1; + +class A { + int f; + int f2; + A(p) : f = apply((j) => 2 - j, p) { /* constr. body */ f2 = -p; } + A.n(p) : f = 1 + apply((j) => 2 - j, p) { /* constr. body */ f2 = -f; } +} + +class B { + var f; + int n; + B(z) : f = ((x) => x * x) { n = z; } + B.n(z) : f = ((x) { return x * x + 1; }) { n = z; } +} + +main() { + FunctionLiteralsTest.testMain(); +} diff --git a/tests/language/src/FunctionLiteralsTest.dart b/tests/language/src/FunctionLiteralsTest.dart new file mode 100644 index 00000000000..0f379e2b557 --- /dev/null +++ b/tests/language/src/FunctionLiteralsTest.dart @@ -0,0 +1,160 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/** + * Test various forms of function literals. + */ +typedef int IntFunc(int); + +class FunctionLiteralsTest { + static void checkIntFunction(expected, int f(x), arg) { + Expect.equals(expected, f(arg)); + } + + static void checkIntFuncFunction(expected, IntFunc f(x), arg) { + Expect.equals(expected, f(arg)(arg)); + } + + int func1(int x) => x; + + int func2(x) => x; + + int func3(int x) { + return x; + } + + int func4(x) { + return x; + } + + FunctionLiteralsTest() {} + + static void testMain() { + var test = new FunctionLiteralsTest(); + test.testArrow(); + test.testArrowArrow(); + test.testArrowBlock(); + test.testBlock(); + test.testBlockArrow(); + test.testBlockBlock(); + test.testFunctionRef(); + } + + void testArrow() { + checkIntFunction(42, (x) => x, 42); + checkIntFunction(42, _(x) => x, 42); + checkIntFunction(42, int f(x) => x, 42); + checkIntFunction(42, (int x) => x, 42); + checkIntFunction(42, _(int x) => x, 42); + checkIntFunction(42, int f(int x) => x, 42); + } + + void testArrowArrow() { + checkIntFuncFunction(84, (x) => (y) => x+y, 42); + checkIntFuncFunction(84, _(x) => (y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(x) => (y) => x+y, 42); + checkIntFuncFunction(84, (int x) => (y) => x+y, 42); + checkIntFuncFunction(84, _(int x) => (y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(int x) => (y) => x+y, 42); + checkIntFuncFunction(84, (x) => f(y) => x+y, 42); + checkIntFuncFunction(84, _(x) => f(y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(x) => f(y) => x+y, 42); + checkIntFuncFunction(84, (int x) => f(y) => x+y, 42); + checkIntFuncFunction(84, _(int x) => f(y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(int x) => f(y) => x+y, 42); + checkIntFuncFunction(84, (x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, _(x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, (int x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, _(int x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(int x) => int f(y) => x+y, 42); + checkIntFuncFunction(84, (int x) => int f(int y) => x+y, 42); + checkIntFuncFunction(84, _(int x) => int f(int y) => x+y, 42); + checkIntFuncFunction(84, IntFunc f(int x) => int f(int y) => x+y, 42); + } + + void testArrowBlock() { + checkIntFuncFunction(84, (x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, _(x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, (int x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, _(int x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) => (y) { return x+y; }, 42); + checkIntFuncFunction(84, (x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, _(x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, (int x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, _(int x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) => f(y) { return x+y; }, 42); + checkIntFuncFunction(84, (x) => int f(y) { return x+y; }, 42); + checkIntFuncFunction(84, _(x) => int f(y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) => int f(y) { return x+y; }, 42); + checkIntFuncFunction(84, (int x) => int f(y) { return x+y; }, 42); + checkIntFuncFunction(84, _(int x) => int f(y) { return x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) => int f(y) { return x+y; }, 42); + } + + void testBlock() { + checkIntFunction(42, (x) { return x; }, 42); + checkIntFunction(42, _(x) { return x; }, 42); + checkIntFunction(42, int f(x) { return x; }, 42); + checkIntFunction(42, (int x) { return x; }, 42); + checkIntFunction(42, _(int x) { return x; }, 42); + checkIntFunction(42, int f(int x) { return x; }, 42); + } + + void testBlockArrow() { + checkIntFuncFunction(84, (x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, _(x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, (int x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, _(int x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return (y) => x+y; }, 42); + checkIntFuncFunction(84, (x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, _(x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, (int x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, _(int x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return f(y) => x+y; }, 42); + checkIntFuncFunction(84, (x) { return int f(y) => x+y; }, 42); + checkIntFuncFunction(84, _(x) { return int f(y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return int f(y) => x+y; }, 42); + checkIntFuncFunction(84, (int x) { return int f(y) => x+y; }, 42); + checkIntFuncFunction(84, _(int x) { return int f(y) => x+y; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return int f(y) => x+y; }, 42); + } + + void testBlockBlock() { + checkIntFuncFunction(84, (x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, (int x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(int x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return (y) { return x+y; }; }, 42); + checkIntFuncFunction(84, (x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, (int x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(int x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, (x) { return int f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(x) { return int f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(x) { return int f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, (int x) { return int f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, _(int x) { return int f(y) { return x+y; }; }, 42); + checkIntFuncFunction(84, IntFunc f(int x) { return int f(y) { return x+y; }; }, 42); + } + + void testFunctionRef() { + checkIntFunction(42, func1, 42); + checkIntFunction(42, func2, 42); + checkIntFunction(42, func3, 42); + checkIntFunction(42, func4, 42); + } +} + + +main() { + FunctionLiteralsTest.testMain(); +} diff --git a/tests/language/src/FunctionSyntaxTest.dart b/tests/language/src/FunctionSyntaxTest.dart new file mode 100644 index 00000000000..53300963ede --- /dev/null +++ b/tests/language/src/FunctionSyntaxTest.dart @@ -0,0 +1,331 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests function statement and expression syntax. + +class FunctionSyntaxTest { + + static void testMain() { + testNestedFunctions(); + testFunctionExpressions(); + testPrecedence(); + testInitializers(); + testFunctionParameter(); + testFunctionIdentifierExpression(); + testFunctionIdentifierStatement(); + } + + static void testNestedFunctions() { + // No types - braces. + nb0() { return 42; } + nb1(a) { return a; } + nb2(a, b) { return a + b; } + Expect.equals(42, nb0()); + Expect.equals(87, nb1(87)); + Expect.equals(1 + 2, nb2(1, 2)); + + // No types - arrows. + na0() => 42; + na1(a) => a; + na2(a, b) => a + b; + Expect.equals(42, na0()); + Expect.equals(87, na1(87)); + Expect.equals(1 + 2, na2(1, 2)); + + // Return type - braces. + int rb0() { return 42; } + int rb1(a) { return a; } + int rb2(a, b) { return a + b; } + Expect.equals(42, rb0()); + Expect.equals(87, rb1(87)); + Expect.equals(1 + 2, rb2(1, 2)); + + // Return type - arrows. + int ra0() => 42; + int ra1(a) => a; + int ra2(a, b) => a + b; + Expect.equals(42, ra0()); + Expect.equals(87, ra1(87)); + Expect.equals(1 + 2, ra2(1, 2)); + + // Fully typed - braces. + int fb1(int a) { return a; } + int fb2(int a, int b) { return a + b; } + Expect.equals(42, rb0()); + Expect.equals(87, rb1(87)); + Expect.equals(1 + 2, rb2(1, 2)); + + // Fully typed - arrows. + int fa1(int a) => a; + int fa2(int a, int b) => a + b; + Expect.equals(42, ra0()); + Expect.equals(87, ra1(87)); + Expect.equals(1 + 2, ra2(1, 2)); + + // Generic types - braces. + List gb0() { return [42]; } + List gb1(List a) { return a; } + Expect.equals(42, gb0()[0]); + Expect.equals(87, gb1([87])[0]); + + // Generic types - arrows. + List ga0() => [42]; + List ga1(List a) => a; + Expect.equals(42, ga0()[0]); + Expect.equals(87, ga1([87])[0]); + } + + static void testFunctionExpressions() { + eval0(fn) => fn(); + eval1(fn, a) => fn(a); + eval2(fn, a, b) => fn(a, b); + + // No types - braces. + Expect.equals(42, eval0(() { return 42; })); + Expect.equals(87, eval1((a) { return a; }, 87)); + Expect.equals(1 + 2, eval2((a, b) { return a + b; }, 1, 2)); + Expect.equals(42, eval0(nb0() { return 42; })); + Expect.equals(87, eval1(nb1(a) { return a; }, 87)); + Expect.equals(1 + 2, eval2(nb2(a, b) { return a + b; }, 1, 2)); + + // No types - arrows. + Expect.equals(42, eval0(() => 42)); + Expect.equals(87, eval1((a) => a, 87)); + Expect.equals(1 + 2, eval2((a, b) => a + b, 1, 2)); + Expect.equals(42, eval0(na0() => 42)); + Expect.equals(87, eval1(na1(a) => a, 87)); + Expect.equals(1 + 2, eval2(na2(a, b) => a + b, 1, 2)); + + // Return type - braces. + Expect.equals(42, eval0(int rb0() { return 42; })); + Expect.equals(87, eval1(int rb1(a) { return a; }, 87)); + Expect.equals(1 + 2, eval2(int rb2(a, b) { return a + b; }, 1, 2)); + + // Return type - arrows. + Expect.equals(42, eval0(int ra0() => 42)); + Expect.equals(87, eval1(int ra1(a) => a, 87)); + Expect.equals(1 + 2, eval2(int ra2(a, b) => a + b, 1, 2)); + + // Argument types - braces. + Expect.equals(42, eval0(() { return 42; })); + Expect.equals(87, eval1((int a) { return a; }, 87)); + Expect.equals(1 + 2, eval2((int a, int b) { return a + b; }, 1, 2)); + Expect.equals(42, eval0( ab0() { return 42; })); + Expect.equals(87, eval1(ab1(int a) { return a; }, 87)); + Expect.equals(1 + 2, eval2(ab2(int a, int b) { return a + b; }, 1, 2)); + + // Argument types - arrows. + Expect.equals(42, eval0(() => 42)); + Expect.equals(87, eval1((int a) => a, 87)); + Expect.equals(1 + 2, eval2((int a, int b) => a + b, 1, 2)); + Expect.equals(42, eval0(aa0() => 42)); + Expect.equals(87, eval1(aa1(int a) => a, 87)); + Expect.equals(1 + 2, eval2(aa2(int a, int b) => a + b, 1, 2)); + + // Fully typed - braces. + Expect.equals(87, eval1(int fb1(int a) { return a; }, 87)); + Expect.equals(1 + 2, eval2(int fb2(int a, int b) { return a + b; }, 1, 2)); + + // Fully typed - arrows. + Expect.equals(87, eval1(int fa1(int a) => a, 87)); + Expect.equals(1 + 2, eval2(int fa2(int a, int b) => a + b, 1, 2)); + + // Generic types - braces. + Expect.equals(42, eval0(List gb0() { return [42]; })[0]); + Expect.equals(87, eval1(List gb1(List a) { return a; }, [87])[0]); + + // Generic types - arrows. + Expect.equals(42, eval0(List ga0() => [42])[0]); + Expect.equals(87, eval1(List ga1(List a) => a, [87])[0]); + } + + static void testPrecedence() { + expectEvaluatesTo(value, fn) { Expect.equals(value, fn()); } + + // Assignment. + var x; + expectEvaluatesTo(42, ()=> x = 42); + Expect.equals(42, x); + x = 1; + expectEvaluatesTo(100, ()=> x += 99); + Expect.equals(100, x); + x = 1; + expectEvaluatesTo(87, ()=> x *= 87); + Expect.equals(87, x); + + // Conditional. + expectEvaluatesTo(42, ()=> true ? 42 : 87); + expectEvaluatesTo(87, ()=> false ? 42 : 87); + + // Logical or. + expectEvaluatesTo(true, ()=> true || true); + expectEvaluatesTo(true, ()=> true || false); + expectEvaluatesTo(true, ()=> false || true); + expectEvaluatesTo(false, ()=> false || false); + + // Logical and. + expectEvaluatesTo(true, ()=> true && true); + expectEvaluatesTo(false, ()=> true && false); + expectEvaluatesTo(false, ()=> false && true); + expectEvaluatesTo(false, ()=> false && false); + + // Bitwise operations. + expectEvaluatesTo(3, ()=> 1 | 2); + expectEvaluatesTo(2, ()=> 3 ^ 1); + expectEvaluatesTo(1, ()=> 3 & 1); + + // Equality. + expectEvaluatesTo(true, ()=> 1 == 1); + expectEvaluatesTo(false, ()=> 1 != 1); + expectEvaluatesTo(true, ()=> 1 === 1); + expectEvaluatesTo(false, ()=> 1 !== 1); + + // Relational. + expectEvaluatesTo(true, ()=> 1 <= 1); + expectEvaluatesTo(false, ()=> 1 < 1); + expectEvaluatesTo(false, ()=> 1 > 1); + expectEvaluatesTo(true, ()=> 1 >= 1); + + // Is. + expectEvaluatesTo(true, ()=> 1 is int); + expectEvaluatesTo(true, ()=> 1.0 is double); + + // Shift. + expectEvaluatesTo(2, ()=> 1 << 1); + expectEvaluatesTo(1, ()=> 2 >> 1); + + // Additive. + expectEvaluatesTo(2, ()=> 1 + 1); + expectEvaluatesTo(1, ()=> 2 - 1); + + // Multiplicative. + expectEvaluatesTo(2, ()=> 1 * 2); + expectEvaluatesTo(2.0, ()=> 4 / 2); + expectEvaluatesTo(2, ()=> 4 ~/ 2); + expectEvaluatesTo(0, ()=> 4 % 2); + + // Negate. + expectEvaluatesTo(-3, ()=> ~2); + expectEvaluatesTo(false, ()=> !true); + + // Postfix / prefix. + var y = 0; + expectEvaluatesTo(0, ()=> y++); + expectEvaluatesTo(2, ()=> ++y); + expectEvaluatesTo(1, ()=> --y); + expectEvaluatesTo(1, ()=> y--); + Expect.equals(0, y); + + // Selector. + fn() => 42; + var list = [87]; + expectEvaluatesTo(42, ()=> fn()); + expectEvaluatesTo(1, ()=> list.length); + expectEvaluatesTo(87, ()=> list[0]); + expectEvaluatesTo(87, ()=> list.removeLast()); + } + + static void testInitializers() { + Expect.equals(42, (new C.cb0().fn)()); + Expect.equals(43, (new C.ca0().fn)()); + Expect.equals(44, (new C.cb1().fn)()); + Expect.equals(45, (new C.ca1().fn)()); + Expect.equals(46, (new C.cb2().fn)()); + Expect.equals(47, (new C.ca2().fn)()); + Expect.equals(48, (new C.cb3().fn)()); + Expect.equals(49, (new C.ca3().fn)()); + + Expect.equals(52, (new C.nb0().fn)()); + Expect.equals(53, (new C.na0().fn)()); + Expect.equals(54, (new C.nb1().fn)()); + Expect.equals(55, (new C.na1().fn)()); + Expect.equals(56, (new C.nb2().fn)()); + Expect.equals(57, (new C.na2().fn)()); + Expect.equals(58, (new C.nb3().fn)()); + Expect.equals(59, (new C.na3().fn)()); + + Expect.equals(62, (new C.rb0().fn)()); + Expect.equals(63, (new C.ra0().fn)()); + Expect.equals(64, (new C.rb1().fn)()); + Expect.equals(65, (new C.ra1().fn)()); + Expect.equals(66, (new C.rb2().fn)()); + Expect.equals(67, (new C.ra2().fn)()); + Expect.equals(68, (new C.rb3().fn)()); + Expect.equals(69, (new C.ra3().fn)()); + } + + static void testFunctionParameter() { + f0(fn()) => fn(); + Expect.equals(42, f0(()=> 42)); + + f1(int fn()) => fn(); + Expect.equals(87, f1(()=> 87)); + + f2(fn(a)) => fn(42); + Expect.equals(43, f2((a)=> a + 1)); + + f3(fn(int a)) => fn(42); + Expect.equals(44, f3((int a)=> a + 2)); + } + + static void testFunctionIdentifierExpression() { + Expect.equals(87, (function() => 87)()); + } + + static void testFunctionIdentifierStatement() { + function() => 42; + Expect.equals(42, function()); + Expect.equals(true, function is Function); + } + +} + + +class C { + + C.cb0() : fn = (() { return 42; }) { } + C.ca0() : fn = (() => 43) { } + + C.cb1() : fn = wrap(() { return 44; }) { } + C.ca1() : fn = wrap(()=> 45) { } + + C.cb2() : fn = [() { return 46; }][0] { } + C.ca2() : fn = [() => 47][0] { } + + C.cb3() : fn = {'x': () { return 48; }}['x'] { } + C.ca3() : fn = {'x': () => 49}['x'] { } + + C.nb0() : fn = (f() { return 52; }) { } + C.na0() : fn = (f() => 53) { } + + C.nb1() : fn = wrap(f() { return 54; }) { } + C.na1() : fn = wrap(f()=> 55) { } + + C.nb2() : fn = [f() { return 56; }][0] { } + C.na2() : fn = [f() => 57][0] { } + + C.nb3() : fn = {'x': f() { return 58; }}['x'] { } + C.na3() : fn = {'x': f() => 59}['x'] { } + + C.rb0() : fn = (int _() { return 62; }) { } + C.ra0() : fn = (int _() => 63) { } + + C.rb1() : fn = wrap(int _() { return 64; }) { } + C.ra1() : fn = wrap(int _()=> 65) { } + + C.rb2() : fn = [int _() { return 66; }][0] { } + C.ra2() : fn = [int _() => 67][0] { } + + C.rb3() : fn = {'x': int _() { return 68; }}['x'] { } + C.ra3() : fn = {'x': int _() => 69}['x'] { } + + static wrap(fn) { return fn; } + + final fn; + +} + +main() { + FunctionSyntaxTest.testMain(); +} diff --git a/tests/language/src/FunctionTest.dart b/tests/language/src/FunctionTest.dart new file mode 100644 index 00000000000..b832e1e1263 --- /dev/null +++ b/tests/language/src/FunctionTest.dart @@ -0,0 +1,358 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests function statements and expressions. + +class Bug4089219 { + int x; + var f; + + Bug4089219(int i) : this.x = i { + f = () => x; + } +} + +class Bug4342163 { + final m; + Bug4342163(int a) : this.m = (() => a) {} +} + +class StaticFunctionDef { + static final int one = 1; + static var fn1; + static var fn2; + static var fn3; + + static init() { + fn1 = () { return one; }; + fn2 = () { return (() { return one; })(); }; + fn3 = () { + final local = 1; + return (() { return local; })(); + }; + } +} + +class A { + var ma; + A(a) {ma = a;} +} + +class B1 extends A { + final mfn; + B1(int a) : super(a), this.mfn = (() {return a;}) { + } +} + +class B2 extends A { + final mfn; + B2(int a) : super(2), this.mfn = (() {return a;}) { + } +} + +class B3 extends A { + final mfn; + B3(int a) : super(() {return a;}), this.mfn = (() {return a;}) { + } +} + +typedef void Fisk(); + +class FunctionTest { + + FunctionTest() {} + + static void testMain() { + var test = new FunctionTest(); + test.testRecursiveClosureRef(); + test.testForEach(); + test.testVarOrder1(); + test.testVarOrder2(); + test.testLexicalClosureRef1(); + test.testLexicalClosureRef2(); + test.testLexicalClosureRef3(); + test.testLexicalClosureRef4(); + test.testLexicalClosureRef5(); + test.testFunctionScopes(); + test.testDefaultParametersOrder(); + test.testParametersOrder(); + test.testFunctionDefaults1(); + test.testFunctionDefaults2(); + test.testEscapingFunctions(); + test.testThisBinding(); + test.testFnBindingInStatics(); + test.testFnBindingInInitLists(); + test.testSubclassConstructorScopeAlias(); + } + + void testSubclassConstructorScopeAlias() { + var b1 = new B1(10); + Expect.equals(10, (b1.mfn)()); + Expect.equals(10, b1.ma); + + var b2 = new B2(11); + Expect.equals(11, (b2.mfn)()); + Expect.equals(2, b2.ma); + + var b3 = new B3(12); + Expect.equals(12, (b3.mfn)()); + Expect.equals(12, (b3.ma)()); + } + + void testFnBindingInInitLists() { + Expect.equals(1, (new Bug4342163(1).m)()); + } + + void testFnBindingInStatics() { + StaticFunctionDef.init(); + Expect.equals(1, ((StaticFunctionDef.fn1)())); + Expect.equals(1, ((StaticFunctionDef.fn2)())); + Expect.equals(1, ((StaticFunctionDef.fn3)())); + } + + Fisk testReturnVoidFunction() { + void f() {} + Fisk x = f; + return f; + } + + void testVarOrder1() { + var a = 0, b = a++, c = a++; + + Expect.equals(a, 2); + Expect.equals(b, 0); + Expect.equals(c, 1); + } + + void testVarOrder2() { + var a = 0; + f() {return a++;}; + var b = f(), c = f(); + + Expect.equals(a, 2); + Expect.equals(b, 0); + Expect.equals(c, 1); + } + + void testLexicalClosureRef1() { + var a = 1; + var f, g; + { + var b = 2; + f = () {return b - a;}; + } + + { + var b = 3; + g = () {return b - a;}; + } + Expect.equals(1, f()); + Expect.equals(2, g()); + } + + void testLexicalClosureRef2() { + var a = 1; + var f, g; + { + var b = 2; + f = () {return ((){return b - a;})();}; + } + + { + var b = 3; + g = () {return ((){return b - a;})();}; + } + Expect.equals(1, f()); + Expect.equals(2, g()); + } + + void testLexicalClosureRef3() { + var a = new List(); + for (int i = 0; i < 10; i++) { + var x = i; + a.add(() {return x;}); + } + + var sum = 0; + for (int i = 0; i < a.length; i++) { + sum += (a[i])(); + } + + Expect.equals(45, sum); + } + + void testLexicalClosureRef5() { + { + var a; + Expect.equals(null, a); + a = 1; + Expect.equals(1, a); + } + + { + var a; + Expect.equals(null, a); + a = 1; + Expect.equals(1, a); + } + } + + // Make sure labels are preserved, and a second 'i' does influence the first. + void testLexicalClosureRef4() { + var a = new List(); + x:for (int i = 0; i < 10; i++) { + a.add(() {return i;}); + continue x; + } + + var sum = 0; + for (int i = 0; i < a.length; i++) { + sum += (a[i])(); + } + + Expect.equals(100, sum); + } + + int tempField; + + // Validate that a closure that calls the private name of a function (for + // for recursion) calls the version of function with the bound names. + void testRecursiveClosureRef() { + tempField = 2; + var x = 3; + var g = f(a) { + tempField++; + x++; + if (a > 0) { + f(--a); + } + }; + g(2); + + + Expect.equals(5, tempField); + Expect.equals(6, x); + } + + void testForEach() { + List vals = [1,2,3]; + int total = 0; + vals.forEach((int v) { + total += v; + }); + Expect.equals(6, total); + } + + void testFunctionScopes() { + // Function expression. 'recurse' is only defined within the function body. + // FAILS: + // var factorial0 = function recurse(int x) { + // return (x == 1) ? 1 : (x * recurse(x - 1)); + // }; + // TEMP: + var factorial0; + factorial0 = recurse(int x) { + return (x == 1) ? 1 : (x * factorial0(x - 1)); + }; + // END TEMP + + + // Function statement. 'factorial1' is defined in the outer scope. + int factorial1(int x) { + return (x == 1) ? 1 : (x * factorial1(x - 1)); + } + + // This would fail to compile if 'recurse' were defined in the outer scope. + // Which it shouldn't be. + int recurse = 42; + + Expect.equals(6, factorial0(3)); + Expect.equals(24, factorial0(4)); + } + + void testDefaultParametersOrder() { + f([a = 1, b = 3]) { + return a - b; + } + Expect.equals(-2, f()); + } + + void testParametersOrder() { + f(a, b) { + return a - b; + } + Expect.equals(-2, f(1,3)); + } + + void testFunctionDefaults1() { + // TODO(jimhug): This return null shouldn't be necessary. + f() { return null; }; + (([a = 10]) { Expect.equals(10, a); })(); + ((a, [b = 10]) { Expect.equals(10, b); })(1); + (([a = 10]) { Expect.equals(null, a); })( f() ); + // FAILS: (([a = 10]) { Expect.equals(null ,a); })( f() ); + } + + void testFunctionDefaults2() { + Expect.equals(10, helperFunctionDefaults2()); + Expect.equals(1, helperFunctionDefaults2(1)); + } + + num helperFunctionDefaults2([a = 10]) { + return ((){return a;})(); + } + + void testEscapingFunctions() { + f() { return 42; } + (() { Expect.equals(42, f()); })(); + var o = new Bug4089219(42); + Expect.equals(42, (o.f)()); + } + + void testThisBinding() { + Expect.equals(this, () { return this; }()); + } +} + +typedef void Foo(A a, B b); + +class Bar { + Foo field; + Bar(A a, B b) : this.field = ((A a1, B b2){}) { + field(a, b); + } +} + +typedef UntypedFunction(arg); +typedef UntypedFunction2(arg); + +class UseFunctionTypes { + void test() { + Function f = null; + UntypedFunction uf = null; + UntypedFunction2 uf2 = null; + Foo foo = null; + Foo fooIntString = null; + + f = uf; + f = uf2; + f = foo; + f = fooIntString; + + uf = f; + uf2 = f; + foo = f; + fooIntString = f; + + foo = fooIntString; + fooIntString = foo; + + uf = uf2; + uf2 = uf; + } +} + +main() { + FunctionTest.testMain(); +} diff --git a/tests/language/src/FunctionTypeAliasNegativeTest.dart b/tests/language/src/FunctionTypeAliasNegativeTest.dart new file mode 100644 index 00000000000..c9d15fa62d4 --- /dev/null +++ b/tests/language/src/FunctionTypeAliasNegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for illegally self referencing function type alias. + +typedef Handle Handle(String command); + +class FunctionTypeAliasNegativeTest { + static void testMain() { + } +} + + +main() { + FunctionTypeAliasNegativeTest.testMain(); +} diff --git a/tests/language/src/FunctionTypeAliasTest.dart b/tests/language/src/FunctionTypeAliasTest.dart new file mode 100644 index 00000000000..f24fdda7376 --- /dev/null +++ b/tests/language/src/FunctionTypeAliasTest.dart @@ -0,0 +1,101 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_type_checks +// +// Dart test for function type alias. + +typedef Fun(a, b); + +typedef int IntFun(a, b); + +typedef bool BoolFun(a, b); + +typedef int CompareObj(Object a, Object b); + +typedef int CompareInt(int a, int b); + +typedef int CompareString(String a, String b, [bool swap]); + +typedef void Test(); + +typedef ParametrizedFun1(T t, U u); + +typedef List ParametrizedFun2>( + Map t, U u); + +class FunctionTypeAliasTest { + FunctionTypeAliasTest() {} + static int test(CompareObj compare, Object a, Object b) { + return compare(a, b); + } + foo(Test test) {} + static bar() { + FunctionTypeAliasTest a = new FunctionTypeAliasTest(); + a.foo(() { }); + return 0; + } + + static void testMain() { + int compareStrLen(String a, String b) { return a.length - b.length; } + Expect.isTrue(compareStrLen is Fun); + Expect.isTrue(compareStrLen is IntFun); + Expect.isTrue(compareStrLen is !BoolFun); + Expect.isTrue(compareStrLen is CompareObj); + Expect.isTrue(compareStrLen is !CompareInt); + Expect.isTrue(compareStrLen is !CompareString); + Expect.equals(3, test(compareStrLen, "abcdef", "xyz")); + + int compareStrLenSwap(String a, String b, [bool swap = false]) { + return swap ? (a.length - b.length) : (b.length - a.length); + } + Expect.isTrue(compareStrLenSwap is Fun); + Expect.isTrue(compareStrLenSwap is IntFun); + Expect.isTrue(compareStrLenSwap is !BoolFun); + Expect.isTrue(compareStrLenSwap is CompareObj); + Expect.isTrue(compareStrLenSwap is !CompareInt); + Expect.isTrue(compareStrLenSwap is CompareString); + + int compareStrLenReverse(String a, String b, [bool reverse = false]) { + return reverse ? (a.length - b.length) : (b.length - a.length); + } + Expect.isTrue(compareStrLenReverse is Fun); + Expect.isTrue(compareStrLenReverse is IntFun); + Expect.isTrue(compareStrLenReverse is !BoolFun); + Expect.isTrue(compareStrLenReverse is CompareObj); + Expect.isTrue(compareStrLenReverse is !CompareInt); + Expect.isTrue(compareStrLenReverse is !CompareString); + + int compareObj(Object a, Object b) { return a === b ? 0 : -1; } + Expect.isTrue(compareObj is Fun); + Expect.isTrue(compareObj is IntFun); + Expect.isTrue(compareObj is !BoolFun); + Expect.isTrue(compareObj is CompareObj); + Expect.isTrue(compareObj is CompareInt); + Expect.isTrue(compareObj is !CompareString); + Expect.equals(-1, test(compareObj, "abcdef", "xyz")); + + CompareInt minus = int _(int a, int b) { return a - b; }; + Expect.isTrue(minus is Fun); + Expect.isTrue(compareStrLen is IntFun); + Expect.isTrue(compareStrLen is !BoolFun); + Expect.isTrue(minus is CompareObj); + Expect.isTrue(minus is CompareInt); + Expect.isTrue(minus is !CompareString); + Expect.equals(99, test(minus, 100, 1)); + + int plus (int a, [int b = 1]) { return a + b; }; + Expect.isTrue(plus is !Fun); + Expect.isTrue(plus is !IntFun); + Expect.isTrue(plus is !BoolFun); + Expect.isTrue(plus is !CompareObj); + Expect.isTrue(plus is !CompareInt); + Expect.isTrue(plus is !CompareString); + + Expect.equals(0, bar()); + } +} + +main() { + FunctionTypeAliasTest.testMain(); +} diff --git a/tests/language/src/FunctionTypeParameter2NegativeTest.dart b/tests/language/src/FunctionTypeParameter2NegativeTest.dart new file mode 100644 index 00000000000..c4abfdf7e73 --- /dev/null +++ b/tests/language/src/FunctionTypeParameter2NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that we detect that a function literal is not +// a compile time constant. + +class FunctionTypeParameterNegativeTest { + + static var formatter; + + static SetFormatter(String fmt(int i) = (i) => "$i") { + formatter = fmt; + } + + static void testMain() { + SetFormatter(); + } +} + +main() { + FunctionTypeParameterNegativeTest.testMain(); +} diff --git a/tests/language/src/FunctionTypeParameter2Test.dart b/tests/language/src/FunctionTypeParameter2Test.dart new file mode 100644 index 00000000000..77d3d216112 --- /dev/null +++ b/tests/language/src/FunctionTypeParameter2Test.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test to check that we can parse closure type formal parameters with +// default value. + +class FunctionTypeParameterTest { + + static var formatter; + + static SetFormatter([String fmt(int i) = null]) { + formatter = fmt; + } + + static void testMain() { + Expect.equals(null, formatter); + SetFormatter((i) => "$i"); + Expect.equals(false, null == formatter); + Expect.equals("1234", formatter(1230 + 4)); + SetFormatter(); + Expect.equals(null, formatter); + } +} + +main() { + FunctionTypeParameterTest.testMain(); +} diff --git a/tests/language/src/FunctionTypeParameterNegativeTest.dart b/tests/language/src/FunctionTypeParameterNegativeTest.dart new file mode 100644 index 00000000000..506cf2a3ad9 --- /dev/null +++ b/tests/language/src/FunctionTypeParameterNegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that we detect that a function literal is not a compile time constant. + +class A { + + static Function func; + + static SetFunc([String fmt(int i) = (i) => "$i"]) { + func = fmt; + } + +} + +main() { + A.SetFunc(); +} diff --git a/tests/language/src/FunctionTypeParameterTest.dart b/tests/language/src/FunctionTypeParameterTest.dart new file mode 100644 index 00000000000..c839a031f5c --- /dev/null +++ b/tests/language/src/FunctionTypeParameterTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test to check that we can parse closure type formal parameters with +// default value. + +class A { + + static Function func; + + static SetFunc([String fmt(int i) = null]) { + func = fmt; + } + +} + +main() { + Expect.equals(null, A.func); + A.SetFunc((i) => "$i"); + Expect.equals(false, null == A.func); + Expect.equals("1234", A.func(1230 + 4)); + A.SetFunc(); + Expect.equals(null, A.func); +} diff --git a/tests/language/src/GenericInheritanceTest.dart b/tests/language/src/GenericInheritanceTest.dart new file mode 100644 index 00000000000..487c9ca8802 --- /dev/null +++ b/tests/language/src/GenericInheritanceTest.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test verifying that the type argument vector of subclasses are properly +// initialized by the class finalizer. + +class A { A(); } +class B extends A { B(); } +class C extends B { C(); } + +main() { + var a = new A(); + var b = new B(); + var c = new C(); + Expect.isTrue(a is Object); + Expect.isTrue(a is A); + Expect.isTrue(a is A); + Expect.isTrue(a is !A); + Expect.isTrue(b is Object); + Expect.isTrue(b is A); + Expect.isTrue(b is !A); + Expect.isTrue(b is Object); + Expect.isTrue(c is Object); + Expect.isTrue(c is A); + Expect.isTrue(c is !A); + Expect.isTrue(c is B); +} diff --git a/tests/language/src/GenericInstanceof.dart b/tests/language/src/GenericInstanceof.dart new file mode 100644 index 00000000000..3f64976d6b5 --- /dev/null +++ b/tests/language/src/GenericInstanceof.dart @@ -0,0 +1,127 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that instanceof works correctly with type variables. + +class Foo { + Foo() {} + + bool isT(x) { // Untyped parameter to ensure that the static type + // does not affect the result. + return x is T; + } + + bool isListT(x) { + return x is List; + } +} + +class GenericInstanceof { + static void testMain() { + // Using Object instead of String to ensure that the static type + // does not affect the result. + Foo fooObject = new Foo(); + Expect.equals(true, fooObject.isT("string")); + Expect.equals(false, fooObject.isT(1)); + + Foo fooString = new Foo(); + Expect.equals(true, fooString.isT("string")); + Expect.equals(false, fooString.isT(1)); + + // Not providing a type argument to ensure that the static type + // does not affect the result. + { + Foo foo = new Foo(); + Expect.equals(true, foo.isT("string")); + Expect.equals(false, foo.isT(1)); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + } + { + Foo foo = new Foo>(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + } + { + Foo foo = new Foo>(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + } + { + Foo foo = new Foo>(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + } + { + Foo foo = new Foo>(); + Expect.equals(true, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(false, foo.isT(new List(5))); + Expect.equals(true, foo.isT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + } + { + Foo foo = new Foo(); + Expect.equals(true, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(false, foo.isListT(new List(5))); + Expect.equals(true, foo.isListT(new List(5))); + } + } +} diff --git a/tests/language/src/GenericInstanceofTest.dart b/tests/language/src/GenericInstanceofTest.dart new file mode 100644 index 00000000000..1729bef3d03 --- /dev/null +++ b/tests/language/src/GenericInstanceofTest.dart @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that instanceof works correctly with type variables. + +#source("GenericInstanceof.dart"); + +main() { + GenericInstanceof.testMain(); +} diff --git a/tests/language/src/GenericParameterizedExtendsTest.dart b/tests/language/src/GenericParameterizedExtendsTest.dart new file mode 100644 index 00000000000..bef0d716da7 --- /dev/null +++ b/tests/language/src/GenericParameterizedExtendsTest.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test verifying that generic extends are processed correctly. + +class A {} +class B> {} +class C, T2> {} + +main() { + var a = new A(); + var b = new B>(); + var c = new C, String>(); + Expect.isTrue(a is Object); + Expect.isTrue(a is A); + Expect.isTrue(a is A); + Expect.isTrue(a is !A); + Expect.isTrue(b is Object); + Expect.isTrue(b is B>); + Expect.isTrue(b is B>); + Expect.isTrue(b is !B>); + Expect.isTrue(c is Object); + Expect.isTrue(c is C, Object>); + Expect.isTrue(c is C, String>); + Expect.isTrue(c is !C, int>); +} diff --git a/tests/language/src/GenericSyntaxTest.dart b/tests/language/src/GenericSyntaxTest.dart new file mode 100644 index 00000000000..b63e3e6df4e --- /dev/null +++ b/tests/language/src/GenericSyntaxTest.dart @@ -0,0 +1,46 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test verifying that the parser does not confuse parameterized types with +// boolean expressions, since both contain '<'. + +class GenericSyntaxTest { + GenericSyntaxTest() {} + + void foo(x1, x2, x3, x4, x5) { + Expect.equals(true, x1); + Expect.equals(3, x2); + Expect.equals(4, x3); + Expect.equals(5, x4); + Expect.equals(false, x5); + } + + void bar(x) { + Expect.equals(null, x()); + } + + test() { + var a = 1; + var b = 2; + var c = 3; + var d = 4; + var e = 5; + var f = 6; + var g = 7; + var h = null; + bar(A g() { return h; }); // 'A g); // 'a { +} + +main() { + GenericSyntaxTest.testMain(); +} diff --git a/tests/language/src/GenericTest.dart b/tests/language/src/GenericTest.dart new file mode 100644 index 00000000000..15cdd6859bc --- /dev/null +++ b/tests/language/src/GenericTest.dart @@ -0,0 +1,85 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_type_checks --enable_asserts +// +// Dart test program testing generic type allocations and generic type tests. + +class A { + const A(); +} + +class AA extends A { + const AA(); +} + +class AX { + const AX(); +} + +class B { + final A a_; + final T t_; + const B(T t) : a_ = t, t_ = t; + isT(x) { + return x is T; + } +} + +class C { + B b_; + C(T t) : b_ = new B(t) { } +} + +class D { + C caa_; + D() : caa_ = new C(const AA()) { } +} + +class E { + C cax_; + E() : cax_ = new C(const AX()) { } +} + +class GenericTest { + static test() { + int result = 0; + try { + D d = new D(); + Expect.equals(true, d.caa_.b_ is B); + Expect.equals(true, d.caa_.b_.isT(const AA())); + C c = new C(const AA()); // c is of raw type C, T in C is VarType. + Expect.equals(true, c.b_ is B); + Expect.equals(true, c.b_ is B); + Expect.equals(true, c.b_.isT(const AA())); + Expect.equals(true, c.b_.isT(const AX())); + E e = new E(); // Throws a type error, if type checks are enabled. + } catch (TypeError error) { + result = 1; + // TODO(regis): The error below is detected too late. + // It should be reported on line 26, at new B(). + // This will be detected when we check the subtyping constraints. + Expect.equals("A", error.dstType); + Expect.equals("AX", error.srcType); + Expect.equals("a_", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("GenericTest.dart", subs); + Expect.equals(23, error.line); + Expect.equals(23, error.column); + } + return result; + } + + static testMain() { + Expect.equals(1, test()); + } +} + + +main() { + GenericTest.testMain(); +} diff --git a/tests/language/src/GenericsTest.dart b/tests/language/src/GenericsTest.dart new file mode 100644 index 00000000000..e1b1b1b2d03 --- /dev/null +++ b/tests/language/src/GenericsTest.dart @@ -0,0 +1,86 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for generic types. + +class GenericsTest implements Map { + static int myFunc(bool a, bool b) { + Expect.equals(true, a); + Expect.equals(false, b); + return 42; + } + + static void testMain() { + int a = 1; + int b = 2; + int c = 3; + int d = 4; + Expect.equals(true, a d)); + Map e; + GenericsTest> f; + + takesVoidMethod(void _(int a) { + Expect.equals(2, a); + return 99; + }); + + takesGenericMapMethod(Map _(int a) { + Expect.equals(2, a); + return null; + }); + + takesIntMethod(int _(int a) { + Expect.equals(2, a); + return 98; + }); + + e = new Map(); + takesMapMethod(e); + Expect.equals(2, e[0]); + Map h = new Map(); + } + + static void takesVoidMethod(void f(int a)) { + Expect.equals(99, f(2)); + } + + static void takesIntMethod(int f(int a)) { + Expect.equals(98, f(2)); + } + + static void takesGenericMapMethod(Map f(int a)) { + f(2); + } + + static void takesMapMethod(Map m) { + m[0] = 2; + } + + Map returnMap() { + return null; + } +} + +class LongGeneric { +} + +class LongerGeneric { + void func() { + LongGeneric, Map>>> id; + + LongGeneric< + num, + Map, + LongGeneric< + C, + List, + Map>>>> id2; + } +} + +main() { + GenericsTest.testMain(); +} diff --git a/tests/language/src/GettersSettersTest.dart b/tests/language/src/GettersSettersTest.dart new file mode 100644 index 00000000000..57b518f1a39 --- /dev/null +++ b/tests/language/src/GettersSettersTest.dart @@ -0,0 +1,169 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class GettersSettersTest { + + static int foo; + + static testMain() { + A a = new A(); + a.x = 2; + Expect.equals(2, a.x); + Expect.equals(2, a.x_); + + // Test inheritance. + a = new B(); + a.x = 4; + Expect.equals(4, a.x); + Expect.equals(4, a.x_); + + // Test overriding. + C c = new C(); + c.x = 8; + Expect.equals(8, c.x); + Expect.equals(0, c.x_); + Expect.equals(8, c.y_); + + // Test keyed getters and setters. + a.x_ = 0; + Expect.equals(2, a[2]); + a[2] = 4; + Expect.equals(6, a[0]); + + // Test assignment operators. + a.x_ = 0; + a[2] += 8; + Expect.equals(12, a[0]); + + // Test calling a function that internally uses getters. + Expect.equals(true, a.isXPositive()); + + // Test static fields. + foo = 42; + Expect.equals(42, foo); + A.foo = 43; + Expect.equals(43, A.foo); + + new D().test(); + + OverrideField of = new OverrideField(); + Expect.equals(27, of.getX_()); + + ReferenceField rf = new ReferenceField(); + rf.x_ = 1; + Expect.equals(1, rf.getIt()); + rf.setIt(2); + Expect.equals(2, rf.x_); + } +} + +class A { + // TODO(fabiofmv): consider removing once http://b/4254120 is fixed. + A() { } + int x_; + static int foo; + + static get bar() { + return foo; + } + + static set bar(newValue) { + foo = newValue; + } + + int get x() { + return x_; + } + + void set x(int value) { + x_ = value; + } + + bool isXPositive() { + return x > 0; + } + + int operator [](int index) { + return x_ + index; + } + + void operator []=(int index, int value) { + x_ = index + value; + } + + int getX_() { + return x_; + } +} + +class B extends A { + B() : super() {} +} + +class C extends A { + int y_; + + C() : super() { + this.x_ = 0; + } + + int get x() { + return y_; + } + + void set x(int value) { + y_ = value; + } +} + +class D extends A { + D() : super() {} + + var x2_; + + set x(new_x) { + x2_ = new_x; + } + + test() { + x = 87; + Expect.equals(87, x2_); + x = 42; + Expect.equals(42, x2_); + + foo = 0; + Expect.equals(0, bar); + bar = 1; + Expect.equals(1, foo); + var tmp = foo; + foo += 3; + Expect.equals(4, bar); + bar += 5; + Expect.equals(9, foo); + } +} + +class OverrideField extends A { + OverrideField() : super() {} + + int get x_() { + return 27; + } +} + +class ReferenceField extends A { + ReferenceField() : super() {} + + setIt(a) { + super.x_ = a; + } + + int getIt() { + return super.x_; + } +} + +main() { + GettersSettersTest.testMain(); +} diff --git a/tests/language/src/HelloDartTest.dart b/tests/language/src/HelloDartTest.dart new file mode 100644 index 00000000000..a60a5fa0933 --- /dev/null +++ b/tests/language/src/HelloDartTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Simple test program invoked with an option to eagerly +// compile all code that is loaded in the isolate. +// VMOptions=--compile_all + +class HelloDartTest { + static testMain() { + print("Hello, Darter!"); + } +} + + +main() { + HelloDartTest.testMain(); +} diff --git a/tests/language/src/HelloScriptLib.dart b/tests/language/src/HelloScriptLib.dart new file mode 100644 index 00000000000..c1771ffd610 --- /dev/null +++ b/tests/language/src/HelloScriptLib.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Testing a simple script importing a library. +// This file contains the library. + +#library("HelloScriptLib"); +#source("HelloScriptLibSource.dart"); + +class HelloLib { + + static doTest() { + x = 17; + Expect.equals(17, x++); + print("Hello from Lib!"); + } + +} diff --git a/tests/language/src/HelloScriptLibSource.dart b/tests/language/src/HelloScriptLibSource.dart new file mode 100644 index 00000000000..8f44b7b541d --- /dev/null +++ b/tests/language/src/HelloScriptLibSource.dart @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Testing a simple script importing a library. +// This file contains a source file included from the library. + +// A top-level variable being accessed both from the library and the importer. + +var x; diff --git a/tests/language/src/HelloScriptTest.dart b/tests/language/src/HelloScriptTest.dart new file mode 100644 index 00000000000..6c51f856b53 --- /dev/null +++ b/tests/language/src/HelloScriptTest.dart @@ -0,0 +1,15 @@ +#! This is currently only a comment. +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Testing a simple script importing a library. +// This file contains the script (aka root library). + +#import("HelloScriptLib.dart"); + +main() { + HelloLib.doTest(); + Expect.equals(18, x); + print("Hello done."); +} diff --git a/tests/language/src/IfTest.dart b/tests/language/src/IfTest.dart new file mode 100644 index 00000000000..ebf32a8c4c9 --- /dev/null +++ b/tests/language/src/IfTest.dart @@ -0,0 +1,91 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing if statement. + +class Helper { + static int f0(bool b) { + if (b); + if (b); else; + if (b) {} + if (b) {} else {} + return 0; + } + + static int f1(bool b) { + if (b) + return 1; + else + return 2; + } + + static int f2(bool b) { + if (b) { + return 1; + } else { + return 2; + } + } + + static int f3(bool b) { + if (b) return 1; + return 2; + } + + static int f4(bool b) { + if (b) { + return 1; + } + return 2; + } + + static int f5(bool b) { + if (!b) { + return 1; + } + return 2; + } + + static int f6(bool a, bool b) { + if (a || b) { + return 1; + } + return 2; + } + + static int f7(bool a, bool b) { + if (a && b) { + return 1; + } + return 2; + } +} + +class IfTest { + static testMain() { + Expect.equals(0, Helper.f0(true)); + Expect.equals(1, Helper.f1(true)); + Expect.equals(2, Helper.f1(false)); + Expect.equals(1, Helper.f2(true)); + Expect.equals(2, Helper.f2(false)); + Expect.equals(1, Helper.f3(true)); + Expect.equals(2, Helper.f3(false)); + Expect.equals(1, Helper.f4(true)); + Expect.equals(2, Helper.f4(false)); + Expect.equals(2, Helper.f5(true)); + Expect.equals(1, Helper.f5(false)); + Expect.equals(1, Helper.f6(true, true)); + Expect.equals(1, Helper.f6(true, false)); + Expect.equals(1, Helper.f6(false, true)); + Expect.equals(2, Helper.f6(false, false)); + Expect.equals(1, Helper.f7(true, true)); + Expect.equals(2, Helper.f7(true, false)); + Expect.equals(2, Helper.f7(false, true)); + Expect.equals(2, Helper.f7(false, false)); + } +} + + +main() { + IfTest.testMain(); +} diff --git a/tests/language/src/ImplicitClosure1Test.dart b/tests/language/src/ImplicitClosure1Test.dart new file mode 100644 index 00000000000..f23ee683243 --- /dev/null +++ b/tests/language/src/ImplicitClosure1Test.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_type_checks --enable_asserts + +typedef Handler(bool e); + +class Hello { + Hello() {} + void handler2(bool e) { print('handler2'); } + static void handler1(bool e) { print('handler1'); } + void addEventListener(String s, Handler handler, bool status) { + handler(status); + } + + static void main() { + final h = new Hello(); + h.addEventListener('click', handler1, false); + h.addEventListener('click', h.handler2, false); + } +} + +main() { + Hello.main(); +} diff --git a/tests/language/src/ImplicitClosureTest.dart b/tests/language/src/ImplicitClosureTest.dart new file mode 100644 index 00000000000..86ac8d23d16 --- /dev/null +++ b/tests/language/src/ImplicitClosureTest.dart @@ -0,0 +1,38 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing invocation of implicit closures. + +class First { + First(this.i) {} + var b; + int foo() { return i; } + Function foo1() { + local() { + return i; + } + return local; + } + int i; +} + +class ImplicitClosureTest { + static void testMain() { + First obj = new First(20); + + Function func = () => obj.i; + obj.b = func; + Expect.equals(20, obj.b()); + + var ib1 = obj.foo1(); + Expect.equals(obj.i, ib1()); + + var ib = obj.foo; + Expect.equals(obj.i, ib()); + } +} + + +main() { + ImplicitClosureTest.testMain(); +} diff --git a/tests/language/src/ImplicitScopeTest.dart b/tests/language/src/ImplicitScopeTest.dart new file mode 100644 index 00000000000..3446fb20e51 --- /dev/null +++ b/tests/language/src/ImplicitScopeTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that if, while etc create an implicit scope if the body +// is not a compound statement. + +class ImplicitScopeTest { + static bool alwaysTrue() { + return 1 + 1 == 2; + } + static testMain() { + var a = "foo"; + var b; + if (alwaysTrue()) var a = "bar"; else var b = a; + Expect.equals("foo", a); + Expect.equals(null, b); + + while (!alwaysTrue()) var a = "bar", b = "baz"; + Expect.equals("foo", a); + Expect.equals(null, b); + + for (int i = 0; i < 10; i++) var a = "bar", b = "baz"; + Expect.equals("foo", a); + Expect.equals(null, b); + + do var a = "bar", b = "baz"; while("black" == "white"); + Expect.equals("foo", a); + Expect.equals(null, b); + } +} + +main() { + ImplicitScopeTest.testMain(); +} diff --git a/tests/language/src/ImpliedInterfaceTest.dart b/tests/language/src/ImpliedInterfaceTest.dart new file mode 100644 index 00000000000..54672380c32 --- /dev/null +++ b/tests/language/src/ImpliedInterfaceTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class BaseClass { + var foo; + BaseClass() { foo = 0; } + toString() => "BaseClass"; +} + +class ImplementsClass implements BaseClass { + ImplementsClass() {} +} + +interface ExtendsClass extends BaseClass {} + +class ImplementsExtendsClass implements ExtendsClass { + ImplementsExtendsClass() {} +} + +main() { + ImplementsClass c1 = new ImplementsClass(); + ImplementsExtendsClass c2 = new ImplementsExtendsClass(); + if (false) { + // Verify we don't inherit the field from BaseClass + Expect.equals(0, c1.foo); // 01: compile-time error + Expect.equals(0, c2.foo); // 02: compile-time error + } + Expect.equals(true, c1 is BaseClass); + Expect.equals(true, c1 is !ExtendsClass); + Expect.equals(true, c2 is BaseClass); + Expect.equals(true, c2 is ExtendsClass); + Expect.equals(true, c2 is !ImplementsClass); + Expect.equals("BaseClass", "${new BaseClass()}"); + + // Verify we don't inherit toString from BaseClass + Expect.equals("${new Object()}", "${c1}"); + Expect.equals("${new Object()}", "${c2}"); +} diff --git a/tests/language/src/ImportCoreImplNoPrefixTest.dart b/tests/language/src/ImportCoreImplNoPrefixTest.dart new file mode 100644 index 00000000000..be94e56b580 --- /dev/null +++ b/tests/language/src/ImportCoreImplNoPrefixTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program importing the core library explicitly. + +#import("dart:coreimpl"); + +main() { + var e = new ExceptionImplementation("test, test, test"); + print('"dart:coreimpl" imported, $e allocated'); +} diff --git a/tests/language/src/ImportCoreNoPrefixTest.dart b/tests/language/src/ImportCoreNoPrefixTest.dart new file mode 100644 index 00000000000..b6f719eee7f --- /dev/null +++ b/tests/language/src/ImportCoreNoPrefixTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program importing the core library explicitly. + +#import("dart:core"); + +main() { + print('"dart:core" imported.'); +} diff --git a/tests/language/src/IncrOpTest.dart b/tests/language/src/IncrOpTest.dart new file mode 100644 index 00000000000..a87d3bd712e --- /dev/null +++ b/tests/language/src/IncrOpTest.dart @@ -0,0 +1,83 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing increment operator. + +class A { + static var yy; + static set y(v) { + yy = v; + } + + static get y() { + return yy; + } +} + +class IncrOpTest { + var x; + static var y; + + IncrOpTest() {} + + static testMain() { + var a = 3; + var c = a++ + 1; + Expect.equals(4, c); + Expect.equals(4, a); + c = a-- + 1; + Expect.equals(5, c); + Expect.equals(3, a); + + c = --a + 1; + Expect.equals(3, c); + Expect.equals(2, a); + + c = 2 + ++a; + Expect.equals(5, c); + Expect.equals(3, a); + + var obj = new IncrOpTest(); + obj.x = 100; + Expect.equals(100, obj.x); + obj.x++; + Expect.equals(101, obj.x); + Expect.equals(102, ++obj.x); + Expect.equals(102, obj.x++); + Expect.equals(103, obj.x); + + A.y = 55; + Expect.equals(55, A.y++); + Expect.equals(56, A.y); + Expect.equals(57, ++A.y); + Expect.equals(57, A.y); + Expect.equals(56, --A.y); + + IncrOpTest.y = 55; + Expect.equals(55, IncrOpTest.y++); + Expect.equals(56, IncrOpTest.y); + Expect.equals(57, ++IncrOpTest.y); + Expect.equals(57, IncrOpTest.y); + Expect.equals(56, --IncrOpTest.y); + + var list = new List(4); + for (int i = 0; i < list.length; i++) { + list[i] = i; + } + for (int i = 0; i < list.length; i++) { + list[i]++; + } + for (int i = 0; i < list.length; i++) { + Expect.equals(i + 1, list[i]); + ++list[i]; + } + Expect.equals(1 + 2, list[1]); + Expect.equals(1 + 2, list[1]--); + Expect.equals(1 + 1, list[1]); + Expect.equals(1 + 0, --list[1]); + } +} + +main() { + IncrOpTest.testMain(); +} diff --git a/tests/language/src/IndexTest.dart b/tests/language/src/IndexTest.dart new file mode 100644 index 00000000000..dbe42074717 --- /dev/null +++ b/tests/language/src/IndexTest.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing index operators. + +class Helper { + static int fibonacci(int n) { + int a = 0, b = 1, i = 0; + while (i++ < n) { + a = a + b; + b = a - b; + } + return a; + } +} + +class IndexTest { + static final ID_IDLE = 0; + + static testMain() { + var a = new List(10); + Expect.equals(10, a.length); + for (int i = 0; i < a.length; i++) { + a[i] = Helper.fibonacci(i); + } + a[ID_IDLE] = Helper.fibonacci(0); + for (int i = 2; i < a.length; i++) { + Expect.equals(a[i-2] + a[i-1], a[i]); + } + Expect.equals(515, a[3] = 515); + } +} + +main() { + IndexTest.testMain(); +} diff --git a/tests/language/src/InlineGetterTest.dart b/tests/language/src/InlineGetterTest.dart new file mode 100644 index 00000000000..eb671f967d5 --- /dev/null +++ b/tests/language/src/InlineGetterTest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test inlining of instance getters. +// Three classes access always the same field. Optimize method foo and inline +// getter for classes 'A' and 'B'. Call later via 'C' and cause deoptimization. + +class A { + int f; + A(this.f) {} + int foo() { + return f; // <-- inline getter for classes 'A' and 'B'. + } +} + +class B extends A { + B() : super(2) {} +} + +class C extends A { + C() : super(10) {} +} + +class InlineGetterTest { + static testMain() { + var a = new A(1); + var b = new B(); + int sum = 0; + for (int i = 0; i < 5000; i++) { + sum += a.foo(); + sum += b.foo(); + } + var c = new C(); + sum += c.foo(); // <-- Deoptimizing. + Expect.equals(15010, sum); + } +} + +main() { + InlineGetterTest.testMain(); +} diff --git a/tests/language/src/InstFieldInitializer1NegativeTest.dart b/tests/language/src/InstFieldInitializer1NegativeTest.dart new file mode 100644 index 00000000000..44fcca13a11 --- /dev/null +++ b/tests/language/src/InstFieldInitializer1NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Catch illegal access to 'this' in initalized instance fields. + + +class A { + A() {} + int x = 5; + int arr = new List(x); // Illegal access to 'this'. + // Also not a compile const expression. +} + +void main() { + var foo = new A(); +} diff --git a/tests/language/src/InstFieldInitializerTest.dart b/tests/language/src/InstFieldInitializerTest.dart new file mode 100644 index 00000000000..9d30ccdf6c3 --- /dev/null +++ b/tests/language/src/InstFieldInitializerTest.dart @@ -0,0 +1,60 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test for instance field initializer expressions. + +class Cheese { + static final mild = 1; + static final stinky = 2; + + // Instance fields with initializer expression. + String name = ""; + var smell = mild; + + Cheese() { + Expect.equals("", this.name); + Expect.equals(Cheese.mild, this.smell); + } + + Cheese.initInBlock(String s) { + Expect.equals("", this.name); + Expect.equals(Cheese.mild, this.smell); + this.name = s; + } + + Cheese.initFieldParam(this.name, this.smell) { + } + + // Test that static final field Cheese.mild is not shadowed + // by the parameter mild when compiling the field initializer + // for instance field smell. + Cheese.hideAndSeek(var mild) : name = mild { + Expect.equals(mild, this.name); + Expect.equals(Cheese.mild, this.smell); + } +} + +class HasNoExplicitConstructor { + String s = "Tilsiter"; +} + +main() { + var generic = new Cheese(); + Expect.equals("", generic.name); + Expect.equals(Cheese.mild, generic.smell); + + var gruyere = new Cheese.initInBlock("Gruyere"); + Expect.equals("Gruyere", gruyere.name); + Expect.equals(Cheese.mild, gruyere.smell); + + var munster = new Cheese.initFieldParam("Munster", Cheese.stinky); + Expect.equals("Munster", munster.name); + Expect.equals(Cheese.stinky, munster.smell); + + var brie = new Cheese.hideAndSeek("Brie"); + Expect.equals("Brie", brie.name); + Expect.equals(Cheese.mild, brie.smell); + + var t = new HasNoExplicitConstructor(); + Expect.equals("Tilsiter", t.s); +} diff --git a/tests/language/src/InstanceCallWrongArgumentCountNegativeTest.dart b/tests/language/src/InstanceCallWrongArgumentCountNegativeTest.dart new file mode 100644 index 00000000000..a64a7288d1b --- /dev/null +++ b/tests/language/src/InstanceCallWrongArgumentCountNegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test mismatch in argument counts. + +class InstanceCallWrongArgumentCountNegativeTest { + static void testMain() { + Niederhorn nh = new Niederhorn(); + nh.goodCall(1, 2, 3); + // Bad call. + nh.goodCall(1, 2, 3, 4); + } +} + +class Niederhorn { + Niederhorn() {} + int goodCall(int a, int b, int c) { + return a + b; + } +} + +main() { + InstanceCallWrongArgumentCountNegativeTest.testMain(); +} diff --git a/tests/language/src/InstanceCompoundAssignmentOperatorTest.dart b/tests/language/src/InstanceCompoundAssignmentOperatorTest.dart new file mode 100644 index 00000000000..7b3e15316fe --- /dev/null +++ b/tests/language/src/InstanceCompoundAssignmentOperatorTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test correct instance compound assignment operator. + +class A { + A() : f = 2 {} + var f; +} + + +class B { + B() : _a = new A(), count = 0 {} + get a() { + count++; + return _a; + } + var _a; + var count; +} + + +class InstanceCompoundAssignmentOperatorTest { + static void testMain() { + B b = new B(); + Expect.equals(0, b.count); + Expect.equals(2, b.a.f); + Expect.equals(1, b.count); + var o = b.a; + Expect.equals(2, b.count); + b.a.f = 1; + Expect.equals(3, b.count); + b.a.f += 1; + Expect.equals(4, b.count); + } +} +main() { + InstanceCompoundAssignmentOperatorTest.testMain(); +} diff --git a/tests/language/src/InstanceFieldInitializerTest.dart b/tests/language/src/InstanceFieldInitializerTest.dart new file mode 100644 index 00000000000..20f11cad8e2 --- /dev/null +++ b/tests/language/src/InstanceFieldInitializerTest.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + int x = 1; + A() {} + A.reassign() : x = 2 {} + A.reassign2(this.x) {} +} + +class B extends A { + B() : super() {} + B.reassign() : super.reassign() {} + B.reassign2() : super.reassign2(3) {} +} + +class InstanceFieldInitializerTest { + static testMain() { + Expect.equals(1, new A().x); + Expect.equals(2, new A.reassign().x); + Expect.equals(3, new A.reassign2(3).x); + + Expect.equals(1, new B().x); + Expect.equals(2, new B.reassign().x); + Expect.equals(3, new B.reassign2().x); + } +} + +main() { + InstanceFieldInitializerTest.testMain(); +} diff --git a/tests/language/src/InstanceFieldNegativeTest.dart b/tests/language/src/InstanceFieldNegativeTest.dart new file mode 100644 index 00000000000..9c1d72c91a5 --- /dev/null +++ b/tests/language/src/InstanceFieldNegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test to check that we correctly flag the use of an +// instance field from a static method. + + +class Goofy { + String instField; + static String bark() { + return instField; // Should get error here. + } +} + +class InstanceFieldNegativeTest { + static testMain() { + var s = Goofy.bark(); + } +} + + +main() { + InstanceFieldNegativeTest.testMain(); +} diff --git a/tests/language/src/InstanceMethod2NegativeTest.dart b/tests/language/src/InstanceMethod2NegativeTest.dart new file mode 100644 index 00000000000..756dcf6520c --- /dev/null +++ b/tests/language/src/InstanceMethod2NegativeTest.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test to check that we correctly flag the use of an +// instance method (as a closure) from a static method. + + +class Goofy { + String instMethod() { + return "woof"; + } + static Function bark() { + return instMethod; // Should get error here. + } +} + +class InstanceMethod2NegativeTest { + static testMain() { + var s = Goofy.bark(); + } +} + + +main() { + InstanceMethod2NegativeTest.testMain(); +} diff --git a/tests/language/src/InstanceMethodNegativeTest.dart b/tests/language/src/InstanceMethodNegativeTest.dart new file mode 100644 index 00000000000..34d4e90e6ef --- /dev/null +++ b/tests/language/src/InstanceMethodNegativeTest.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test to check that we correctly flag the use of an +// instance method from a static method. + + +class Goofy { + String instMethod() { + return "woof"; + } + static String bark() { + return instMethod(); // Should get error here. + } +} + +class InstanceMethodNegativeTest { + static testMain() { + var s = Goofy.bark(); + } +} + + +main() { + InstanceMethodNegativeTest.testMain(); +} diff --git a/tests/language/src/Instanceof2Test.dart b/tests/language/src/Instanceof2Test.dart new file mode 100644 index 00000000000..8ca45cc0706 --- /dev/null +++ b/tests/language/src/Instanceof2Test.dart @@ -0,0 +1,101 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing the instanceof operation. + +interface I { } + +interface AI extends I { } + +class A implements AI { + const A(); +} + +class B implements I { + const B(); +} + +class C extends A { + const C() : super(); +} + +class InstanceofTest { + static testMain() { + var a = new A(); + var b = new B(); + var c = new C(); + var n = null; + + Expect.equals(true, a is A); + Expect.equals(true, b is B); + Expect.equals(true, c is C); + Expect.equals(true, c is A); + + Expect.equals(true, a is AI); + Expect.equals(true, a is I); + Expect.equals(false, b is AI); + Expect.equals(true, b is I); + Expect.equals(true, c is AI); + Expect.equals(true, c is I); + Expect.equals(false, n is AI); + Expect.equals(false, n is I); + + Expect.equals(false, a is B); + Expect.equals(false, a is C); + Expect.equals(false, b is A); + Expect.equals(false, b is C); + Expect.equals(false, c is B); + Expect.equals(false, n is A); + + Expect.equals(false, null is A); + Expect.equals(false, null is B); + Expect.equals(false, null is C); + Expect.equals(false, null is AI); + Expect.equals(false, null is I); + + { + var a = new List(5); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + } + { + var a = new List(5); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(false, a is List); + Expect.equals(false, a is List); + Expect.equals(false, a is List); + } + { + var a = new List(5); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(false, a is List); + } + { + var a = new List(5); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(false, a is List); + Expect.equals(true, a is List); + Expect.equals(false, a is List); + } + { + var a = new List(5); + Expect.equals(true, a is List); + Expect.equals(true, a is List); + Expect.equals(false, a is List); + Expect.equals(false, a is List); + Expect.equals(true, a is List); + } + } +} + +main() { + InstanceofTest.testMain(); +} diff --git a/tests/language/src/InstanceofTest.dart b/tests/language/src/InstanceofTest.dart new file mode 100644 index 00000000000..988deedce1c --- /dev/null +++ b/tests/language/src/InstanceofTest.dart @@ -0,0 +1,184 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class InstanceofTest { + + InstanceofTest() {} + + static void testBasicTypes() { + Expect.equals(true, 0 is int); + Expect.equals(false, (0 is bool)); + Expect.equals(false, (0 is String)); + Expect.equals(true, 1 is int); + Expect.equals(false, (1 is bool)); + Expect.equals(false, (1 is String)); + + Expect.equals(false, (true is int)); + Expect.equals(true, true is bool); + Expect.equals(false, (true is String)); + Expect.equals(false, (false is int)); + Expect.equals(true, false is bool); + Expect.equals(false, (false is String)); + + Expect.equals(false, ("a" is int)); + Expect.equals(false, ("a" is bool)); + Expect.equals(true, "a" is String); + + Expect.equals(false, ("" is int)); + Expect.equals(false, ("" is bool)); + Expect.equals(true, "" is String); + } + + static void testInterfaces() { + // Simple Cases with interfaces. + var a = new A(); + Expect.equals(true, a is I); + Expect.equals(true, a is A); + Expect.equals(false, (a is String)); + Expect.equals(false, (a is int)); + Expect.equals(false, (a is bool)); + Expect.equals(false, (a is B)); + Expect.equals(false, (a is J)); + + // Interfaces with parent + var c = new C(); + Expect.equals(true, c is I); + Expect.equals(true, c is J); + Expect.equals(true, c is K); + + var d = new D(); + Expect.equals(true, d is I); + Expect.equals(true, d is J); + Expect.equals(true, d is K); + + Expect.equals(true, [] is List); + Expect.equals(true, [1,2,3] is List); + Expect.equals(false, (d is List)); + Expect.equals(false, (null is List)); + Expect.equals(false, (null is D)); + } + + static void testnum() { + Expect.equals(true, 0 is num); + Expect.equals(true, 123 is num); + Expect.equals(true, 123.34 is num); + Expect.equals(false, ("123" is num)); + Expect.equals(false, (null is num)); + Expect.equals(false, (true is num)); + Expect.equals(false, (false is num)); + var a = new A(); + Expect.equals(false, (a is num)); + } + + + static void testTypeOfInstanceOf() { + var a = new A(); + // Interfaces with parent + var c = new C(); + var d = new D(); + + Expect.equals(true, (null is int) is bool); + Expect.equals(true, (null is bool) is bool); + Expect.equals(true, (null is String) is bool); + Expect.equals(true, (null is A) is bool); + Expect.equals(true, (null is B) is bool); + Expect.equals(true, (null is I) is bool); + Expect.equals(true, (null is J) is bool); + + Expect.equals(true, (0 is int) is bool); + Expect.equals(true, (0 is bool) is bool); + Expect.equals(true, (0 is String) is bool); + Expect.equals(true, (0 is A) is bool); + Expect.equals(true, (0 is B) is bool); + Expect.equals(true, (0 is I) is bool); + Expect.equals(true, (0 is J) is bool); + + Expect.equals(true, (1 is int) is bool); + Expect.equals(true, (1 is bool) is bool); + Expect.equals(true, (1 is String) is bool); + Expect.equals(true, (1 is A) is bool); + Expect.equals(true, (1 is B) is bool); + Expect.equals(true, (1 is I) is bool); + Expect.equals(true, (1 is J) is bool); + + Expect.equals(true, (true is int) is bool); + Expect.equals(true, (true is bool) is bool); + Expect.equals(true, (true is String) is bool); + Expect.equals(true, (true is A) is bool); + Expect.equals(true, (true is B) is bool); + Expect.equals(true, (true is I) is bool); + Expect.equals(true, (true is J) is bool); + + Expect.equals(true, (false is int) is bool); + Expect.equals(true, (false is bool) is bool); + Expect.equals(true, (false is String) is bool); + Expect.equals(true, (false is A) is bool); + Expect.equals(true, (false is B) is bool); + Expect.equals(true, (false is I) is bool); + Expect.equals(true, (false is J) is bool); + + Expect.equals(true, ("a" is int) is bool); + Expect.equals(true, ("a" is bool) is bool); + Expect.equals(true, ("a" is String) is bool); + Expect.equals(true, ("a" is A) is bool); + Expect.equals(true, ("a" is B) is bool); + Expect.equals(true, ("a" is I) is bool); + Expect.equals(true, ("a" is J) is bool); + + Expect.equals(true, ("" is int) is bool); + Expect.equals(true, ("" is bool) is bool); + Expect.equals(true, ("" is String) is bool); + Expect.equals(true, ("" is A) is bool); + Expect.equals(true, ("" is B) is bool); + Expect.equals(true, ("" is I) is bool); + Expect.equals(true, ("" is J) is bool); + + Expect.equals(true, (a is int) is bool); + Expect.equals(true, (a is bool) is bool); + Expect.equals(true, (a is String) is bool); + Expect.equals(true, (a is A) is bool); + Expect.equals(true, (a is B) is bool); + Expect.equals(true, (a is I) is bool); + Expect.equals(true, (a is J) is bool); + + Expect.equals(true, (c is int) is bool); + Expect.equals(true, (c is bool) is bool); + Expect.equals(true, (c is String) is bool); + Expect.equals(true, (c is A) is bool); + Expect.equals(true, (c is B) is bool); + Expect.equals(true, (c is I) is bool); + Expect.equals(true, (c is J) is bool); + + Expect.equals(true, (d is int) is bool); + Expect.equals(true, (d is bool) is bool); + Expect.equals(true, (d is String) is bool); + Expect.equals(true, (d is A) is bool); + Expect.equals(true, (d is B) is bool); + Expect.equals(true, (d is I) is bool); + Expect.equals(true, (d is J) is bool); + } + + static void testMain() { + testBasicTypes(); + // TODO(sra): enable after fixing b/4604295 + // testnum(); + testInterfaces(); + testTypeOfInstanceOf(); + } +} + +interface I {} +class A implements I {A() {}} +class B {B() {}} + +interface J {} + +interface K extends J {} +class C implements I, K {C() {}} + +class D extends C {D() : super() {}} + +main() { + InstanceofTest.testMain(); +} diff --git a/tests/language/src/InstantiateTypeVariableNegativeTest.dart b/tests/language/src/InstantiateTypeVariableNegativeTest.dart new file mode 100644 index 00000000000..1ced0585618 --- /dev/null +++ b/tests/language/src/InstantiateTypeVariableNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that you cannot instantiate a type variable. + +class Foo { + Foo() {} + T make() { return new T(); } +} + +main() { + new Foo().make(); +} diff --git a/tests/language/src/IntTest.dart b/tests/language/src/IntTest.dart new file mode 100644 index 00000000000..298f716669e --- /dev/null +++ b/tests/language/src/IntTest.dart @@ -0,0 +1,57 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test basic integer operations. + +class IntTest { + static void testMain() { + Expect.equals(0, 0 + 0); + Expect.equals(1, 1 + 0); + Expect.equals(2, 1 + 1); + Expect.equals(3, -1 + 4); + Expect.equals(3, 4 + -1); + + Expect.equals(1, 1 - 0); + Expect.equals(0, 1 - 1); + Expect.equals(1, 2 - 1); + Expect.equals(2, 4 - 2); + Expect.equals(-2, 2 - 4); + + Expect.equals(0, 3 * 0); + Expect.equals(0, 0 * 3); + Expect.equals(1, 1 * 1); + Expect.equals(5, 5 * 1); + Expect.equals(15, 3 * 5); + Expect.equals(-1, 1 * -1); + Expect.equals(-15, -5 * 3); + Expect.equals(15, -5 * -3); + + Expect.equals(1, 2 ~/ 2); + Expect.equals(2, 2 ~/ 1); + Expect.equals(2, 4 ~/ 2); + Expect.equals(2, 5 ~/ 2); + Expect.equals(-2, -5 ~/ 2); + Expect.equals(-2, -4 ~/ 2); + Expect.equals(-2, 5 ~/ -2); + Expect.equals(-2, 4 ~/ -2); + + Expect.equals(3, 7 % 4); + Expect.equals(2, 9 % 7); + Expect.equals(2, -7 % 9); + Expect.equals(7, 7 % -9); + Expect.equals(7, 7 % 9); + Expect.equals(2, -7 % -9); + + Expect.equals(3, (7).remainder(4)); + Expect.equals(2, (9).remainder(7)); + Expect.equals(-7, (-7).remainder(9)); + Expect.equals(7, (7).remainder(-9)); + Expect.equals(7, (7).remainder(9)); + Expect.equals(-7, (-7).remainder(-9)); + } +} + + +main() { + IntTest.testMain(); +} diff --git a/tests/language/src/Interface2NegativeTest.dart b/tests/language/src/Interface2NegativeTest.dart new file mode 100644 index 00000000000..27f4565aac9 --- /dev/null +++ b/tests/language/src/Interface2NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing wrong interface reference: +// A class must implement a known interface. + + +class Interface2NegativeTest implements BooHoo { + static testMain() { + } +} + +main() { + Interface2NegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceConstantsTest.dart b/tests/language/src/InterfaceConstantsTest.dart new file mode 100644 index 00000000000..07056d0d9a8 --- /dev/null +++ b/tests/language/src/InterfaceConstantsTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface Constants { + static final int FIVE = 5; +} + +class InterfaceConstantsTest { + InterfaceConstantsTest() {} + + static void testMain() { + Expect.equals(5, Constants.FIVE); + } +} + +main() { + InterfaceConstantsTest.testMain(); +} diff --git a/tests/language/src/InterfaceCycleNegativeTest.dart b/tests/language/src/InterfaceCycleNegativeTest.dart new file mode 100644 index 00000000000..52b8edaead2 --- /dev/null +++ b/tests/language/src/InterfaceCycleNegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check fail because of cycles in super interface relationship. + +interface C extends B { + +} + +interface A extends B { + +} + +interface B extends A { + +} + +class InterfaceCycleNegativeTest { + static testMain() { + } +} + +main() { + InterfaceCycleNegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceFactory1NegativeTest.dart b/tests/language/src/InterfaceFactory1NegativeTest.dart new file mode 100644 index 00000000000..c882db06402 --- /dev/null +++ b/tests/language/src/InterfaceFactory1NegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test that a "default implementation" interface factory only +// provides the constructors declared in the interface. + +interface Interface factory DefaultImplementation { + Interface.some_name(); +} + +class DefaultImplementation implements Interface { + DefaultImplementation.some_name() {} + DefaultImplementation.wrong_name() {} + + static testMain() { + // We should not be able to find Interface.wrong_name(). + new Interface.wrong_name(); + } +} + +main() { + DefaultImplementation.testMain(); +} diff --git a/tests/language/src/InterfaceFactory2NegativeTest.dart b/tests/language/src/InterfaceFactory2NegativeTest.dart new file mode 100644 index 00000000000..a154255239a --- /dev/null +++ b/tests/language/src/InterfaceFactory2NegativeTest.dart @@ -0,0 +1,33 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test that a "factory provider" interface factory only +// provides the constructors declared in the interface. + +interface Interface factory FactoryProvider { + Interface.some_name(var secret); +} + +class SomeImplementation implements Interface { + SomeImplementation() {} +} + +class FactoryProvider { + factory Interface.some_name() { + return new SomeImplementation(); + } + + factory Interface.wrong_name() { + return new SomeImplementation(); + } + + static testMain() { + // We should not be able to find Interface1.wrong_name(). + new Interface.wrong_name(); + } +} + +main() { + FactoryProvider.testMain(); +} diff --git a/tests/language/src/InterfaceFactory3NegativeTest.dart b/tests/language/src/InterfaceFactory3NegativeTest.dart new file mode 100644 index 00000000000..524beb62cd3 --- /dev/null +++ b/tests/language/src/InterfaceFactory3NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test that a "default implementation" interface factory checks the +// arity of its declared constructor arguments + +interface Interface factory DefaultImplementation { + Interface(int x, int y); +} + +class DefaultImplementation implements Interface { + DefaultImplementation() {} + + static testMain() { + // We should not be able to find the nullary Interface constructor. + new Interface(); + } +} + +main() { + DefaultImplementation.testMain(); +} diff --git a/tests/language/src/InterfaceFactoryConstructorNegativeTest.dart b/tests/language/src/InterfaceFactoryConstructorNegativeTest.dart new file mode 100644 index 00000000000..bcbcd3e0bc4 --- /dev/null +++ b/tests/language/src/InterfaceFactoryConstructorNegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface A { + factory A(); +} + +class InterfaceFactoryConstructorNegativeTest { + + static testMain() { + } +} + +main() { + InterfaceFactoryConstructorNegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceFactoryMultiTest.dart b/tests/language/src/InterfaceFactoryMultiTest.dart new file mode 100644 index 00000000000..7dc12766d02 --- /dev/null +++ b/tests/language/src/InterfaceFactoryMultiTest.dart @@ -0,0 +1,51 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +// Test that a factory provider can provide for more than one interface. + +interface A factory F { + A(var secret); + + GetSecret(); +} + +class AImpl implements A { + String _secret; + + AImpl(String one, String two) : _secret = one + two; + + String GetSecret() { return _secret; } +} + +interface B factory F { + B(var secret); + + GetSecret(); +} + +class BImpl implements B { + String _secret; + + BImpl(String one, String two) : _secret = two + one; + + String GetSecret() { return _secret; } +} + + +// One factory provider for two interfaces. +class F { + factory A(var secret) { + return new AImpl(secret, 'A'); + } + + factory B(var secret) { + return new BImpl(secret, 'B'); + } +} + +main() { + Expect.equals('1A', new A('1').GetSecret()); + Expect.equals('B2', new B('2').GetSecret()); +} diff --git a/tests/language/src/InterfaceFactoryTest.dart b/tests/language/src/InterfaceFactoryTest.dart new file mode 100644 index 00000000000..e39de7efa13 --- /dev/null +++ b/tests/language/src/InterfaceFactoryTest.dart @@ -0,0 +1,68 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test that the two major variations of interface factories work. + +// Variant 1. The factory class implements the interface and provides +// a default implementation of the interface. + +interface Interface1 factory DefaultImplementation { + Interface1(var secret); + Interface1.named(); + + GetSecret(); +} + +class DefaultImplementation implements Interface1 { + int _secret; + + DefaultImplementation(int this._secret) {} + DefaultImplementation.named() : this._secret = 11 {} + + int GetSecret() { return _secret; } + + static testMain() { + Expect.equals(7, new Interface1(7).GetSecret()); + Expect.equals(11, new Interface1.named().GetSecret()); + } +} + +// Variant 2. The factory class provides factory constructors for the +// interface. + +interface Interface2 factory FactoryProvider { + Interface2(var secret); + Interface2.named(); + + GetSecret(); +} + +class SomeImplementation implements Interface2 { + String _secret; + + SomeImplementation(String one, String two) : _secret = one + two {} + + String GetSecret() { return _secret; } +} + +// Note that FactoryProvider does not implement Interface2. +class FactoryProvider { + factory Interface2(var secret) { + return new SomeImplementation(secret, secret); + } + + factory Interface2.named() { + return new SomeImplementation("Named", "Constructor"); + } + + static testMain() { + Expect.equals("cobracobra", new Interface2("cobra").GetSecret()); + Expect.equals("NamedConstructor", new Interface2.named().GetSecret()); + } +} + +main() { + DefaultImplementation.testMain(); + FactoryProvider.testMain(); +} diff --git a/tests/language/src/InterfaceFunctionTypeAlias1NegativeTest.dart b/tests/language/src/InterfaceFunctionTypeAlias1NegativeTest.dart new file mode 100644 index 00000000000..9f58a0ef9f5 --- /dev/null +++ b/tests/language/src/InterfaceFunctionTypeAlias1NegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that deprecated syntax for introducing function type aliases +// using the interface keyword isn't valid anymore. + +interface function f(); + +main() { + InterfaceFunctionTypeAlias1NegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceFunctionTypeAlias2NegativeTest.dart b/tests/language/src/InterfaceFunctionTypeAlias2NegativeTest.dart new file mode 100644 index 00000000000..91efa4fb4bf --- /dev/null +++ b/tests/language/src/InterfaceFunctionTypeAlias2NegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that deprecated syntax for introducing function type aliases +// using the interface keyword isn't valid anymore. + +interface void f(); + +main() { + InterfaceFunctionTypeAlias2NegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceFunctionTypeAlias3NegativeTest.dart b/tests/language/src/InterfaceFunctionTypeAlias3NegativeTest.dart new file mode 100644 index 00000000000..803c443bdba --- /dev/null +++ b/tests/language/src/InterfaceFunctionTypeAlias3NegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that deprecated syntax for introducing function type aliases +// using the interface keyword isn't valid anymore. + +interface String f(); + +main() { + InterfaceFunctionTypeAlias3NegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceInjection1NegativeTest.dart b/tests/language/src/InterfaceInjection1NegativeTest.dart new file mode 100644 index 00000000000..c219450c0eb --- /dev/null +++ b/tests/language/src/InterfaceInjection1NegativeTest.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface S { } +interface I { } +interface I extends S; + +class C implements I { } + +main() { + Expect.equals(true, new C() is S); +} diff --git a/tests/language/src/InterfaceInjection2NegativeTest.dart b/tests/language/src/InterfaceInjection2NegativeTest.dart new file mode 100644 index 00000000000..82a9afce45c --- /dev/null +++ b/tests/language/src/InterfaceInjection2NegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface S { } +class C { } +class C implements S; + +main() { + Expect.equals(true, new C() is S); +} diff --git a/tests/language/src/InterfaceStaticMethodNegativeTest.dart b/tests/language/src/InterfaceStaticMethodNegativeTest.dart new file mode 100644 index 00000000000..238dbdc0f91 --- /dev/null +++ b/tests/language/src/InterfaceStaticMethodNegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface A { + static void foo(); +} + +class InterfaceStaticMethodNegativeTest { + + static testMain() { + } +} + +main() { + InterfaceStaticMethodNegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceStaticNonFinalFieldsNegativeTest.dart b/tests/language/src/InterfaceStaticNonFinalFieldsNegativeTest.dart new file mode 100644 index 00000000000..ef1eb4902e6 --- /dev/null +++ b/tests/language/src/InterfaceStaticNonFinalFieldsNegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +interface A { + static var a; +} + +class InterfaceStaticNonConstFieldsNegativeTest { + + static testMain() { + } +} + +main() { + InterfaceStaticNonFinalFieldsNegativeTest.testMain(); +} diff --git a/tests/language/src/InterfaceTest.dart b/tests/language/src/InterfaceTest.dart new file mode 100644 index 00000000000..e39a66f480d --- /dev/null +++ b/tests/language/src/InterfaceTest.dart @@ -0,0 +1,44 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing params. + +interface Ai { + int foo(); +} + +interface Bi extends Ai factory InterfaceTest { + Bi(); +} + +interface Simple extends Ai { } + +interface Aai { } + +interface Abi { } + +interface Bar { } + +interface Foo extends Bar { } + +interface Baz extends Bar, Foo { } + +class InterfaceTest implements Ai, Aai, Abi, Baz, Bi { + var f; + + InterfaceTest() {} + int foo() { return 1; } + + abstract beta(); + abstract String beta1(); + abstract String beta2(double d); + + static testMain() { + var o = new Bi(); + Expect.equals(1, o.foo()); + } +} + +main() { + InterfaceTest.testMain(); +} diff --git a/tests/language/src/IsNotClass1NegativeTest.dart b/tests/language/src/IsNotClass1NegativeTest.dart new file mode 100644 index 00000000000..5fafbbdd07b --- /dev/null +++ b/tests/language/src/IsNotClass1NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for catch that we expect a class after an 'is'. + +class A { + const A(); +} + +class IsNotClass1NegativeTest { + static testMain() { + var a = new A(); + + if (a is "A") { + return 0; + } + return 0; + } +} + +main() { + IsNotClass1NegativeTest.testMain(); +} diff --git a/tests/language/src/IsNotClass2NegativeTest.dart b/tests/language/src/IsNotClass2NegativeTest.dart new file mode 100644 index 00000000000..3883910b12f --- /dev/null +++ b/tests/language/src/IsNotClass2NegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for catch that we expect a class after an 'is'. + +class A { + const A(); +} + +class IsNotClass2NegativeTest { + static testMain() { + var a = new A(); + var aa = new A(); + + if (a is aa) { + return 0; + } + return 0; + } +} + +main() { + IsNotClass2NegativeTest.testMain(); +} diff --git a/tests/language/src/IsNotClass3NegativeTest.dart b/tests/language/src/IsNotClass3NegativeTest.dart new file mode 100644 index 00000000000..8b53ba68712 --- /dev/null +++ b/tests/language/src/IsNotClass3NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for catch that we expect a class after an 'is'. + +class A { + const A(); +} + +class IsNotClass3NegativeTest { + static testMain() { + var a = new A(); + + if (a is B) { + return 0; + } + return 0; + } +} + +main() { + IsNotClass3NegativeTest.testMain(); +} diff --git a/tests/language/src/IsNotClass4NegativeTest.dart b/tests/language/src/IsNotClass4NegativeTest.dart new file mode 100644 index 00000000000..84ef5ed1c58 --- /dev/null +++ b/tests/language/src/IsNotClass4NegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test that the parser emits an error when +// two 'is' expressions follow each other. + +class A { + const A(); +} + +class IsNotClass4NegativeTest { + static testMain() { + var a = new A(); + + if (a is A is A) { + return 0; + } + return 0; + } +} + +main() { + IsNotClass4NegativeTest.testMain(); +} diff --git a/tests/language/src/IsOperatorTest.dart b/tests/language/src/IsOperatorTest.dart new file mode 100644 index 00000000000..feb6a81992f --- /dev/null +++ b/tests/language/src/IsOperatorTest.dart @@ -0,0 +1,83 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for the "is" type test operator. + +interface I { } + +interface AI extends I { } + +class A implements AI { + const A(); +} + +class B implements I { + const B(); +} + +class C extends A { + const C() : super(); +} + +class IsOperatorTest { + static testMain() { + var a = new A(); + var b = new B(); + var c = new C(); + var n = null; + Expect.equals(true, a is A); + Expect.equals(false, a is !A); + Expect.equals(true, b is B); + Expect.equals(false, b is !B); + Expect.equals(true, c is C); + Expect.equals(false, c is !C); + Expect.equals(true, c is A); + Expect.equals(false, c is !A); + + Expect.equals(true, a is AI); + Expect.equals(false, a is !AI); + Expect.equals(true, a is I); + Expect.equals(false, a is !I); + Expect.equals(false, b is AI); + Expect.equals(true, b is !AI); + Expect.equals(true, b is I); + Expect.equals(false, b is !I); + Expect.equals(true, c is AI); + Expect.equals(false, c is !AI); + Expect.equals(true, c is I); + Expect.equals(false, c is !I); + Expect.equals(false, n is AI); + Expect.equals(true, n is !AI); + Expect.equals(false, n is I); + Expect.equals(true, n is !I); + + Expect.equals(false, a is B); + Expect.equals(true, a is !B); + Expect.equals(false, a is C); + Expect.equals(true, a is !C); + Expect.equals(false, b is A); + Expect.equals(true, b is !A); + Expect.equals(false, b is C); + Expect.equals(true, b is !C); + Expect.equals(false, c is B); + Expect.equals(true, c is !B); + Expect.equals(false, n is A); + Expect.equals(true, n is !A); + + Expect.equals(false, null is A); + Expect.equals(false, null is B); + Expect.equals(false, null is C); + Expect.equals(false, null is AI); + Expect.equals(false, null is I); + + Expect.equals(true, null is !A); + Expect.equals(true, null is !B); + Expect.equals(true, null is !C); + Expect.equals(true, null is !AI); + Expect.equals(true, null is !I); + } +} + +main() { + IsOperatorTest.testMain(); +} diff --git a/tests/language/src/Issue4157508Test.dart b/tests/language/src/Issue4157508Test.dart new file mode 100644 index 00000000000..d9990efe4dc --- /dev/null +++ b/tests/language/src/Issue4157508Test.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class Issue4157508Test { + Issue4157508Test(var v) { + var d = new DateTime.fromEpoch(v, const TimeZone.utc()); + } + + static void testMain() { + var d = new Issue4157508Test(0); + } +} + +main() { + Issue4157508Test.testMain(); +} diff --git a/tests/language/src/Issue4295001Test.dart b/tests/language/src/Issue4295001Test.dart new file mode 100644 index 00000000000..0fa8b563c8f --- /dev/null +++ b/tests/language/src/Issue4295001Test.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class Issue4295001Test { + String foo; + Issue4295001Test(String s) : this.foo = s { + var f = () => s; + } + + static void testMain() { + var d = new Issue4295001Test("Hello"); + } +} + +main() { + Issue4295001Test.testMain(); +} diff --git a/tests/language/src/Issue4515170Test.dart b/tests/language/src/Issue4515170Test.dart new file mode 100644 index 00000000000..8434ca77961 --- /dev/null +++ b/tests/language/src/Issue4515170Test.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class Issue4515170Test { + static final VAL = 3; + static int defaultVal([int a = VAL]) { + return a; + } + + static testMain() { + defaultVal(); + } +} + +main() { + Issue4515170Test.testMain(); +} diff --git a/tests/language/src/Label2NegativeTest.dart b/tests/language/src/Label2NegativeTest.dart new file mode 100644 index 00000000000..ab9d2565ed6 --- /dev/null +++ b/tests/language/src/Label2NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test check that we catch label errors. + + +class Label2NegativeTest { + static testMain() { + if (true) { + break; // Illegal: not embedded in a loop. + } + } +} + + +main() { + Label2NegativeTest.testMain(); +} diff --git a/tests/language/src/Label3NegativeTest.dart b/tests/language/src/Label3NegativeTest.dart new file mode 100644 index 00000000000..56482ee61a2 --- /dev/null +++ b/tests/language/src/Label3NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test check that we catch label errors. + + +class Label3NegativeTest { + static testMain() { + L: while (false) { + if (true) break L; // Ok + } + continue L; // Illegal: L is out of scope. + } +} + + +main() { + Label3NegativeTest.testMain(); +} diff --git a/tests/language/src/Label5NegativeTest.dart b/tests/language/src/Label5NegativeTest.dart new file mode 100644 index 00000000000..d1a9e0c7c57 --- /dev/null +++ b/tests/language/src/Label5NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test check that we catch label errors. + + +class Label5NegativeTest { + static testMain() { + var L = 33; + while (false) { + if (true) break L; // Illegal: L is not a label. + } + } +} + + +main() { + Label5NegativeTest.testMain(); +} diff --git a/tests/language/src/Label6NegativeTest.dart b/tests/language/src/Label6NegativeTest.dart new file mode 100644 index 00000000000..661497cd2e0 --- /dev/null +++ b/tests/language/src/Label6NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test check that we catch label errors. + + +class Label6NegativeTest { + static testMain() { + L: while (false) { + break; // ok; + break L; // ok + void innerfunc() { + if (true) break L; // Illegal: jump target is outside of function + } + innerfunc(); + } + } +} + + +main() { + Label6NegativeTest.testMain(); +} diff --git a/tests/language/src/Label8NegativeTest.dart b/tests/language/src/Label8NegativeTest.dart new file mode 100644 index 00000000000..ff35321450b --- /dev/null +++ b/tests/language/src/Label8NegativeTest.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Labels aren't allowed in front of { for switch stmt + + +class Label8NegativeTest { + static errorMethod() { + int i; + // grammar doesn't currently allow label on block for switch stmt. + switch(i) L: { + case 111: + while (doAgain()) { + break L; + } + i++; + } + } + static testMain() { + Label8NegativeTest.errorMethod(); + } +} + + +main() { + Label8NegativeTest.testMain(); +} diff --git a/tests/language/src/LabelTest.dart b/tests/language/src/LabelTest.dart new file mode 100644 index 00000000000..e9affb2cbc3 --- /dev/null +++ b/tests/language/src/LabelTest.dart @@ -0,0 +1,316 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to test check that we can parse labels. + + +class Helper { + + static int ticks; + + // Helper function to prevent endless loops in case labels or + // break/continue is broken. + static doAgain() { + ++ticks; + if (ticks > 300) { + // obfuscating man's assert(false) + Expect.equals(true, false); + } + return true; + } + + static test1() { + var i = 1; + while (doAgain()) { + if (i > 0) break; + return 0; + } + return 111; + } + + static test2() { + // Make sure we break out to default label. + var i = 1; + L: while (doAgain()) { // unused label + if (i > 0) break; + return 0; + } + return 111; + } + + static test3() { + // Make sure we break out of outer loop. + var i = 1; + L: while (doAgain()) { + while (doAgain()) { + if (i > 0) break L; + return 0; + } + return 1; + } + return 111; + } + + static test4() { + // Make sure we break out of inner loop. + var i = 100; + L: while (doAgain()) { // unused label + while (doAgain()) { + if (i > 0) break; + return 0; + } + return 111; + } + return 1; + } + + static test5() { + // Make sure we jump to loop condition. + var i = 10; + while (i > 0) { + i--; + if (true) continue; // without the if the following return is dead code. + return 0; + } + return 111; + } + + static test6() { + // Make sure we jump to loop condition. + L: for (int i = 10; i > 0; i--) { // unreferenced label, should warn + if (true) continue; // without the if the following return is dead code. + return 0; + } + // Make sure this L does not conflict with previous L. + var k = 20; + L: while (doAgain()) { + L0: while (doAgain()) break L; // unreferenced label L0, should warn + return 1; + } + return 111; + } + + static test7() { + // Just weird stuff. + var i = 10; + L: do { + L: while (doAgain()) { + if (true) break L; // without the if the following line is dead code. + continue L; + } + i = 0; + continue L; + } while (i == 10 && doAgain()); + return 111; + } + + static test8() { + L: while (false) { + var L = 33; // OK, shouldn't collide with label. + if (true) break L; + } + return 111; + } + + static test9() { + var i = 111; + L1: if (i == 0) { // unreferenced label, should warn + return 0; + } + + L2: while (i == 0) { // unreferenced label, should warn + return 0; + } + + L3: // useless label, should warn + return i; + } + + // Labels should be allowed on block/if/for/switch/while/do stmts. + static test10() { + int i = 111; + // block + while (doAgain()) { + L: { + while (doAgain()) { + break L; + } + i--; + } + break; + } + Expect.equals(111, i); + + while(doAgain()) { + L: if (doAgain()) { + while(doAgain()) { + break L; + } + i--; + } + break; + } + Expect.equals(111, i); + + while(doAgain()) { + L: for (;doAgain();) { + while (doAgain()) { + break L; + } + i--; + } + break; + } + Expect.equals(111, i); + + L: for (i in [111]) { + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + + L: for (var j in [111]) { + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + + while(doAgain()) { + L: switch (i) { + case 111: + while(doAgain()) { + break L; + } + default: + i--; + } + break; + } + Expect.equals(111, i); + + while(doAgain()) { + L: do { + while(doAgain()) { + break L; + } + i--; + } while (doAgain()); + break; + } + Expect.equals(111, i); + + while(doAgain()) { + L: try { + while(doAgain()) { + break L; + } + i--; + } finally { + } + break; + } + Expect.equals(111, i); + + return i; + } + + static test11() { + // Kind of odd, but is valid and shouldn't be flagged as useless either. + L: break L; + return 111; + } + + static test12() { + int i = 111; + + // label the inner block on compound stmts + if (true) L: { + while (doAgain()) { + break L; + } + i--; + } + Expect.equals(111, i); + + // loop will execute each time, but won't execute code below the break + var forCount = 0; + for (forCount = 0 ; forCount < 2 ; forCount++) L: { + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + Expect.equals(forCount, 2); + + for (i in [111]) L: { + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + + for (var j in [111]) L: { + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + + if (false) { + } else L: { + while (doAgain()) { + break L; + } + i--; + } + Expect.equals(111, i); + + int whileCount = 0; + while (whileCount < 2) L: { + whileCount++; + while(doAgain()) { + break L; + } + i--; + break; + } + Expect.equals(111, i); + Expect.equals(2, whileCount); + + return i; + } +} + +class LabelTest { + static testMain() { + Helper.ticks = 0; + Expect.equals(111, Helper.test1()); + Expect.equals(111, Helper.test2()); + Expect.equals(111, Helper.test3()); + Expect.equals(111, Helper.test4()); + Expect.equals(111, Helper.test5()); + Expect.equals(111, Helper.test6()); + Expect.equals(111, Helper.test7()); + Expect.equals(111, Helper.test8()); + Expect.equals(111, Helper.test9()); + Expect.equals(111, Helper.test10()); + Expect.equals(111, Helper.test11()); + Expect.equals(111, Helper.test12()); + } +} + +main() { + LabelTest.testMain(); +} diff --git a/tests/language/src/Library1Lib.dart b/tests/language/src/Library1Lib.dart new file mode 100644 index 00000000000..c605f426396 --- /dev/null +++ b/tests/language/src/Library1Lib.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + A() {} + String foo() { return "foo-rty two"; } +} diff --git a/tests/language/src/Library1Lib.lib b/tests/language/src/Library1Lib.lib new file mode 100644 index 00000000000..5feef14144a --- /dev/null +++ b/tests/language/src/Library1Lib.lib @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("Library1Lib"); + +#source("Library1Lib.dart"); diff --git a/tests/language/src/Library1Test.dart b/tests/language/src/Library1Test.dart new file mode 100644 index 00000000000..49484beb411 --- /dev/null +++ b/tests/language/src/Library1Test.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing libraries. + +#import("Library1Lib.lib"); + +main() { + Library1Test.testMain(); +} + +class Library1Test { + static testMain() { + var a = new A(); + String s = a.foo(); + Expect.equals(s, "foo-rty two"); + } +} diff --git a/tests/language/src/LibraryNegativeTest.dart b/tests/language/src/LibraryNegativeTest.dart new file mode 100644 index 00000000000..0d0676bbf10 --- /dev/null +++ b/tests/language/src/LibraryNegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// This test should fail to load because the app file references a +// library spec file that does not exist. + +#import("NonexistingLibrary.lib"); + + +main(args) { + LibraryNegativeTest.testMain(args); +} + +class LibraryNegativeTest { + static testMain() { + print("Er, hello world? This should not be printed!"); + } +} + +main() { + LibraryNegativeTest.testMain(); +} diff --git a/tests/language/src/LibraryPrefixes.dart b/tests/language/src/LibraryPrefixes.dart new file mode 100644 index 00000000000..d44e374eca0 --- /dev/null +++ b/tests/language/src/LibraryPrefixes.dart @@ -0,0 +1,70 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class LibraryPrefixes { + + static void main(var expectEquals) { + var a = Constants.PI; + var b = other.Constants.PI; + expectEquals(3.14, a); + expectEquals(3.14, b); + + expectEquals(1, Constants.foo); + expectEquals(2, other.Constants.foo); + + expectEquals(-1, A.y); + expectEquals(0, other.A.y); + + expectEquals(1, new A().x); + expectEquals(2, new other.A().x); + + expectEquals(3, new A.named().x); + expectEquals(4, new other.A.named().x); + + expectEquals(3, new A.fac().x); + expectEquals(4, new other.A.fac().x); + + expectEquals(1, new B().x); + expectEquals(2, new other.B().x); + + expectEquals(8, new B.named().x); + expectEquals(13, new other.B.named().x); + + expectEquals(8, new B.fac().x); + expectEquals(13, new other.B.fac().x); + + expectEquals(1, const C().x); + expectEquals(2, const other.C().x); + + expectEquals(3, const C.named().x); + expectEquals(4, const other.C.named().x); + + expectEquals(3, new C.fac().x); + expectEquals(4, new other.C.fac().x); + + expectEquals(1, const D().x); + expectEquals(2, const other.D().x); + + expectEquals(8, const D.named().x); + expectEquals(13, const other.D.named().x); + + expectEquals(8, new D.fac().x); + expectEquals(13, new other.D.fac().x); + + expectEquals(0, E.foo()); + expectEquals(3, other.E.foo()); + + expectEquals(1, new E().bar()); + expectEquals(4, new other.E().bar()); + + expectEquals(9, new E().toto(7)()); + expectEquals(16, new other.E().toto(11)()); + + expectEquals(111, (new E.fun(100).f)()); + expectEquals(1313, (new other.E.fun(1300).f)()); + + expectEquals(999, E.fooo(900)()); + expectEquals(2048, other.E.fooo(1024)()); + } +} diff --git a/tests/language/src/LibraryPrefixes.lib b/tests/language/src/LibraryPrefixes.lib new file mode 100644 index 00000000000..dabb3b50549 --- /dev/null +++ b/tests/language/src/LibraryPrefixes.lib @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("LibraryPrefixes.lib"); + +#import("LibraryPrefixesTest1.lib"); +#import("LibraryPrefixesTest2.lib", prefix:"other"); +#source("LibraryPrefixes.dart"); diff --git a/tests/language/src/LibraryPrefixesTest.dart b/tests/language/src/LibraryPrefixesTest.dart new file mode 100644 index 00000000000..51e1dcb0e3d --- /dev/null +++ b/tests/language/src/LibraryPrefixesTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + + +#import("LibraryPrefixes.lib"); +class LibraryPrefixesTest { + static testMain() { + LibraryPrefixes.main((a, b) { Expect.equals(a, b); }); + } +} + +main() { + LibraryPrefixesTest.testMain(); +} diff --git a/tests/language/src/LibraryPrefixesTest1.dart b/tests/language/src/LibraryPrefixesTest1.dart new file mode 100644 index 00000000000..1231e97513b --- /dev/null +++ b/tests/language/src/LibraryPrefixesTest1.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class Constants { + static final PI = 3.14; + static final foo = 1; +} + +class A { + static final y = -1; + int x; + A() : x = 1 {} + A.named() : x = 3 {} + A.superC(x) : x = x + 7 {} + factory A.fac() { return new A.named(); } +} + +class B extends A { + B() : super() {} + B.named() : super.superC(1) {} + factory B.fac() { return new B.named(); } +} + +class C { + final int x; + const C() : x = 1; + const C.named() : x = 3; + const C.superC(x) : x = x + 7; + factory C.fac() { return const C.named(); } +} + +class D extends C { + const D() : super(); + const D.named() : super.superC(1); + factory D.fac() { return const D.named(); } +} + +class E { + var f; + E() {} + E.fun(x) : f = (() { return x + 11; }) {} + static foo() { return 0; } + static fooo(x) { return () { return x + 99; }; } + bar() { return 1; } + toto(x) { return () { return x + 2; }; } +} diff --git a/tests/language/src/LibraryPrefixesTest1.lib b/tests/language/src/LibraryPrefixesTest1.lib new file mode 100644 index 00000000000..4803feea02d --- /dev/null +++ b/tests/language/src/LibraryPrefixesTest1.lib @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("LibraryPrefixesTest1.lib"); + +#source("LibraryPrefixesTest1.dart"); diff --git a/tests/language/src/LibraryPrefixesTest2.dart b/tests/language/src/LibraryPrefixesTest2.dart new file mode 100644 index 00000000000..5c2d3128dae --- /dev/null +++ b/tests/language/src/LibraryPrefixesTest2.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class Constants { + static final PI = 3.14; + static final foo = 2; +} + +class A { + static final y = 0; + int x; + A() : x = 2 {} + A.named() : x = 4 {} + A.superC(x) : x = x + 11 {} + factory A.fac() { return new A.named(); } +} + +class B extends A { + B() : super() {} + B.named() : super.superC(2) {} + factory B.fac() { return new B.named(); } +} + +class C { + final int x; + const C() : x = 2; + const C.named() : x = 4; + const C.superC(x) : x = x + 11; + factory C.fac() { return const C.named(); } +} + +class D extends C { + const D() : super(); + const D.named() : super.superC(2); + factory D.fac() { return const D.named(); } +} + +class E { + var f; + E() {} + E.fun(x) : f = (() { return x + 13; }) {} + static foo() { return 3; } + static fooo(x) { return () { return x + 1024; }; } + bar() { return 4; } + toto(x) { return () { return x + 5; }; } +} diff --git a/tests/language/src/LibraryPrefixesTest2.lib b/tests/language/src/LibraryPrefixesTest2.lib new file mode 100644 index 00000000000..8eb37b62e3b --- /dev/null +++ b/tests/language/src/LibraryPrefixesTest2.lib @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("LibraryPrefixesTest2.lib"); + +#source("LibraryPrefixesTest2.dart"); + diff --git a/tests/language/src/ListLiteral2Test.dart b/tests/language/src/ListLiteral2Test.dart new file mode 100644 index 00000000000..d9d0d00b078 --- /dev/null +++ b/tests/language/src/ListLiteral2Test.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test program for array literals. + +class ArrayLiteral2Test { + static final int LAUREL = 1965; + static final int HARDY = 1957; + + static final LUCKY_DOG = const [ 1919, 1921 ]; + static final MUSIC_BOX = const [ LAUREL, HARDY ]; + + static testMain() { + Expect.equals(2, LUCKY_DOG.length); + Expect.equals(2, MUSIC_BOX.length); + + Expect.equals(1919, LUCKY_DOG[0]); + Expect.equals(1921, LUCKY_DOG[1]); + + Expect.equals(LAUREL, MUSIC_BOX[0]); + Expect.equals(HARDY, MUSIC_BOX[1]); + } +} + +main() { + ArrayLiteral2Test.testMain(); +} diff --git a/tests/language/src/ListLiteral3Test.dart b/tests/language/src/ListLiteral3Test.dart new file mode 100644 index 00000000000..2db30a63e34 --- /dev/null +++ b/tests/language/src/ListLiteral3Test.dart @@ -0,0 +1,65 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that arrays from final array literals are immutable. + +class ListLiteral3Test { + + static final List canonicalJoke = const ["knock", "knock"]; + + static testMain() { + + List joke = const ["knock", "knock"]; + // Elements of canonical lists are canonicalized. + Expect.equals(true, joke === canonicalJoke); + Expect.equals(true, joke[0] === joke[1]); + Expect.equals(true, joke[0] === canonicalJoke[0]); + + // Lists from literals are immutable. + bool caughtException = false; + try { + joke[0] = "sock"; + } catch (UnsupportedOperationException e) { + caughtException = true; + } + Expect.equals(true, joke[0] === joke[1]); + Expect.equals(true, caughtException); + + // Make sure lists allocated at runtime are mutable and are + // not canonicalized. + List lame_joke = ["knock", "knock"]; // Invokes operator new. + Expect.equals(true, joke[1] === lame_joke[1]); + // Operator new creates a mutable list. + Expect.equals(false, joke === lame_joke); + lame_joke[1] = "who"; + Expect.equals(true, "who" === lame_joke[1]); + + // Elements of canonical lists are canonicalized. + List> a = const >[ const [1, 2], const [1, 2]]; + Expect.equals(true, a[0] === a[1]); + Expect.equals(true, a[0][0] === a[1][0]); + try { + caughtException = false; + a[0][0] = 42; + } catch (UnsupportedOperationException e) { + caughtException = true; + } + Expect.equals(true, caughtException); + + List> b = const [ const [1.0, 2.0], const [1.0, 2.0]]; + Expect.equals(true, b[0] === b[1]); + Expect.equals(true, b[0][0] === 1.0); + Expect.equals(true, b[0][0] === b[1][0]); + try { + caughtException = false; + b[0][0] = 42.0; + } catch (UnsupportedOperationException e) { + caughtException = true; + } + Expect.equals(true, caughtException); + } +} + +main() { + ListLiteral3Test.testMain(); +} diff --git a/tests/language/src/ListLiteralNegativeTest.dart b/tests/language/src/ListLiteralNegativeTest.dart new file mode 100644 index 00000000000..4c9ad6d9961 --- /dev/null +++ b/tests/language/src/ListLiteralNegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Legacy compound literal syntax that should go away. + +class ListLiteralNegativeTest { + + static testMain() { + var funny = new List[1, 2]; + } +} + +main() { + ListLiteralNegativeTest.testMain(); +} diff --git a/tests/language/src/ListLiteralTest.dart b/tests/language/src/ListLiteralTest.dart new file mode 100644 index 00000000000..7bb523e09fb --- /dev/null +++ b/tests/language/src/ListLiteralTest.dart @@ -0,0 +1,45 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test program for array literals. + +class ListLiteralTest { + + static final LAUREL = 1; + static final HARDY = 2; + + static testMain() { + + var funny = [LAUREL, HARDY, ]; // Check that trailing comma works. + Expect.equals(2, funny.length); + + List m = [101, 102, 100 + 3]; + Expect.equals(3, m.length); + Expect.equals(101, m[0]); + Expect.equals(103, m[2]); + + var d = m[2] - m[1]; + Expect.equals(1, d); + + var e2 = [5.1, -55, 555, 5555][2]; + Expect.equals(555, e2); + + e2 = [5.1, -55, 555, 5555][2]; + Expect.equals(555, e2); + + e2 = const [5.1, -55, 555, 5555][2]; + Expect.equals(555, e2); + + e2 = const [5.1, const [-55, 555], 5555][1][1]; + Expect.equals(555, e2); + + Expect.equals(0, [].length); + Expect.equals(0, [].length); + Expect.equals(0, const [].length); + Expect.equals(0, const [].length); + } +} + +main() { + ListLiteralTest.testMain(); +} diff --git a/tests/language/src/ListTest.dart b/tests/language/src/ListTest.dart new file mode 100644 index 00000000000..9a8023a0507 --- /dev/null +++ b/tests/language/src/ListTest.dart @@ -0,0 +1,145 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing arrays. + +class ListTest { + static void TestIterator() { + List a = new List(10); + int count = 0; + + // Basic iteration over ObjectList. + for (int elem in a) { + Expect.equals(null, elem); + count++; + } + Expect.equals(10, count); + + // List length is 0. + List fa = new List(); + count = 0; + for (int elem in fa) { + count++; + } + Expect.equals(0, count); + + // Iterate over ImmutableList. + List ca = const [0, 1, 2, 3, 4, 5]; + int sum = 0; + for (int elem in ca) { + sum += elem; + fa.add(elem); + } + Expect.equals(15, sum); + + // Iterate over List. + int sum2 = 0; + for (int elem in fa) { + sum2 += elem; + } + Expect.equals(sum, sum2); + } + + static void testMain() { + int len = 10; + List a = new List(len); + Expect.equals(true, a is List); + Expect.equals(len, a.length); + a.forEach(f(element) { Expect.equals(null, element); }); + a[1] = 1; + Expect.equals(1, a[1]); + bool exception_caught = false; + try { + var x = a[len]; + } catch (IndexOutOfRangeException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + + exception_caught = false; + try { + List a = new List(4); + a.copyFrom(a, null, 1, 1); + } catch (IllegalArgumentException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + + exception_caught = false; + try { + List a = new List(4); + a.copyFrom(a, 10, 1, 1); + } catch (IndexOutOfRangeException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + + exception_caught = false; + try { + List a = new List(4); + List b = new List(4); + b.copyFrom(a, 0, 0, 4); + } catch (var e) { + exception_caught = true; + } + Expect.equals(false, exception_caught); + + List unsorted = [4, 3, 9, 12, -4, 9]; + int compare(a, b) { + if (a < b) return -1; + if (a > b) return 1; + return 0; + } + unsorted.sort(compare); + Expect.equals(6, unsorted.length); + Expect.equals(-4, unsorted[0]); + Expect.equals(12, unsorted[unsorted.length - 1]); + int compare2(a, b) { + if (a < b) return 1; + if (a > b) return -1; + return 0; + } + unsorted.sort(compare2); + Expect.equals(12, unsorted[0]); + Expect.equals(-4, unsorted[unsorted.length - 1]); + Set t = new Set.from(unsorted); + Expect.equals(true, t.contains(9)); + Expect.equals(true, t.contains(-4)); + Expect.equals(false, t.contains(-3)); + Expect.equals(6, unsorted.length); + Expect.equals(5, t.length); + TestIterator(); + int element = unsorted[2]; + Expect.equals(9, element); + bool exceptionCaught = false; + try { + element = unsorted[2.1]; + } catch (IllegalArgumentException e) { + exceptionCaught = true; + } catch (TypeError e) { + // For type checked mode. + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + + exceptionCaught = false; + try { + var a = new List(-1); + } catch (Exception e) { // Must agree which exception to throw. + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + + exceptionCaught = false; + try { + var a = new List(99999999999999999999999); // Non-Smi. + } catch (Exception e) { // Must agree which exception to throw. + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + } +} + +main() { + ListTest.testMain(); +} diff --git a/tests/language/src/LocalFunction2Test.dart b/tests/language/src/LocalFunction2Test.dart new file mode 100644 index 00000000000..8f584a8bcb9 --- /dev/null +++ b/tests/language/src/LocalFunction2Test.dart @@ -0,0 +1,38 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing closures. + +typedef T F(T t); + +class Parameterized { + Parameterized() { } + T mul3(F f, T t) { return 3*f(t); } + T test(T t) { + return mul3(T _(T t) { return 3*t; }, t); + } +} + +class LocalFunction2Test { + static int f(int n) { + int a = 0; + var g = (int n) { + a += n; + return a; + }; + var h = (int n) { + a += 10*n; + return a; + }; + return g(n) + h(n); + } + + static testMain() { + Expect.equals(3 + 33, f(3)); + Expect.equals(9.0, new Parameterized().test(1.0)); + } +} + +main() { + LocalFunction2Test.testMain(); +} diff --git a/tests/language/src/LocalFunction3Test.dart b/tests/language/src/LocalFunction3Test.dart new file mode 100644 index 00000000000..7c7bb9546d7 --- /dev/null +++ b/tests/language/src/LocalFunction3Test.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing closures. + +class LocalFunction3Test { + static testExceptions() { + var f = (int n) { return n + 1; }; + Expect.equals(true, f is Object); + bool exception_caught = false; + try { + f.xyz(0); + } catch (NoSuchMethodException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + exception_caught = false; + String f_string; + try { + f_string = f.toString(); + } catch (NoSuchMethodException e) { + exception_caught = true; + } + Expect.equals(false, exception_caught); + Expect.equals("Closure", f_string); + } + + static testMain() { + testExceptions(); + } +} + +main() { + LocalFunction3Test.testMain(); +} + diff --git a/tests/language/src/LocalFunctionTest.dart b/tests/language/src/LocalFunctionTest.dart new file mode 100644 index 00000000000..57c3168fca3 --- /dev/null +++ b/tests/language/src/LocalFunctionTest.dart @@ -0,0 +1,183 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing closures. + +class LocalFunctionTest { + LocalFunctionTest() : field1 = 100, field2_ = 200 { } + static int f(int n) { + int a = 0; + g(int m) { + a = 3*n + m + 1; // Capture parameter n and local a. + return a; + } + var b = g(n); + return a + b; + } + static int h(int n) { + k(int n) { + var a = new List(n); + var b = new List(n); + for (int i = 0; i < n; i++) { + var j = i; + a[i] = () => i; // Captured i is always n. + b[i] = () => j; // Captured j varies from 0 to n-1. + } + var a_sum = 0; + var b_sum = 0; + for (int i = 0; i < n; i++) { + a_sum += a[i](); + b_sum += b[i](); + } + return a_sum + b_sum; + } + return k(n); + } + int field1; + int field2_; + int get field2() { return field2_; } + void set field2(int value) { field2_ = value; } + + int method(int n) { + incField1() { field1++; } + incField2() { field2++; } + for (int i = 0; i < n; i++) { + incField1(); + incField2(); + } + return field1 + field2; + } + int execute(int times, apply(int x)) { + for (int i = 0; i < times; i++) { + apply(i); + } + return field1; + } + int testExecute(int n) { + execute(n, (int x) { field1 += x; }); + return field1; + } + static int foo(int n) { + return -100; // Wrong foo. + } + static testSelfReference1(int n) { + int foo(int n) { + if (n == 0) { + return 0; + } else { + return 1 + foo(n - 1); // Local foo, not static foo. + } + }; + return foo(n); // Local foo, not static foo. + } + static void hep(Function f) { + f(); + } + static testSelfReference3(int n) { + int i = 0; + var yup; // Not in same scope as yup below. + hep(yup() { + if (++i < n) hep(yup); + }); + return i; + } + static testNesting(int n) { + var a = new List(n*n); + f0() { + for (int i = 0; i < n; i++) { + int vi = i; + f1() { + for (int j = 0; j < n; j++) { + int vj = j; + a[i*n + j] = () => vi*n + vj; + } + } + f1(); + } + } + f0(); + int result = 0; + for (int k = 0; k < n*n; k++) { + Expect.equals(k, a[k]()); + result += a[k](); + } + return result; + } + + static var field5; + static var set_field5_func; + static testClosureCallStatement(int x) { + LocalFunctionTest.set_field5_func = (int n) { field5 = n * n; }; + (LocalFunctionTest.set_field5_func)(x); + Expect.equals(x * x, LocalFunctionTest.field5); + return true; + } + + static testExceptions() { + var f = (int n) => n + 1; + Expect.equals(2, f(1)); + Expect.equals(true, f is Function); + Expect.equals(true, f is Object); + Expect.equals("Closure", f.toString()); + bool exception_caught = false; + try { + f(1, 2); + } catch (ClosureArgumentMismatchException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + exception_caught = false; + try { + f(); + } catch (ClosureArgumentMismatchException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + exception_caught = false; + try { + f.xyz(0); + } catch (NoSuchMethodException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + + // Overwrite closure value. + f = 3; + exception_caught = false; + try { + f(1); + } catch (ObjectNotClosureException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + + // Do not expect any exceptions to be thrown. + var g = ([int n = 1]) => n + 1; + Expect.equals(2, g()); + Expect.equals(3, g(2)); + } + + static int doThis(int n, int f(int n)) { + return f(n); + } + + static testMain() { + Expect.equals(2*(3*2 + 2 + 1), f(2)); + Expect.equals(10*10 + 10*9/2, h(10)); + Expect.equals(320, new LocalFunctionTest().method(10)); + Expect.equals(145, new LocalFunctionTest().testExecute(10)); + Expect.equals(5, testSelfReference1(5)); + Expect.equals(5, testSelfReference3(5)); + Expect.equals(24*25/2, testNesting(5)); + Expect.equals(true, testClosureCallStatement(7)); + Expect.equals(99, doThis(10, int _(n) => n * n - 1)); + Expect.equals(99, doThis(10, int f(n) => n * n - 1)); + Expect.equals(99, doThis(10, (n) => n * n - 1)); + Expect.equals(99, doThis(10, f(n) => n * n - 1)); + testExceptions(); + } +} + +main() { + LocalFunctionTest.testMain(); +} diff --git a/tests/language/src/ManyCallsTest.dart b/tests/language/src/ManyCallsTest.dart new file mode 100644 index 00000000000..c59b90ff54f --- /dev/null +++ b/tests/language/src/ManyCallsTest.dart @@ -0,0 +1,110 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test megamorphic calls. + +class A { + A() {} + f1() { return 1; } + f2() { return 2; } + f3() { return 3; } + f4() { return 4; } + f5() { return 5; } + f6() { return 6; } + f7() { return 7; } + f8() { return 8; } + f9() { return 9; } + f11() { return 11; } + f12() { return 12; } + f13() { return 13; } + f14() { return 14; } + f15() { return 15; } + f16() { return 16; } + f17() { return 17; } + f18() { return 18; } + f19() { return 19; } + f20() { return 20; } + f21() { return 21; } + f22() { return 22; } + f23() { return 23; } + f24() { return 24; } + f25() { return 25; } + f26() { return 26; } + f27() { return 27; } + f28() { return 28; } + f29() { return 29; } + f30() { return 30; } + f31() { return 31; } + f32() { return 32; } + f33() { return 33; } + f34() { return 34; } + f35() { return 35; } + f36() { return 36; } + f37() { return 37; } + f38() { return 38; } + f39() { return 39; } +} + + +class B extends A { + B() : super() {} +} + + +class ManyCallsTest { + static testMain() { + var list = new List(10); + for (int i = 0; i < (list.length ~/ 2) ; i++) { + list[i] = new A(); + } + for (int i = (list.length ~/ 2); i < list.length; i++) { + list[i] = new B(); + } + for (int loop = 0; loop < 7; loop++) { + for (int i = 0; i < list.length; i++) { + Expect.equals(1, list[i].f1()); + Expect.equals(2, list[i].f2()); + Expect.equals(3, list[i].f3()); + Expect.equals(4, list[i].f4()); + Expect.equals(5, list[i].f5()); + Expect.equals(6, list[i].f6()); + Expect.equals(7, list[i].f7()); + Expect.equals(8, list[i].f8()); + Expect.equals(9, list[i].f9()); + Expect.equals(11, list[i].f11()); + Expect.equals(12, list[i].f12()); + Expect.equals(13, list[i].f13()); + Expect.equals(14, list[i].f14()); + Expect.equals(15, list[i].f15()); + Expect.equals(16, list[i].f16()); + Expect.equals(17, list[i].f17()); + Expect.equals(18, list[i].f18()); + Expect.equals(19, list[i].f19()); + Expect.equals(20, list[i].f20()); + Expect.equals(21, list[i].f21()); + Expect.equals(22, list[i].f22()); + Expect.equals(23, list[i].f23()); + Expect.equals(24, list[i].f24()); + Expect.equals(25, list[i].f25()); + Expect.equals(26, list[i].f26()); + Expect.equals(27, list[i].f27()); + Expect.equals(28, list[i].f28()); + Expect.equals(29, list[i].f29()); + Expect.equals(30, list[i].f30()); + Expect.equals(31, list[i].f31()); + Expect.equals(32, list[i].f32()); + Expect.equals(33, list[i].f33()); + Expect.equals(34, list[i].f34()); + Expect.equals(35, list[i].f35()); + Expect.equals(36, list[i].f36()); + Expect.equals(37, list[i].f37()); + Expect.equals(38, list[i].f38()); + Expect.equals(39, list[i].f39()); + } + } + } +} + +main() { + ManyCallsTest.testMain(); +} diff --git a/tests/language/src/ManyGenericInstanceofTest.dart b/tests/language/src/ManyGenericInstanceofTest.dart new file mode 100644 index 00000000000..aa23075b359 --- /dev/null +++ b/tests/language/src/ManyGenericInstanceofTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source("GenericInstanceof.dart"); + +class ManyGenericInstanceofTest { + static testMain() { + for (int i = 0; i < 5000; i++) { + GenericInstanceof.testMain(); + } + } +} + +main() { + ManyGenericInstanceofTest.testMain(); +} diff --git a/tests/language/src/ManyOverriddenNoSuchMethodTest.dart b/tests/language/src/ManyOverriddenNoSuchMethodTest.dart new file mode 100644 index 00000000000..e63ca7a37d7 --- /dev/null +++ b/tests/language/src/ManyOverriddenNoSuchMethodTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source("OverriddenNoSuchMethod.dart"); + +class ManyOverriddenNoSuchMethodTest { + static testMain() { + for (int i = 0; i < 5000; i++) { + OverriddenNoSuchMethod.testMain(); + } + } +} + +main() { + ManyOverriddenNoSuchMethodTest.testMain(); +} diff --git a/tests/language/src/MapLiteral2Test.dart b/tests/language/src/MapLiteral2Test.dart new file mode 100644 index 00000000000..0aa30c0a84e --- /dev/null +++ b/tests/language/src/MapLiteral2Test.dart @@ -0,0 +1,38 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test program for map literals. + +final AA = 1; +final BB = 2; + +int nextValCtr; + +get nextVal() { + return nextValCtr++; +} + +class MapLiteral2Test { + static testMain() { + // Map literals with string interpolation in keys. + var map = const { "a$AA": 88, "b$BB": 99 }; + Expect.equals(2, map.length); + Expect.equals("a1", "a$AA"); + Expect.equals(88, map["a1"]); + Expect.equals("b2", "b$BB"); + Expect.equals(99, map["b2"]); + + nextValCtr = 0; + map = {"a$nextVal": "Grey", "a$nextVal": "Poupon" }; + Expect.equals(true, map.containsKey("a0")); + Expect.equals(true, map.containsKey("a1")); + Expect.equals("Grey", map["a0"]); + Expect.equals("Poupon", map["a1"]); + } +} + + + +main() { + MapLiteral2Test.testMain(); +} diff --git a/tests/language/src/MapLiteral3Test.dart b/tests/language/src/MapLiteral3Test.dart new file mode 100644 index 00000000000..1139f51c330 --- /dev/null +++ b/tests/language/src/MapLiteral3Test.dart @@ -0,0 +1,103 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test program for map literals. + +class MapLiteralTest { + + static testMain() { + var map = { "a": 1, "b": 2, "c": 3 }; + + Expect.equals(map.length, 3); + Expect.equals(map["a"], 1); + Expect.equals(map["z"], null); + Expect.equals(map["c"], 3); + + map["foo"] = 42; + Expect.equals(map.length, 4); + Expect.equals(map["foo"], 42); + map["foo"] = 55; + Expect.equals(map.length, 4); + Expect.equals(map["foo"], 55); + + map.remove("foo"); + Expect.equals(map.length, 3); + Expect.equals(map["foo"], null); + + map["foo"] = "bar"; + Expect.equals(map.length, 4); + Expect.equals(map["foo"], "bar"); + + map.clear(); + Expect.equals(map.length, 0); + + var b = 22; + Expect.equals(22, {"a": 11, "b": b, }["b"]); + + // Make map grow. We currently don't have a way to construct + // strings from an integer value, so we can't use a loop here. + var m = new Map(); + Expect.equals(m.length, 0); + m["1"] = 1; + m["2"] = 2; + m["3"] = 3; + m["4"] = 4; + m["5"] = 5; + m["6"] = 6; + m["7"] = 7; + m["8"] = 8; + m["9"] = 9; + m["10"] = 10; + m["11"] = 11; + m["12"] = 12; + m["13"] = 13; + m["14"] = 14; + m["15"] = 15; + m["16"] = 16; + Expect.equals(16, m.length); + m.remove("1"); + m.remove("1"); // Remove element twice. + m.remove("16"); + Expect.equals(14, m.length); + + // Check that last value of duplicate key wins for const maps. + final cmap = const {"a": 10, "b": 100, "a": 1000}; + Expect.equals(2, cmap.length); + Expect.equals(1000, cmap["a"]); + Expect.equals(100, cmap["b"]); + + final cmap2 = const {"a": 10, "a": 100, "a": 1000}; + Expect.equals(1, cmap2.length); + Expect.equals(1000, cmap["a"]); + + // Check that last value of duplicate key wins for mutable maps. + var mmap = {"a": 10, "b": 100, "a": 1000}; + Expect.equals(2, mmap.length); + Expect.equals(1000, mmap["a"]); + Expect.equals(100, mmap["b"]); + + // Check that even if a key gets eliminated (the first "a"), all values + // are still evaluated, including side effects. + int counter = 0; + int ctr() { counter += 10; return counter; } + mmap = {"a": ctr(), "b": ctr(), "a": ctr()}; + Expect.equals(2, mmap.length); + Expect.equals(40, ctr()); + Expect.equals(30, mmap["a"]); + Expect.equals(20, mmap["b"]); + + Expect.equals(10, { "beta": 100, "alpha": 9 + 1 }["alpha"]); + Expect.equals(10, { + "beta": 100, + "alpha": {"gamma": 10} }["alpha"]["gamma"]); + + // Map literals at beginning of statement. + {"pink": 100}; + const {"floyd": 100}; + } +} + + +main() { + MapLiteralTest.testMain(); +} diff --git a/tests/language/src/MapLiteralNegativeTest.dart b/tests/language/src/MapLiteralNegativeTest.dart new file mode 100644 index 00000000000..abc9d1dcec5 --- /dev/null +++ b/tests/language/src/MapLiteralNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Legacy compound literal syntax that should go away. + +class MapLiteralNegativeTest { + static testMain() { + var map = new Map{ "a": 1, "b": 2, "c": 3 }; + } +} + +main() { + MapLiteralNegativeTest.testMain(); +} diff --git a/tests/language/src/MapLiteralTest.dart b/tests/language/src/MapLiteralTest.dart new file mode 100644 index 00000000000..27d7d7b7a69 --- /dev/null +++ b/tests/language/src/MapLiteralTest.dart @@ -0,0 +1,76 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests map literals. + +class MapLiteralTest { + MapLiteralTest() {} + + static testMain() { + var test = new MapLiteralTest(); + test.testStaticInit(); + test.testConstInit(); + } + + testStaticInit() { + var testClass = new StaticInit(); + testClass.test(); + } + + testConstInit() { + var testClass = new ConstInit(); + testClass.test(); + } + + testLocalInit() { + // Test construction of static final map literals + var map1 = {"a":1, "b":2}; + // Test construction of static final map literals, with numbers + var map2 = {"1":1, "2":2}; + + Expect.equals(1, map1["a"]); + Expect.equals(2, map1["b"]); + + Expect.equals(1, map2["1"]); + Expect.equals(2, map2["2"]); + } +} + +class StaticInit { + StaticInit() {} + + // Test construction of static final map literals + static final map1 = const {"a":1, "b":2}; + // Test construction of static final map literals, with numbers + static final map2 = const {"1":1, "2":2}; + + test() { + Expect.equals(1, map1["a"]); + Expect.equals(2, map1["b"]); + + Expect.equals(1, map2["1"]); + Expect.equals(2, map2["2"]); + } +} + +class ConstInit { + + final map1; + final map2; + + ConstInit() : this.map1 = {"a":1, "b":2}, this.map2 = {"1":1, "2":2} { + } + + test() { + Expect.equals(1, map1["a"]); + Expect.equals(2, map1["b"]); + + Expect.equals(1, map2["1"]); + Expect.equals(2, map2["2"]); + } +} + +main() { + MapLiteralTest.testMain(); +} diff --git a/tests/language/src/MapTest.dart b/tests/language/src/MapTest.dart new file mode 100644 index 00000000000..70de2c4b7b0 --- /dev/null +++ b/tests/language/src/MapTest.dart @@ -0,0 +1,221 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// A subtest of the larger MapTest. Will eliminate once the full +// test is running. + +class MapTest { + + static void testDeletedElement(Map map) { + map.clear(); + for (int i = 0; i < 100; i++) { + map[1] = 2; + Expect.equals(1, map.length); + int x = map.remove(1); + Expect.equals(2, x); + Expect.equals(0, map.length); + } + Expect.equals(0, map.length); + for (int i = 0; i < 100; i++) { + map[i] = 2; + Expect.equals(1, map.length); + int x = map.remove(105); + Expect.equals(null, x); + Expect.equals(1, map.length); + x = map.remove(i); + Expect.equals(2, x); + Expect.equals(0, map.length); + } + Expect.equals(0, map.length); + map.remove(105); + } + + static void test(Map map) { + testDeletedElement(map); + testMap(map, 1, 2, 3, 4, 5, 6, 7, 8); + map.clear(); + testMap(map, "value1", "value2", "value3", "value4", "value5", + "value6", "value7", "value8"); + } + + static void testMap(Map map, key1, key2, key3, key4, key5, key6, key7, key8) { + int value1 = 10; + int value2 = 20; + int value3 = 30; + int value4 = 40; + int value5 = 50; + int value6 = 60; + int value7 = 70; + int value8 = 80; + + Expect.equals(0, map.length); + + map[key1] = value1; + Expect.equals(value1, map[key1]); + map[key1] = value2; + Expect.equals(false, map.containsKey(key2)); + Expect.equals(1, map.length); + + map[key1] = value1; + Expect.equals(value1, map[key1]); + // Add enough entries to make sure the table grows. + map[key2] = value2; + Expect.equals(value2, map[key2]); + Expect.equals(2, map.length); + map[key3] = value3; + Expect.equals(value2, map[key2]); + Expect.equals(value3, map[key3]); + map[key4] = value4; + Expect.equals(value3, map[key3]); + Expect.equals(value4, map[key4]); + map[key5] = value5; + Expect.equals(value4, map[key4]); + Expect.equals(value5, map[key5]); + map[key6] = value6; + Expect.equals(value5, map[key5]); + Expect.equals(value6, map[key6]); + map[key7] = value7; + Expect.equals(value6, map[key6]); + Expect.equals(value7, map[key7]); + map[key8] = value8; + Expect.equals(value1, map[key1]); + Expect.equals(value2, map[key2]); + Expect.equals(value3, map[key3]); + Expect.equals(value4, map[key4]); + Expect.equals(value5, map[key5]); + Expect.equals(value6, map[key6]); + Expect.equals(value7, map[key7]); + Expect.equals(value8, map[key8]); + Expect.equals(8, map.length); + + map.remove(key4); + Expect.equals(false, map.containsKey(key4)); + Expect.equals(7, map.length); + + // Test clearing the table. + map.clear(); + Expect.equals(0, map.length); + Expect.equals(false, map.containsKey(key1)); + Expect.equals(false, map.containsKey(key2)); + Expect.equals(false, map.containsKey(key3)); + Expect.equals(false, map.containsKey(key4)); + Expect.equals(false, map.containsKey(key5)); + Expect.equals(false, map.containsKey(key6)); + Expect.equals(false, map.containsKey(key7)); + Expect.equals(false, map.containsKey(key8)); + + // Test adding and removing again. + map[key1] = value1; + Expect.equals(value1, map[key1]); + Expect.equals(1, map.length); + map[key2] = value2; + Expect.equals(value2, map[key2]); + Expect.equals(2, map.length); + map[key3] = value3; + Expect.equals(value3, map[key3]); + map.remove(key3); + Expect.equals(2, map.length); + map[key4] = value4; + Expect.equals(value4, map[key4]); + map.remove(key4); + Expect.equals(2, map.length); + map[key5] = value5; + Expect.equals(value5, map[key5]); + map.remove(key5); + Expect.equals(2, map.length); + map[key6] = value6; + Expect.equals(value6, map[key6]); + map.remove(key6); + Expect.equals(2, map.length); + map[key7] = value7; + Expect.equals(value7, map[key7]); + map.remove(key7); + Expect.equals(2, map.length); + map[key8] = value8; + Expect.equals(value8, map[key8]); + map.remove(key8); + Expect.equals(2, map.length); + + Expect.equals(true, map.containsKey(key1)); + Expect.equals(true, map.containsValue(value1)); + + // Test Map.forEach. + Map other_map = new Map(); + void testForEachMap(key, value) { + other_map[key] = value; + } + map.forEach(testForEachMap); + Expect.equals(true, other_map.containsKey(key1)); + Expect.equals(true, other_map.containsKey(key2)); + Expect.equals(true, other_map.containsValue(value1)); + Expect.equals(true, other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Collection.getKeys. + void testForEachCollection(value) { + other_map[value] = value; + } + Collection keys = map.getKeys(); + keys.forEach(testForEachCollection); + Expect.equals(true, other_map.containsKey(key1)); + Expect.equals(true, other_map.containsKey(key2)); + Expect.equals(true, other_map.containsValue(key1)); + Expect.equals(true, other_map.containsValue(key2)); + Expect.equals(true, !other_map.containsKey(value1)); + Expect.equals(true, !other_map.containsKey(value2)); + Expect.equals(true, !other_map.containsValue(value1)); + Expect.equals(true, !other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Collection.getValues. + Collection values = map.getValues(); + values.forEach(testForEachCollection); + Expect.equals(true, !other_map.containsKey(key1)); + Expect.equals(true, !other_map.containsKey(key2)); + Expect.equals(true, !other_map.containsValue(key1)); + Expect.equals(true, !other_map.containsValue(key2)); + Expect.equals(true, other_map.containsKey(value1)); + Expect.equals(true, other_map.containsKey(value2)); + Expect.equals(true, other_map.containsValue(value1)); + Expect.equals(true, other_map.containsValue(value2)); + Expect.equals(2, other_map.length); + other_map.clear(); + Expect.equals(0, other_map.length); + + // Test Map.putIfAbsent. + map.clear(); + Expect.equals(false, map.containsKey(key1)); + map.putIfAbsent(key1, () => 10); + Expect.equals(true, map.containsKey(key1)); + Expect.equals(10, map[key1]); + Expect.equals(10, + map.putIfAbsent(key1, () => 11)); + } + + static testKeys(Map map) { + map[1] = 101; + map[2] = 102; + Collection k = map.getKeys(); + Expect.equals(2, k.length); + Collection v = map.getValues(); + Expect.equals(2, v.length); + Expect.equals(true, map.containsValue(101)); + Expect.equals(true, map.containsValue(102)); + Expect.equals(false, map.containsValue(103)); + } + + static testMain() { + test(new Map()); + testKeys(new Map()); + } +} + + +main() { + MapTest.testMain(); +} diff --git a/tests/language/src/MathTest.dart b/tests/language/src/MathTest.dart new file mode 100644 index 00000000000..9747d061166 --- /dev/null +++ b/tests/language/src/MathTest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Tests weird cornercases of class Math. +// An exception is thrown either by the type checker (development mode) or by +// library (default mode). + +class FakeNumber { + const FakeNumber(); + void toDouble() {} +} + +class MathTest { + static bool testParseInt(x) { + try { + Math.parseInt(x); + return true; + } catch (var e) { + print(e); + return false; + } + } + + static bool testSqrt(x) { + try { + Math.sqrt(x); + return true; + } catch (var e) { + print(e); + return false; + } + } + + static void testMain() { + Expect.equals(false, testParseInt(5)); + Expect.equals(false, testSqrt(const FakeNumber())); + } +} +main() { + MathTest.testMain(); +} diff --git a/tests/language/src/MethodBindingTest.dart b/tests/language/src/MethodBindingTest.dart new file mode 100644 index 00000000000..260964d912c --- /dev/null +++ b/tests/language/src/MethodBindingTest.dart @@ -0,0 +1,136 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Bind a method to a variable that can be invoked as a function + +class A { + int a; + + static var func; + + A(this.a) { } + + static foo() { return 4; } + + bar() { return a; } + + int baz() { return a; } + + getThis() { return this.bar; } + + getNoThis() { return bar; } + + methodArgs(arg) { return arg + a; } + + selfReference () { return selfReference; } + + invokeBaz() { return (baz)(); } + + invokeBar(var obj) { return (obj.bar)(); } + + invokeThisBar() { return (this.bar)(); } + + implicitStaticRef() { return foo; } +} + +class B { + static foo() { return -1; } +} + +class C { + C() { } + var f; +} + +topLevel99() { + return 99; +} + +var topFunc; + +class D extends A { + D(a): super(a) { } + getSuper() { return super.bar; } +} + +class MethodBindingTest { + static test() { + + // Create closure from global + Expect.equals(99, topLevel99()); + Function f99 = topLevel99; + Expect.equals(99, f99()); + + // Invoke closure through a global + topFunc = f99; + Expect.equals(99, topFunc()); + + // Create closure from static method + Function f4 = A.foo; + Expect.equals(4, f4()); + + // Create closure from instance method + var o5 = new A(5); + Function f5 = o5.bar; + Expect.equals(5, f5()); + + // Assign closure to field and invoke it + var c = new C(); + c.f = () => "success"; + Expect.equals("success", c.f()); + + // referencing instance method with explicit 'this' qualiier + var o6 = new A(6); + var f6 = o6.getThis(); + Expect.equals(6, f6()); + + // referencing an instance method with no qualifier + var o7 = new A(7); + var f7 = o7.getNoThis(); + Expect.equals(7, f7()); + + // bind a method that takes arguments + var o8 = new A(8); + Function f8 = o8.methodArgs; + Expect.equals(9, f8(1)); + + // Self referential method + var o9 = new A(9); + Function f9 = o9.selfReference; + + // invoking a known method as if it were a bound closure... + var o10 = new A(10); + Expect.equals(10, o10.invokeBaz()); + + // invoking a known method as if it were a bound closure... + var o11 = new A(11); + Expect.equals(10, o11.invokeBar(o10)); + + // invoking a known method as if it were a bound closure... + var o12 = new A(12); + Expect.equals(12, o12.invokeThisBar()); + + // bind to a static variable with no explicit class qualifier + var o13 = new A(13); + Function f13 = o13.implicitStaticRef(); + Expect.equals(4, f13()); + + var o14 = new D(14); + Function f14 = o14.getSuper(); + Expect.equals(14, f14()); + + // Assign static field to a function and invoke it. + A.func = A.foo; + Expect.equals(4, A.func()); + + } + + static testMain() { + test(); + } +} + +main() { + MethodBindingTest.testMain(); +} diff --git a/tests/language/src/MethodInvocationTest.dart b/tests/language/src/MethodInvocationTest.dart new file mode 100644 index 00000000000..3037cb58ee3 --- /dev/null +++ b/tests/language/src/MethodInvocationTest.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Testing method invocation. +// Currently testing only NullPointerException. + +class A { + A() {} + int foo() { + return 1; + } +} + +class MethodInvocationTest { + static void testNullReceiver() { + A a = new A(); + Expect.equals(1, a.foo()); + a = null; + bool exceptionCaught = false; + try { + a.foo(); + } catch (NullPointerException e) { + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + } + + static void testMain() { + testNullReceiver(); + } +} + +main() { + MethodInvocationTest.testMain(); +} diff --git a/tests/language/src/MultiAssignTest.dart b/tests/language/src/MultiAssignTest.dart new file mode 100644 index 00000000000..8dc89332237 --- /dev/null +++ b/tests/language/src/MultiAssignTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing multiple assignment. + + +class MultiAssignTest { + static testMain() { + var i, j, k; + i = j = k = 11; + Expect.equals(11, i); + Expect.equals(11, j); + Expect.equals(11, k); + + var m; + var n = m = k = 55; + Expect.equals(55, m); + Expect.equals(55, n); + Expect.equals(55, k); + } +} + +main() { + MultiAssignTest.testMain(); +} diff --git a/tests/language/src/MultiPass2Test.dart b/tests/language/src/MultiPass2Test.dart new file mode 100644 index 00000000000..765c12be00d --- /dev/null +++ b/tests/language/src/MultiPass2Test.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for loading several dart files and resolving superclasses lazily. +// Same as MultiPassTest, except that the file order is reversed. + +#source("MultiPassA.dart"); +#source("MultiPassB.dart"); + + +class Base { + Base(this.value) { } + var value; +} + +class MultiPass2Test { + static testMain() { + var a = new B(5); + Expect.equals(5, a.value); + } +} + +main() { + MultiPass2Test.testMain(); +} diff --git a/tests/language/src/MultiPassA.dart b/tests/language/src/MultiPassA.dart new file mode 100644 index 00000000000..05f41899fa6 --- /dev/null +++ b/tests/language/src/MultiPassA.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for loading several dart files and resolving superclasses lazily. + + +class A extends Base { + A(v) : super(v) {} +} diff --git a/tests/language/src/MultiPassB.dart b/tests/language/src/MultiPassB.dart new file mode 100644 index 00000000000..802f1c60054 --- /dev/null +++ b/tests/language/src/MultiPassB.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for loading several dart files and resolving superclasses lazily. + +class B extends A { + B(v) : super(v) {} +} diff --git a/tests/language/src/MultiPassTest.dart b/tests/language/src/MultiPassTest.dart new file mode 100644 index 00000000000..cebbdb27d73 --- /dev/null +++ b/tests/language/src/MultiPassTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for loading several dart files and resolving superclasses lazily. + +#source("MultiPassB.dart"); +#source("MultiPassA.dart"); + + +class Base { + Base(this.value) { } + var value; +} + +class MultiPassTest { + static testMain() { + var a = new B(5); + Expect.equals(5, a.value); + } +} + +main() { + MultiPassTest.testMain(); +} diff --git a/tests/language/src/NamedConstructorTest.dart b/tests/language/src/NamedConstructorTest.dart new file mode 100644 index 00000000000..51429d3db3f --- /dev/null +++ b/tests/language/src/NamedConstructorTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NamedConstructorTest { + int x_; + + NamedConstructorTest.fill(int x) { + // Should resolve to the fill method + fill(x); + } + + void fill(int x) { + x_ = x; + } + + static testMain() { + var a = new NamedConstructorTest.fill(3); + assert(a.x_ == 3); + } +} + +main() { + NamedConstructorTest.testMain(); +} diff --git a/tests/language/src/NamedParameters2NegativeTest.dart b/tests/language/src/NamedParameters2NegativeTest.dart new file mode 100644 index 00000000000..6b276a1ef38 --- /dev/null +++ b/tests/language/src/NamedParameters2NegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class NamedParameters2NegativeTest { + + static int F31(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + static testMain() { + try { + F31(10, 25, b:25); // Parameter b passed twice, as positional and named. + } catch (var e) { + // This is a negative test that should not compile. + // If it runs due to a bug, catch and ignore exceptions. + } + } +} + +main() { + NamedParameters2NegativeTest.testMain(); +} diff --git a/tests/language/src/NamedParameters3NegativeTest.dart b/tests/language/src/NamedParameters3NegativeTest.dart new file mode 100644 index 00000000000..53534e756b0 --- /dev/null +++ b/tests/language/src/NamedParameters3NegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class NamedParameters3NegativeTest { + + static int F31(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + static testMain() { + try { + F31(10, 25, x:99); // Parameter x does not exist. + } catch (var e) { + // This is a negative test that should not compile. + // If it runs due to a bug, catch and ignore exceptions. + } + } +} + +main() { + NamedParameters3NegativeTest.testMain(); +} diff --git a/tests/language/src/NamedParameters4NegativeTest.dart b/tests/language/src/NamedParameters4NegativeTest.dart new file mode 100644 index 00000000000..719d754fee2 --- /dev/null +++ b/tests/language/src/NamedParameters4NegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class NamedParameters4NegativeTest { + + static int F31(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + static testMain() { + try { + F31(10, b:25, b:35); // Duplicate named argument. + } catch (var e) { + // This is a negative test that should not compile. + // If it runs due to a bug, catch and ignore exceptions. + } + } +} + +main() { + NamedParameters4NegativeTest.testMain(); +} diff --git a/tests/language/src/NamedParameters5NegativeTest.dart b/tests/language/src/NamedParameters5NegativeTest.dart new file mode 100644 index 00000000000..0ba0a95119b --- /dev/null +++ b/tests/language/src/NamedParameters5NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +interface I { + // Expect a compile-time error below: no default values allowed. + int F31(int a, [int b = 20, int c = 30]); +} + +class C implements I { + int F31(int a, [int b = 20, int c = 30]) { + return 100 * (100 * a + b) + c; + } +} + +main() { + var c = new C(); + var i = c.F31(10, c:35); + Expect.equals(true, false); +} diff --git a/tests/language/src/NamedParameters6NegativeTest.dart b/tests/language/src/NamedParameters6NegativeTest.dart new file mode 100644 index 00000000000..9d53ef6c2d1 --- /dev/null +++ b/tests/language/src/NamedParameters6NegativeTest.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +// Expect a compile-time error below: +// No default values allowed in closure type definitions. +typedef void Callback([String msg = ""]); + +main() { + Expect.equals(true, false); +} diff --git a/tests/language/src/NamedParameters7NegativeTest.dart b/tests/language/src/NamedParameters7NegativeTest.dart new file mode 100644 index 00000000000..c69ccda529a --- /dev/null +++ b/tests/language/src/NamedParameters7NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class C { + // Expect a compile-time error below: + // No default values allowed in abstract method parameter lists. + abstract int F31(int a, [int b = 20, int c = 30]); +} + +main() { + Expect.equals(true, false); +} diff --git a/tests/language/src/NamedParameters8NegativeTest.dart b/tests/language/src/NamedParameters8NegativeTest.dart new file mode 100644 index 00000000000..3cea5fcc0b5 --- /dev/null +++ b/tests/language/src/NamedParameters8NegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class C { + var _handler = null; + + // Expect a compile-time error below: + // No default values allowed in closure type. + void InstallCallback(void cb([String msg = null])) { + _handler = cb; + } +} + + +main() { + Expect.equals(true, false); +} diff --git a/tests/language/src/NamedParametersNegativeTest.dart b/tests/language/src/NamedParametersNegativeTest.dart new file mode 100644 index 00000000000..0773b0236c7 --- /dev/null +++ b/tests/language/src/NamedParametersNegativeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class NamedParametersNegativeTest { + + static int F31(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + static testMain() { + try { + F31(b:25, c:35); // No positional argument passed. + } catch (var e) { + // This is a negative test that should not compile. + // If it runs due to a bug, catch and ignore exceptions. + } + } +} + +main() { + NamedParametersNegativeTest.testMain(); +} diff --git a/tests/language/src/NamedParametersTest.dart b/tests/language/src/NamedParametersTest.dart new file mode 100644 index 00000000000..c6a3f0849c2 --- /dev/null +++ b/tests/language/src/NamedParametersTest.dart @@ -0,0 +1,120 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing named parameters. + + +class NamedParametersTest { + + static int F00() { + return 0; + } + + int f11() { + return 0; + } + + static int F11(int a) { + return a; + } + + int f22(int a) { + return a; + } + + static int F10([int b = 20]) { + return b; + } + + int f21([int b = 20]) { + return b; + } + + static int F21(int a, [int b = 20]) { + return 100*a + b; + } + + int f32(int a, [int b = 20]) { + return 100*a + b; + } + + static int F31(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + int f42(int a, [int b = 20, int c = 30]) { + return 100*(100*a + b) + c; + } + + static int F41(int a, [int b = 20, int c, int d = 40]) { + return 100*(100*(100*a + b) + (c == null ? 0 : c)) + d; + } + + int f52(int a, [int b = 20, int c, int d = 40]) { + return 100*(100*(100*a + b) + (c == null ? 0 : c)) + d; + } + + static testMain() { + NamedParametersTest np = new NamedParametersTest(); + Expect.equals(0, F00()); + Expect.equals(0, np.f11()); + Expect.equals(10, F11(10)); + Expect.equals(10, np.f22(10)); + Expect.equals(20, F10()); + Expect.equals(20, np.f21()); + Expect.equals(20, F10(20)); + Expect.equals(20, np.f21(20)); + Expect.equals(20, F10(b:20)); + Expect.equals(20, np.f21(b:20)); + Expect.equals(1020, F21(10)); + Expect.equals(1020, np.f32(10)); + Expect.equals(1025, F21(10, 25)); + Expect.equals(1025, np.f32(10, 25)); + Expect.equals(1025, F21(10, b:25)); + Expect.equals(1025, np.f32(10, b:25)); + Expect.equals(102030, F31(10)); + Expect.equals(102030, np.f42(10)); + Expect.equals(102530, F31(10, 25)); + Expect.equals(102530, np.f42(10, 25)); + Expect.equals(102530, F31(10, b:25)); + Expect.equals(102530, np.f42(10, b:25)); + Expect.equals(102035, F31(10, c:35)); + Expect.equals(102035, np.f42(10, c:35)); + Expect.equals(102535, F31(10, b:25, c:35)); + Expect.equals(102535, np.f42(10, b:25, c:35)); + Expect.equals(102535, F31(10, 25, c:35)); + Expect.equals(102535, np.f42(10, 25, c:35)); + Expect.equals(102535, F31(10, c:35, b:25)); + Expect.equals(102535, np.f42(10, c:35, b:25)); + Expect.equals(10200040, F41(10)); + Expect.equals(10200040, np.f52(10)); + Expect.equals(10203540, F41(10, c:35)); + Expect.equals(10203540, np.f52(10, c:35)); + Expect.equals(10250045, F41(10, d:45, b:25)); + Expect.equals(10250045, np.f52(10, d:45, b:25)); + Expect.equals(10253545, F41(10, d:45, c:35, b:25)); + Expect.equals(10253545, np.f52(10, d:45, c:35, b:25)); + } +} + +interface I factory C { + I(); + int mul(int a, [int factor]); +} + +class C implements I { + int mul(int a, [int factor = 10]) { + return a * factor; + } +} + + +main() { + NamedParametersTest.testMain(); + var i = new I(); + Expect.equals(100, i.mul(10)); + Expect.equals(1000, i.mul(10, 100)); + var c = new C(); + Expect.equals(100, c.mul(10)); + Expect.equals(1000, c.mul(10, 100)); +} diff --git a/tests/language/src/NamedParametersTypeTest.dart b/tests/language/src/NamedParametersTypeTest.dart new file mode 100644 index 00000000000..536395c2c80 --- /dev/null +++ b/tests/language/src/NamedParametersTypeTest.dart @@ -0,0 +1,43 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_type_checks +// +// Dart test program for testing named parameters in type tests. + +class NamedParametersTypeTest { + static int testMain() { + int result = 0; + Function anyFunction; + void acceptFunNumOptBool(void funNumOptBool(num num, [bool b])) { }; + void funNum(num num) { }; + void funNumBool(num num, bool b) { }; + void funNumOptBool(num num, [bool b = true]) { }; + void funNumOptBoolX(num num, [bool x = true]) { }; + anyFunction = funNum; // No error. + anyFunction = funNumBool; // No error. + anyFunction = funNumOptBool; // No error. + anyFunction = funNumOptBoolX; // No error. + acceptFunNumOptBool(funNum); // No error. + acceptFunNumOptBool(funNumOptBool); // No error. + try { + acceptFunNumOptBool(funNumBool); // Throws an error. + } catch (TypeError error) { + result += 1; + Expect.stringEquals("(num, [b: bool]) => void", error.dstType); + Expect.stringEquals("(num, bool) => void", error.srcType); + } + try { + acceptFunNumOptBool(funNumOptBoolX); // Throws an error. + } catch (TypeError error) { + result += 10; + Expect.stringEquals("(num, [b: bool]) => void", error.dstType); + Expect.stringEquals("(num, [x: bool]) => void", error.srcType); + } + return result; + } +} + +main() { + Expect.equals(11, NamedParametersTypeTest.testMain()); +} diff --git a/tests/language/src/NamedParametersWithConversionsTest.dart b/tests/language/src/NamedParametersWithConversionsTest.dart new file mode 100644 index 00000000000..c277d39021b --- /dev/null +++ b/tests/language/src/NamedParametersWithConversionsTest.dart @@ -0,0 +1,124 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// +// Test named arguments work as expected regardless of whether the function or +// method is called via function call syntax or method call syntax. + + +Validate(tag, a, b) { + // tag encodes which parameters are passed in with values a: 111, b: 222. + if (tag == 'ab') { + Expect.equals(a, 111); + Expect.equals(b, 222); + } + if (tag == 'a') { + Expect.equals(a, 111); + Expect.equals(b, 20); + } + if (tag == 'b') { + Expect.equals(a, 10); + Expect.equals(b, 222); + } + if (tag == '') { + Expect.equals(a, 10); + Expect.equals(b, 20); + } +} + +class HasMethod { + + int calls; + + HasMethod() : calls = 0 {} + + foo(tag, [a = 10, b = 20]) { + calls += 1; + Validate(tag, a, b); + } +} + +class HasField { + + int calls; + var foo; + + HasField() { + calls = 0; + foo = makeFoo(this); + } + + makeFoo(owner) { + // This function is closed-over 'owner'. + return (tag, [a = 10, b = 20]) { + owner.calls += 1; + Validate(tag, a, b); + }; + } +} + + +class NamedParametersWithConversionsTest { + + static checkException(thunk) { + bool threw = false; + try { + thunk(); + } catch (var e) { + threw = true; + } + Expect.isTrue(threw); + } + + static testMethodCallSyntax(a) { + a.foo(''); + a.foo('a', 111); + a.foo('ab', 111, 222); + a.foo('a', a: 111); + a.foo('b', b: 222); + a.foo('ab', a: 111, b: 222); + a.foo('ab', b: 222, a: 111); + + Expect.equals(7, a.calls); + + checkException(() => a.foo()); // Too few arguments. + checkException(() => a.foo('abc', 1, 2, 3)); // Too many arguments. + checkException(() => a.foo('c', c: 1)); // Bad name. + + Expect.equals(7, a.calls); + } + + static testFunctionCallSyntax(a) { + var f = a.foo; + f(''); + f('a', 111); + f('ab', 111, 222); + f('a', a: 111); + f('b', b: 222); + f('ab', a: 111, b: 222); + f('ab', b: 222, a: 111); + + Expect.equals(7, a.calls); + + checkException(() => f()); // Too few arguments. + checkException(() => f('abc', 1, 2, 3)); // Too many arguments. + checkException(() => f('c', c: 1)); // Bad name. + + Expect.equals(7, a.calls); + } + + static testMain() { + // 'Plain' calls where the method/field syntax matches the object. + testMethodCallSyntax(new HasMethod()); + testFunctionCallSyntax(new HasField()); + + // 'Conversion' calls where method/field call syntax does not match the + // object. + testMethodCallSyntax(new HasField()); + testFunctionCallSyntax(new HasMethod()); + } +} + +main() { + NamedParametersWithConversionsTest.testMain(); +} diff --git a/tests/language/src/NamingTest.dart b/tests/language/src/NamingTest.dart new file mode 100644 index 00000000000..49416a490bd --- /dev/null +++ b/tests/language/src/NamingTest.dart @@ -0,0 +1,510 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + A() { NamingTest.count++; } + foo(a, b) { + Expect.equals(1, a); + Expect.equals(2, b); + } +} + +class MyException { + MyException() {} +} + +class debugger { + static final int __PROTO__ = 5; + + int x; + + factory debugger.F() { + return new debugger(1); + } + debugger(x) : this.x = x + 1 { } + debugger.C(x) : this.x = x + 2 { } + debugger.C$C(x) : this.x = x + 3 { } + debugger.C$I(x) : this.x = x + 4 { } +} + +class debugger$C { + int x; + + factory debugger$C.F() { + return new debugger$C(1); + } + debugger$C(x) : this.x = x + 5 { } + debugger$C.C(x) : this.x = x + 6 { } + debugger$C.C$C(x) : this.x = x + 7 { } + debugger$C.C$I(x) : this.x = x + 8 { } +} + +class debugger$C$C { + int x; + + factory debugger$C$C.F() { + return new debugger$C$C(1); + } + debugger$C$C(x) : this.x = x + 9 { } + debugger$C$C.C(x) : this.x = x + 10 { } + debugger$C$C.C$C(x) : this.x = x + 11 { } + debugger$C$C.C$I(x) : this.x = x + 12 { } +} + +class with extends debugger$C { + int y; + + factory with.F() { + return new with(1, 2); + } + with(x, y) : super(x), this.y = y + 1 { } + with.I(x, y) : super.C(x), this.y = y + 2 { } + with.C(x, y) : super.C$C(x), this.y = y + 3 { } + with.I$C(x, y) : super.C$I(x), this.y = y + 4 { } + with.C$C(x, y) : super(x), this.y = y + 5 { } + with.C$C$C(x, y) : super.C(x), this.y = y + 6 { } + with.$C$I(x, y) : super.C$C(x), this.y = y + 7 { } + with.$$I$C(x, y) : super.C$I(x), this.y = y + 8 { } + with.$(x, y) : super(x), this.y = y + 9 { } + with.$$(x, y) : super.C(x), this.y = y + 10 { } +} + +class with$I extends debugger$C { + int y; + + factory with$I.F() { + return new with$I(1, 2); + } + with$I(x, y) : super(x), this.y = y + 11 { } + with$I.I(x, y) : super.C(x), this.y = y + 12 { } + with$I.C(x, y) : super.C$C(x), this.y = y + 13 { } + with$I.I$C(x, y) : super.C$I(x), this.y = y + 14 { } + with$I.C$C(x, y) : super(x), this.y = y + 15 { } + with$I.C$C$C(x, y) : super.C(x), this.y = y + 16 { } + with$I.$C$I(x, y) : super.C$C(x), this.y = y + 17 { } + with$I.$$I$C(x, y) : super.C$I(x), this.y = y + 18 { } + with$I.$(x, y) : super(x), this.y = y + 19 { } + with$I.$$(x, y) : super.C(x), this.y = y + 20 { } +} + +class with$C extends debugger$C$C { + int y; + + factory with$C.F() { + return new with$C(1, 2); + } + with$C(x, y) : super(x), this.y = y + 21 { } + with$C.I(x, y) : super.C(x), this.y = y + 22 { } + with$C.C(x, y) : super.C$C(x), this.y = y + 23 { } + with$C.I$C(x, y) : super.C$I(x), this.y = y + 24 { } + with$C.C$C(x, y) : super(x), this.y = y + 25 { } + with$C.C$C$C(x, y) : super.C(x), this.y = y + 26 { } + with$C.$C$I(x, y) : super.C$C(x), this.y = y + 27 { } + with$C.$$I$C(x, y) : super.C$I(x), this.y = y + 28 { } + with$C.$(x, y) : super(x), this.y = y + 29 { } + with$C.$$(x, y) : super.C(x), this.y = y + 30 { } +} + +class with$I$C extends debugger$C$C { + int y; + + factory with$I$C.F() { + return new with$I$C(1, 2); + } + with$I$C(x, y) : super(x), this.y = y + 31 { } + with$I$C.I(x, y) : super.C(x), this.y = y + 32 { } + with$I$C.C(x, y) : super.C$C(x), this.y = y + 33 { } + with$I$C.I$C(x, y) : super.C$I(x), this.y = y + 34 { } + with$I$C.C$C(x, y) : super(x), this.y = y + 35 { } + with$I$C.C$C$C(x, y) : super.C(x), this.y = y + 36 { } + with$I$C.$C$I(x, y) : super.C$C(x), this.y = y + 37 { } + with$I$C.$$I$C(x, y) : super.C$I(x), this.y = y + 38 { } + with$I$C.$(x, y) : super(x), this.y = y + 39 { } + with$I$C.$$(x, y) : super.C(x), this.y = y + 40 { } +} + +class Tata { + var prototype; + + Tata() : this.prototype = 0 {} + + __PROTO__$() { return 12; } +} + +class Toto extends Tata { + var __PROTO__; + + Toto() : super(), this.__PROTO__ = 0 { } + + prototype$() { return 10; } + + titi() { + Expect.equals(0, prototype); + Expect.equals(0, __PROTO__); + prototype = 3; + __PROTO__ = 5; + Expect.equals(3, prototype); + Expect.equals(5, __PROTO__); + Expect.equals(10, prototype$()); + Expect.equals(12, __PROTO__$()); + Expect.equals(12, this.__PROTO__$()); + Expect.equals(10, this.prototype$()); + Expect.equals(12, __PROTO__$()); + } +} + +class Bug4082360 { + int x_; + Bug4082360() {} + + int get x() { return x_; } + void set x(int value) { x_ = value; } + + void indirectSet(int value) { x = value; } + + static void test() { + var bug = new Bug4082360(); + bug.indirectSet(42); + Expect.equals(42, bug.x_); + Expect.equals(42, bug.x); + } +} + +class Hoisting { + var f_; + Hoisting.negate(var x) { + f_ = () { return x; }; + } + + operator negate() { + var x = 3; + return () { return x + 1; }; + } + + negate(x) { + return () { return x + 2; }; + } + + operator[] (x) { + return () { return x + 3; }; + } + + static void test() { + var h = new Hoisting.negate(1); + Expect.equals(1, (h.f_)()); + var f = -h; + Expect.equals(4, f()); + Expect.equals(6, h.negate(4)()); + Expect.equals(7, h[4]()); + } +} + +// It is not possible to make sure that the backend uses the hardcoded names +// we are testing against. This test might therefore become rapidly out of date +class NamingTest { + static int count; + + static testExceptionNaming() { + // Exceptions use a hardcoded "e" as exception name. If the namer works + // correctly then it will be renamed in case of clashes. + var e = 3; + var caught = false; + try { + throw new MyException(); + } catch (var exc) { + try { + throw new MyException(); + } catch (var exc2) { + exc = 9; + } + Expect.equals(9, exc); + caught = true; + } + Expect.equals(true, caught); + Expect.equals(3, e); + } + + static testTmpNaming() { + Expect.equals(0, count); + var tmp$0 = 1; + var tmp$1 = 2; + new A().foo(tmp$0, tmp$1++); + Expect.equals(1, count); + Expect.equals(3, tmp$1); + } + + static testScopeNaming() { + // Alias scopes use a hardcoded "dartc_scp$" as names. + var dartc_scp$1 = 5; + var foo = 8; + var f = () { + var dartc_scp$1 = 15; + return foo + dartc_scp$1; + }; + Expect.equals(5, dartc_scp$1); + Expect.equals(23, f()); + } + + static testGlobalMangling() { + var x; + x = new debugger(0); + Expect.equals(1, x.x); + x = new debugger.C(0); + Expect.equals(2, x.x); + x = new debugger.C$C(0); + Expect.equals(3, x.x); + x = new debugger.C$I(0); + Expect.equals(4, x.x); + x = new debugger$C(0); + Expect.equals(5, x.x); + x = new debugger$C.C(0); + Expect.equals(6, x.x); + x = new debugger$C.C$C(0); + Expect.equals(7, x.x); + x = new debugger$C.C$I(0); + Expect.equals(8, x.x); + x = new debugger$C$C(0); + Expect.equals(9, x.x); + x = new debugger$C$C.C(0); + Expect.equals(10, x.x); + x = new debugger$C$C.C$C(0); + Expect.equals(11, x.x); + x = new debugger$C$C.C$I(0); + Expect.equals(12, x.x); + x = new with(0, 0); + Expect.equals(5, x.x); + Expect.equals(1, x.y); + x = new with.I(0, 0); + Expect.equals(6, x.x); + Expect.equals(2, x.y); + x = new with.C(0, 0); + Expect.equals(7, x.x); + Expect.equals(3, x.y); + x = new with.I$C(0, 0); + Expect.equals(8, x.x); + Expect.equals(4, x.y); + x = new with.C$C(0, 0); + Expect.equals(5, x.x); + Expect.equals(5, x.y); + x = new with.C$C$C(0, 0); + Expect.equals(6, x.x); + Expect.equals(6, x.y); + x = new with.$C$I(0, 0); + Expect.equals(7, x.x); + Expect.equals(7, x.y); + x = new with.$$I$C(0, 0); + Expect.equals(8, x.x); + Expect.equals(8, x.y); + x = new with.$(0, 0); + Expect.equals(5, x.x); + Expect.equals(9, x.y); + x = new with.$$(0, 0); + Expect.equals(6, x.x); + Expect.equals(10, x.y); + x = new with$I(0, 0); + Expect.equals(5, x.x); + Expect.equals(11, x.y); + x = new with$I.I(0, 0); + Expect.equals(6, x.x); + Expect.equals(12, x.y); + x = new with$I.C(0, 0); + Expect.equals(7, x.x); + Expect.equals(13, x.y); + x = new with$I.I$C(0, 0); + Expect.equals(8, x.x); + Expect.equals(14, x.y); + x = new with$I.C$C(0, 0); + Expect.equals(5, x.x); + Expect.equals(15, x.y); + x = new with$I.C$C$C(0, 0); + Expect.equals(6, x.x); + Expect.equals(16, x.y); + x = new with$I.$C$I(0, 0); + Expect.equals(7, x.x); + Expect.equals(17, x.y); + x = new with$I.$$I$C(0, 0); + Expect.equals(8, x.x); + Expect.equals(18, x.y); + x = new with$I.$(0, 0); + Expect.equals(5, x.x); + Expect.equals(19, x.y); + x = new with$I.$$(0, 0); + Expect.equals(6, x.x); + Expect.equals(20, x.y); + x = new with$C(0, 0); + Expect.equals(9, x.x); + Expect.equals(21, x.y); + x = new with$C.I(0, 0); + Expect.equals(10, x.x); + Expect.equals(22, x.y); + x = new with$C.C(0, 0); + Expect.equals(11, x.x); + Expect.equals(23, x.y); + x = new with$C.I$C(0, 0); + Expect.equals(12, x.x); + Expect.equals(24, x.y); + x = new with$C.C$C(0, 0); + Expect.equals(9, x.x); + Expect.equals(25, x.y); + x = new with$C.C$C$C(0, 0); + Expect.equals(10, x.x); + Expect.equals(26, x.y); + x = new with$C.$C$I(0, 0); + Expect.equals(11, x.x); + Expect.equals(27, x.y); + x = new with$C.$$I$C(0, 0); + Expect.equals(12, x.x); + Expect.equals(28, x.y); + x = new with$C.$(0, 0); + Expect.equals(9, x.x); + Expect.equals(29, x.y); + x = new with$C.$$(0, 0); + Expect.equals(10, x.x); + Expect.equals(30, x.y); + x = new with$I$C(0, 0); + Expect.equals(9, x.x); + Expect.equals(31, x.y); + x = new with$I$C.I(0, 0); + Expect.equals(10, x.x); + Expect.equals(32, x.y); + x = new with$I$C.C(0, 0); + Expect.equals(11, x.x); + Expect.equals(33, x.y); + x = new with$I$C.I$C(0, 0); + Expect.equals(12, x.x); + Expect.equals(34, x.y); + x = new with$I$C.C$C(0, 0); + Expect.equals(9, x.x); + Expect.equals(35, x.y); + x = new with$I$C.C$C$C(0, 0); + Expect.equals(10, x.x); + Expect.equals(36, x.y); + x = new with$I$C.$C$I(0, 0); + Expect.equals(11, x.x); + Expect.equals(37, x.y); + x = new with$I$C.$$I$C(0, 0); + Expect.equals(12, x.x); + Expect.equals(38, x.y); + x = new with$I$C.$(0, 0); + Expect.equals(9, x.x); + Expect.equals(39, x.y); + x = new with$I$C.$$(0, 0); + Expect.equals(10, x.x); + Expect.equals(40, x.y); + var wasCaught = false; + try { + throw new with(0, 0); + } catch(with e) { + wasCaught = true; + Expect.equals(5, e.x); + } + Expect.equals(true, wasCaught); + } + + static void testMemberMangling() { + Expect.equals(5, debugger.__PROTO__); + new Toto().titi(); + } + + static void testFactoryMangling() { + var o = new debugger.F(); + Expect.equals(2, o.x); + o = new debugger$C.F(); + Expect.equals(6, o.x); + o = new debugger$C$C.F(); + Expect.equals(10, o.x); + o = new with.F(); + Expect.equals(6, o.x); + Expect.equals(3, o.y); + o = new with$I.F(); + Expect.equals(6, o.x); + Expect.equals(13, o.y); + o = new with$C.F(); + Expect.equals(10, o.x); + Expect.equals(23, o.y); + o = new with$I$C.F(); + Expect.equals(10, o.x); + Expect.equals(33, o.y); + } + + static testFunctionParameters() { + a(with) { + return with; + } + + b(eval) { + return eval; + } + + c(arguments) { + return arguments; + } + + Expect.equals(10, a(10)); + Expect.equals(10, b(10)); + Expect.equals(10, c(10)); + } + + static testPseudoTokens() { + var EOS = 400; + var ILLEGAL = 99; + Expect.equals(499, EOS + ILLEGAL); + } + + static void testMain() { + count = 0; + testExceptionNaming(); + testTmpNaming(); + testScopeNaming(); + testGlobalMangling(); + testMemberMangling(); + testFactoryMangling(); + testFunctionParameters(); + Bug4082360.test(); + Hoisting.test(); + testPseudoTokens(); + } +} + + +// Ensure we don't have false positive. named constructor and methods +// are in different namespaces, therefore it is ok to have a method +// called foo and a named constructor CLASS.foo +class Naming1Test { + Naming1Test.foo() { } + foo() { } + + static void main(args) { + var a = new Naming1Test.foo(); + a.foo(); + } +} + +// Ensure we don't have false positive. +class Naming2Test { + Naming2Test() { } + int get foo() { return 1; } + set foo(x) { } + + static void main(args) { + var a = new Naming2Test(); + a.foo(2); + } +} + +// Ensure we don't have false positivesj. +class Naming3Test { + Naming3Test() { } + operator negate() { } + negate() { } + + static void main(args) { + var a = new Naming3Test(); + a.negate(3); + } +} + +main() { + NamingTest.testMain(); +} diff --git a/tests/language/src/NativeTest.dart b/tests/language/src/NativeTest.dart new file mode 100644 index 00000000000..93f435a637c --- /dev/null +++ b/tests/language/src/NativeTest.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program which shows how to write self verifying tests +// and how to print dart objects if needed. + +class Helper { + static int foo(int i) { + return i + 10; + } +} + +class NativeTest { + static testMain() { + int i = 10; + int result = 10 + 10 + 10; + i = Helper.foo(i + 10); + print("$i is result."); + Expect.equals(i, result); + } +} + + +main() { + NativeTest.testMain(); +} diff --git a/tests/language/src/NewExpression1NegativeTest.dart b/tests/language/src/NewExpression1NegativeTest.dart new file mode 100644 index 00000000000..450997bebe2 --- /dev/null +++ b/tests/language/src/NewExpression1NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NewExpressionNegativeTest { + NewExpressionNegativeTest() { } + + static void testMain() { + new NewExpressionNegativeTest; + } + } + +main() { + NewExpression1NegativeTest.testMain(); +} diff --git a/tests/language/src/NewExpression2NegativeTest.dart b/tests/language/src/NewExpression2NegativeTest.dart new file mode 100644 index 00000000000..55bb2a071df --- /dev/null +++ b/tests/language/src/NewExpression2NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NewExpressionNegativeTest { + NewExpressionNegativeTest() { } + + static void testMain() { + new NewExpressionNegativeTest(; + } + } + +main() { + NewExpression2NegativeTest.testMain(); +} diff --git a/tests/language/src/NewExpression3NegativeTest.dart b/tests/language/src/NewExpression3NegativeTest.dart new file mode 100644 index 00000000000..e16489cd810 --- /dev/null +++ b/tests/language/src/NewExpression3NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NewExpressionNegativeTest { + NewExpressionNegativeTest() { } + + static void testMain() { + new NewExpressionNegativeTest(...; + } + } + +main() { + NewExpression3NegativeTest.testMain(); +} diff --git a/tests/language/src/NewStatementTest.dart b/tests/language/src/NewStatementTest.dart new file mode 100644 index 00000000000..5e00f4d3f58 --- /dev/null +++ b/tests/language/src/NewStatementTest.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test a new statement by itself. + +class A { + int a; + int b; + static int c; + static int d; + + A(int x, int y) : a = x, b = y { + A.c = x; + A.d = y; + } +} + +class NewStatementTest { + static testMain() { + new A(10, 20); + Expect.equals(10, A.c); + Expect.equals(20, A.d); + } +} + + +main() { + NewStatementTest.testMain(); +} diff --git a/tests/language/src/NoSuchMethodNegativeTest.dart b/tests/language/src/NoSuchMethodNegativeTest.dart new file mode 100644 index 00000000000..f2a9d720b4d --- /dev/null +++ b/tests/language/src/NoSuchMethodNegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing that NoSuchMethodException stops the program. + +class NoSuchMethodNegativeTest { + NoSuchMethodNegativeTest() {} + + foo() { return 1; } + + static testMain() { + var obj = new NoSuchMethodNegativeTest(); + return obj.moo(); // NoSuchMethodException thrown here + } +} + +main() { + NoSuchMethodNegativeTest.testMain(); +} diff --git a/tests/language/src/NoSuchMethodTest.dart b/tests/language/src/NoSuchMethodTest.dart new file mode 100644 index 00000000000..138df66ea62 --- /dev/null +++ b/tests/language/src/NoSuchMethodTest.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing that NoSuchMethod is properly called. + +class NoSuchMethodTest { + + foo([a = 10, b = 20]) { + return (10 * a) + b; + } + + noSuchMethod(String name, List args) { + Expect.equals("moo", name); + Expect.equals(1, args.length); + return foo(args[0]); + } + + static testMain() { + var obj = new NoSuchMethodTest(); + Expect.equals(1010, obj.moo(b:99)); // obj.NoSuchMethod called here. + // After we remove the rest argument and change the signature of + // noSuchMethod to be compatible with named arguments, we can expect the + // correct value of 199 instead of 1010. + } +} + +main() { + NoSuchMethodTest.testMain(); +} diff --git a/tests/language/src/NonConstConstructorWithoutBodyTest.dart b/tests/language/src/NonConstConstructorWithoutBodyTest.dart new file mode 100644 index 00000000000..7e8fdc25342 --- /dev/null +++ b/tests/language/src/NonConstConstructorWithoutBodyTest.dart @@ -0,0 +1,28 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NonConstConstructorWithoutBodyTest { + int x; + + NonConstConstructorWithoutBodyTest(); + NonConstConstructorWithoutBodyTest.named(); + NonConstConstructorWithoutBodyTest.initializers() : x = 1; + NonConstConstructorWithoutBodyTest.parameters(int x) : x = x + 1; + NonConstConstructorWithoutBodyTest.fieldParameter(int this.x); + NonConstConstructorWithoutBodyTest.redirection() : this.initializers(); + + static testMain() { + Expect.equals(null, new NonConstConstructorWithoutBodyTest().x); + Expect.equals(null, new NonConstConstructorWithoutBodyTest.named().x); + Expect.equals(1, new NonConstConstructorWithoutBodyTest.initializers().x); + Expect.equals(2, new NonConstConstructorWithoutBodyTest.parameters(1).x); + Expect.equals( + 2, new NonConstConstructorWithoutBodyTest.fieldParameter(2).x); + Expect.equals(1, new NonConstConstructorWithoutBodyTest.redirection().x); + } +} + +main() { + NonConstConstructorWithoutBodyTest.testMain(); +} diff --git a/tests/language/src/NonConstSuperNegativeTest.dart b/tests/language/src/NonConstSuperNegativeTest.dart new file mode 100644 index 00000000000..b07fb79d118 --- /dev/null +++ b/tests/language/src/NonConstSuperNegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check fails because const class extends from non const class. + +class Base { + Base() {} +} + +class Sub extends Base { + const Sub(a) : a_ = a; + final a_; +} + +class NonConstSuperNegativeTest { + static testMain() { + } +} + +main() { + NonConstSuperNegativeTest.testMain(); +} diff --git a/tests/language/src/NullPointerExceptionTest.dart b/tests/language/src/NullPointerExceptionTest.dart new file mode 100644 index 00000000000..64d5d3956c8 --- /dev/null +++ b/tests/language/src/NullPointerExceptionTest.dart @@ -0,0 +1,49 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NullPointerExceptionTest { + + static void testNullPointerExceptionVariable() { + int variable; + bool exceptionCaught = false; + bool wrongExceptionCaught = false; + try { + variable++; + } catch (NullPointerException ex) { + exceptionCaught = true; + } catch (Exception ex) { + wrongExceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + Expect.equals(true, !wrongExceptionCaught); + } + + static int helperFunction(int parameter) { + return parameter++; + } + + static void testNullPointerExceptionFunctionCall() { + int variable; + bool exceptionCaught = false; + bool wrongExceptionCaught = false; + try { + variable = helperFunction(variable); + } catch (NullPointerException ex) { + exceptionCaught = true; + } catch (Exception ex) { + wrongExceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + Expect.equals(true, !wrongExceptionCaught); + } + + static void testMain() { + testNullPointerExceptionVariable(); + testNullPointerExceptionFunctionCall(); + } +} + +main() { + NullPointerExceptionTest.testMain(); +} diff --git a/tests/language/src/NullTest.dart b/tests/language/src/NullTest.dart new file mode 100644 index 00000000000..e52a06ddab2 --- /dev/null +++ b/tests/language/src/NullTest.dart @@ -0,0 +1,52 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Second dart test program. + +class NullTest { + static int foo(var obj) { + Expect.equals(null, obj); + } + + static bool compareToNull(var value) { + return null == value; + } + + static bool compareWithNull(var value) { + return value == null; + } + + static int testMain() { + var val = 1; + var obj = null; + + Expect.equals(null, obj); + Expect.equals(null, null); + + foo(obj); + foo(null); + + if (obj != null) { + foo(null); + } else { + foo(obj); + } + + Expect.isFalse(compareToNull(val)); + Expect.isTrue(compareToNull(obj)); + Expect.isFalse(compareWithNull(val)); + Expect.isTrue(compareWithNull(obj)); + Expect.isTrue(obj is Object); + Expect.isFalse(obj is String); + Expect.isTrue(obj is !String); + Expect.isFalse(obj is !Object); + Expect.isFalse(val is !Object); + + return 0; + } +} + + +main() { + NullTest.testMain(); +} diff --git a/tests/language/src/NumberIdentifierNegativeTest.dart b/tests/language/src/NumberIdentifierNegativeTest.dart new file mode 100644 index 00000000000..587267b1289 --- /dev/null +++ b/tests/language/src/NumberIdentifierNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NumberIdentifierNegativeTest { + + static void testMain() { + 1is int; // Number literals must not be followed by an identifier or keyword. + } + +} +main() { + NumberIdentifierNegativeTest.testMain(); +} diff --git a/tests/language/src/NumberSyntaxTest.dart b/tests/language/src/NumberSyntaxTest.dart new file mode 100644 index 00000000000..be57ab00477 --- /dev/null +++ b/tests/language/src/NumberSyntaxTest.dart @@ -0,0 +1,81 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class NumberSyntaxTest { + + static void testMain() { + testShortDoubleSyntax(); + testDotSelectorSyntax(); + } + + static void testShortDoubleSyntax() { + Expect.equals(0.0, .0); + Expect.equals(0.5, .5); + Expect.equals(0.1234, .1234); + } + + static void testDotSelectorSyntax() { + // Integers. + Expect.equals(0, 0.dynamic); + Expect.equals(1, 1.dynamic); + Expect.equals(123, 123.dynamic); + Expect.equals('0', 0.toString()); + Expect.equals('1', 1.toString()); + Expect.equals('123', 123.toString()); + + Expect.equals(0, 0 .dynamic); + Expect.equals(1, 1 .dynamic); + Expect.equals(123, 123 .dynamic); + Expect.equals('0', 0 .toString()); + Expect.equals('1', 1 .toString()); + Expect.equals('123', 123 .toString()); + + Expect.equals(0, 0. dynamic); + Expect.equals(1, 1. dynamic); + Expect.equals(123, 123. dynamic); + Expect.equals('0', 0. toString()); + Expect.equals('1', 1. toString()); + Expect.equals('123', 123. toString()); + + // Doubles. + Expect.equals(0.0, 0.0.dynamic); + Expect.equals(0.1, .1.dynamic); + Expect.equals(1.1, 1.1.dynamic); + Expect.equals(123.4, 123.4.dynamic); + Expect.equals((0.0).toString(), 0.0.toString()); + Expect.equals((0.1).toString(), .1.toString()); + Expect.equals((1.1).toString(), 1.1.toString()); + Expect.equals((123.4).toString(), 123.4.toString()); + + Expect.equals(0.0, 0.0 .dynamic); + Expect.equals(0.1, .1.dynamic); + Expect.equals(1.1, 1.1 .dynamic); + Expect.equals(123.4, 123.4 .dynamic); + Expect.equals((0.0).toString(), 0.0 .toString()); + Expect.equals((0.1).toString(), .1 .toString()); + Expect.equals((1.1).toString(), 1.1 .toString()); + Expect.equals((123.4).toString(), 123.4 .toString()); + + Expect.equals(0.0, 0.0. dynamic); + Expect.equals(0.1, .1.dynamic); + Expect.equals(1.1, 1.1. dynamic); + Expect.equals(123.4, 123.4. dynamic); + Expect.equals((0.0).toString(), 0.0. toString()); + Expect.equals((0.1).toString(), .1. toString()); + Expect.equals((1.1).toString(), 1.1. toString()); + Expect.equals((123.4).toString(), 123.4. toString()); + + // Exponent notation. + Expect.equals(0e0, 0e0.dynamic); + Expect.equals(1e+1, 1e+1.dynamic); + Expect.equals(2.1e-34, 2.1e-34.dynamic); + Expect.equals((0e0).toString(), 0e0.toString()); + Expect.equals((1e+1).toString(), 1e+1.toString()); + Expect.equals((2.1e-34).toString(), 2.1e-34.toString()); + } + +} +main() { + NumberSyntaxTest.testMain(); +} diff --git a/tests/language/src/NumbersTest.dart b/tests/language/src/NumbersTest.dart new file mode 100644 index 00000000000..55289cf56e6 --- /dev/null +++ b/tests/language/src/NumbersTest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test number types. +// VMOptions=--expose_core_impl + +class NumbersTest { + static double testMain() { + var one = 1; + Expect.equals(true, one is Object); + Expect.equals(true, one is num); + Expect.equals(true, one is int); + Expect.equals(true, one is Smi); + Expect.equals(false, one is double); + Expect.equals(false, one is Double); + + var two = 2.0; + Expect.equals(true, two is Object); + Expect.equals(true, two is num); + Expect.equals(false, two is int); + Expect.equals(false, two is Smi); + Expect.equals(true, two is double); + Expect.equals(true, two is Double); + + var result = one + two; + Expect.equals(true, result is Object); + Expect.equals(true, result is num); + Expect.equals(false, result is int); + Expect.equals(false, result is Smi); + Expect.equals(true, result is double); + Expect.equals(true, result is Double); + + Expect.equals(3.0, result); + return result; + } +} + + +main() { + NumbersTest.testMain(); +} diff --git a/tests/language/src/Operator1NegativeTest.dart b/tests/language/src/Operator1NegativeTest.dart new file mode 100644 index 00000000000..7f9c24daad2 --- /dev/null +++ b/tests/language/src/Operator1NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Operator dart test program (operator functions cannot be static). + +class Helper { + int i; + Helper(int val) : i = val { } + static operator +(int index) { + return index; + } +} + +class Operator1NegativeTest { + static testMain() { + Helper obj = new Helper(10); + } +} + +main() { + Operator1NegativeTest.testMain(); +} diff --git a/tests/language/src/Operator2NegativeTest.dart b/tests/language/src/Operator2NegativeTest.dart new file mode 100644 index 00000000000..5ee70965942 --- /dev/null +++ b/tests/language/src/Operator2NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Operator dart test program (=== cannot have an operator function). + +class Helper { + int i; + Helper(int val) : i = val { } + operator ===(int index) { + return index; + } +} + +class Operator2NegativeTest { + static testMain() { + Helper obj = new Helper(10); + } +} + +main() { + Operator2NegativeTest.testMain(); +} diff --git a/tests/language/src/Operator2Test.dart b/tests/language/src/Operator2Test.dart new file mode 100644 index 00000000000..f6e48f3e322 --- /dev/null +++ b/tests/language/src/Operator2Test.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Operator dart test program. + +class Helper { + int i; + Helper(int val) : i = val { } + operator [](int index) { + return i + index; + } + void operator []=(int index, int val) { + i = val; + } +} + +class OperatorTest { + static testMain() { + Helper obj = new Helper(10); + Expect.equals(10, obj.i); + obj[10] = 20; + Expect.equals(30, obj[10]); + } +} + + +main() { + OperatorTest.testMain(); +} diff --git a/tests/language/src/OperatorTest.dart b/tests/language/src/OperatorTest.dart new file mode 100644 index 00000000000..e9f74c70115 --- /dev/null +++ b/tests/language/src/OperatorTest.dart @@ -0,0 +1,142 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class OperatorTest { + static int i1, i2; + + OperatorTest() {} + + static testMain() { + var op1 = new Operator(1); + var op2 = new Operator(2); + Expect.equals(3, op1 + op2); + Expect.equals(-1, op1 - op2); + Expect.equals(0.5, op1 / op2); + Expect.equals(0, op1 ~/ op2); + Expect.equals(2, op1 * op2); + Expect.equals(1, op1 % op2); + Expect.equals(true, !(op1 == op2)); + Expect.equals(true, op1 < op2); + Expect.equals(true, !(op1 > op2)); + Expect.equals(true, op1 <= op2); + Expect.equals(true, !(op1 >= op2)); + Expect.equals(3, (op1 | op2)); + Expect.equals(3, (op1 ^ op2)); + Expect.equals(0, (op1 & op2)); + Expect.equals(4, (op1 << op2)); + Expect.equals(0, (op1 >> op2)); + Expect.equals(~1, ~op1); + Expect.equals(-1, -op1); + + op1.value += op2.value; + Expect.equals(3, op1.value); + + op2.value += (op2.value += op2.value); + Expect.equals(6, op2.value); + + op2.value -= (op2.value -= op2.value); + Expect.equals(6, op2.value); + + op1.value = op2.value = 42; + Expect.equals(42, op1.value); + Expect.equals(42, op2.value); + + i1 = i2 = 42; + Expect.equals(42, i1); + Expect.equals(42, i2); + i1 += 7; + Expect.equals(49, i1); + i1 += (i2 = 17); + Expect.equals(66, i1); + Expect.equals(17, i2); + + i1 += i2 += 3; + Expect.equals(86, i1); + Expect.equals(20, i2); + } +} + +class Operator { + int value; + + Operator(int i) { + value = i; + } + + operator +(Operator other) { + return value + other.value; + } + + operator -(Operator other) { + return value - other.value; + } + + operator /(Operator other) { + return value / other.value; + } + + operator *(Operator other) { + return value * other.value; + } + + operator %(Operator other) { + return value % other.value; + } + + operator ==(Operator other) { + return value == other.value; + } + + operator <(Operator other) { + return value < other.value; + } + + operator >(Operator other) { + return value > other.value; + } + + operator <=(Operator other) { + return value <= other.value; + } + + operator >=(Operator other) { + return value >= other.value; + } + + operator |(Operator other) { + return value | other.value; + } + + operator ^(Operator other) { + return value ^ other.value; + } + + operator &(Operator other) { + return value & other.value; + } + + operator <<(Operator other) { + return value << other.value; + } + + operator >>(Operator other) { + return value >> other.value; + } + + operator ~/(Operator other) { + return value ~/ other.value; + } + + operator ~() { + return ~value; + } + + operator negate() { + return -value; + } +} + +main() { + OperatorTest.testMain(); +} diff --git a/tests/language/src/OrderedMapsTest.dart b/tests/language/src/OrderedMapsTest.dart new file mode 100644 index 00000000000..7bcf697bb3f --- /dev/null +++ b/tests/language/src/OrderedMapsTest.dart @@ -0,0 +1,78 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests that map literals are ordered. + +class OrderedMapsTest { + static testMain() { + testMaps(const { "a": 1, "c": 2 }, const { "c": 2, "a": 1}, true); + testMaps({ "a": 1, "c": 2 }, { "c": 2, "a": 1 }, false); + } + + static void testMaps(map1, map2, bool isConst) { + Expect.equals(true, map1 !== map2); + + var keys = map1.getKeys(); + Expect.equals(2, keys.length); + Expect.equals("a", keys[0]); + Expect.equals("c", keys[1]); + + keys = map2.getKeys(); + Expect.equals(2, keys.length); + Expect.equals("c", keys[0]); + Expect.equals("a", keys[1]); + + var values = map1.getValues(); + Expect.equals(2, values.length); + Expect.equals(1, values[0]); + Expect.equals(2, values[1]); + + values = map2.getValues(); + Expect.equals(2, values.length); + Expect.equals(2, values[0]); + Expect.equals(1, values[1]); + + if (isConst) return; + + map1["b"] = 3; + map2["b"] = 3; + + keys = map1.getKeys(); + Expect.equals(3, keys.length); + Expect.equals("a", keys[0]); + Expect.equals("c", keys[1]); + Expect.equals("b", keys[2]); + + keys = map2.getKeys(); + Expect.equals(3, keys.length); + Expect.equals("c", keys[0]); + Expect.equals("a", keys[1]); + Expect.equals("b", keys[2]); + + values = map1.getValues(); + Expect.equals(3, values.length); + Expect.equals(1, values[0]); + Expect.equals(2, values[1]); + Expect.equals(3, values[2]); + + values = map2.getValues(); + Expect.equals(3, values.length); + Expect.equals(2, values[0]); + Expect.equals(1, values[1]); + Expect.equals(3, values[2]); + + map1["a"] = 4; + keys = map1.getKeys(); + Expect.equals(3, keys.length); + Expect.equals("a", keys[0]); + + values = map1.getValues(); + Expect.equals(3, values.length); + Expect.equals(4, values[0]); + } +} + +main() { + OrderedMapsTest.testMain(); +} diff --git a/tests/language/src/OverriddenNoSuchMethod.dart b/tests/language/src/OverriddenNoSuchMethod.dart new file mode 100644 index 00000000000..d2d26fbddd9 --- /dev/null +++ b/tests/language/src/OverriddenNoSuchMethod.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing overridden messageNotUnderstood. + +class OverriddenNoSuchMethod { + + OverriddenNoSuchMethod() {} + + noSuchMethod(var function_name, List args) { + Expect.equals("foo", function_name); + // 'foo' was called with two parameters (not counting receiver). + Expect.equals(2, args.length); + Expect.equals(101, args[0]); + Expect.equals(202, args[1]); + return 5; + } + + static testMain() { + var obj = new OverriddenNoSuchMethod(); + Expect.equals(5, obj.foo(101, 202)); + } +} diff --git a/tests/language/src/OverriddenNoSuchMethodTest.dart b/tests/language/src/OverriddenNoSuchMethodTest.dart new file mode 100644 index 00000000000..58854a0661c --- /dev/null +++ b/tests/language/src/OverriddenNoSuchMethodTest.dart @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing overridden messageNotUnderstood. + +#source("OverriddenNoSuchMethod.dart"); + +main() { + OverriddenNoSuchMethod.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod1NegativeTest.dart b/tests/language/src/OverrideFieldMethod1NegativeTest.dart new file mode 100644 index 00000000000..8827105f0f5 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod1NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding field with method. + +class A { + var foo; +} + +class B extends A { + foo() {} // method cannot override field. +} + +class OverrideFieldMethod1NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod1NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod2NegativeTest.dart b/tests/language/src/OverrideFieldMethod2NegativeTest.dart new file mode 100644 index 00000000000..07ecc9dadb7 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod2NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding getter with method. + +class A { + get foo() { return 123; } +} + +class B extends A { + foo() {} // method cannot override getter. +} + +class OverrideFieldMethod2NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod2NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod3NegativeTest.dart b/tests/language/src/OverrideFieldMethod3NegativeTest.dart new file mode 100644 index 00000000000..72d5d27d6f4 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod3NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding setter with method. + +class A { + set foo(x) { } +} + +class B extends A { + foo(x) {} // method cannot override setter. +} + +class OverrideFieldMethod3NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod3NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod4NegativeTest.dart b/tests/language/src/OverrideFieldMethod4NegativeTest.dart new file mode 100644 index 00000000000..f1c7bdc76c0 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod4NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding method with field. + +class A { + foo() { } +} + +class B extends A { + var foo; // Field cannot override method. +} + +class OverrideFieldMethod4NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod4NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod5NegativeTest.dart b/tests/language/src/OverrideFieldMethod5NegativeTest.dart new file mode 100644 index 00000000000..dfef44ac8c3 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod5NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding method with getter. + +class A { + foo() { return 999; } +} + +class B extends A { + get foo() { return 123; } // getter cannot override method +} + +class OverrideFieldMethod5NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod5NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldMethod6NegativeTest.dart b/tests/language/src/OverrideFieldMethod6NegativeTest.dart new file mode 100644 index 00000000000..612fc166b00 --- /dev/null +++ b/tests/language/src/OverrideFieldMethod6NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test error for overriding method with setter. + +class A { + foo(x) { } +} + +class B extends A { + set foo(x) { } // setter cannot override method. +} + +class OverrideFieldMethod6NegativeTest { + static testMain() { + } +} + +main() { + OverrideFieldMethod6NegativeTest.testMain(); +} diff --git a/tests/language/src/OverrideFieldTest.dart b/tests/language/src/OverrideFieldTest.dart new file mode 100644 index 00000000000..7e8ab43cb56 --- /dev/null +++ b/tests/language/src/OverrideFieldTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test checking that static/instance field shadowing do not conflict. + +class A { + A() {} // DartC has no implicit constructors yet. + + int instanceFieldInA; + static int staticFieldInA; +} + +class B extends A { + B() : super() {} // DartC has no implicit constructors yet. + + static int instanceFieldInA; /// 01: compile-time error + int staticFieldInA; /// 02: compile-time error + static int staticFieldInA; /// 03: compile-time error + int instanceFieldInA; +} + +main() { + var x = new B(); +} diff --git a/tests/language/src/OverrideMethodWithFieldTest.dart b/tests/language/src/OverrideMethodWithFieldTest.dart new file mode 100644 index 00000000000..739d49a6037 --- /dev/null +++ b/tests/language/src/OverrideMethodWithFieldTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test overriding a method with a field. + +class Super { + Super() : super(); + + instanceMethod() => 42; +} + +class Sub extends Super { + Sub() : super(), this.instanceMethod = 87; + + var instanceMethod; // Intentional static type error. + + superInstanceMethod() => super.instanceMethod(); +} + +main() { + var s = new Sub(); + Super sup = s; + Sub sub = s; + Expect.equals(87, s.instanceMethod); + Expect.equals(42, s.superInstanceMethod()); + Expect.equals(87, sup.instanceMethod); + Expect.equals(42, sup.superInstanceMethod()); // Intentional static type error. + Expect.equals(87, sub.instanceMethod); + Expect.equals(42, sub.superInstanceMethod()); +} diff --git a/tests/language/src/Param1Test.dart b/tests/language/src/Param1Test.dart new file mode 100644 index 00000000000..c2546663b8a --- /dev/null +++ b/tests/language/src/Param1Test.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing params. + +class Param1Test { + // TODO(asiva): Should we try to interpret 1 above as an int? In order to + // avoid a type error with --enable_type_checks, the type of i below is + // changed from int to String. + // static int testMain(String s, int i) { return i; } + static int testMain() { return 0; } +} + + +main() { + Param1Test.testMain(); +} diff --git a/tests/language/src/Param2Test.dart b/tests/language/src/Param2Test.dart new file mode 100644 index 00000000000..bedb313f78d --- /dev/null +++ b/tests/language/src/Param2Test.dart @@ -0,0 +1,63 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing function type parameters. + + +class Param2Test { + + static forEach(List a, int f(k)) { + for (int i = 0; i < a.length; i++) { + a[i] = f(a[i]); + } + } + + static int apply(f(int k), int arg) { + var res = f(arg); + return res; + } + + static exists(List a, f(e)) { + for (int i = 0; i < a.length; i++) { + if (f(a[i])) return true; + } + return false; + } + + static testMain() { + int square(int x) { + return x * x; + } + Expect.equals(4, apply(square, 2)); + Expect.equals(100, apply(square, 10)); + + var v = [1, 2, 3, 4, 5, 6]; + forEach(v, square); + Expect.equals(1, v[0]); + Expect.equals(4, v[1]); + Expect.equals(9, v[2]); + Expect.equals(16, v[3]); + Expect.equals(25, v[4]); + Expect.equals(36, v[5]); + + isOdd(element) { + return element % 2 == 1; + } + + Expect.equals(true, exists([3, 5, 7, 11, 13], isOdd)); + Expect.equals(false, exists([2, 4, 10], isOdd)); + Expect.equals(false, exists([], isOdd)); + + v = [4, 5, 7]; + Expect.equals(true, exists(v, (e) => e % 2 == 1)); + Expect.equals(false, exists(v, f(e) => e == 6)); + + var isZero = (e) => e == 0; + Expect.equals(false, exists(v, isZero)); + } +} + + +main() { + Param2Test.testMain(); +} diff --git a/tests/language/src/ParamTest.dart b/tests/language/src/ParamTest.dart new file mode 100644 index 00000000000..43abf50f8ec --- /dev/null +++ b/tests/language/src/ParamTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing params. + +class Helper { + static int foo(int i) { + var b; + b = i + 1; + return b; + } +} + +class ParamTest { + static testMain() { + Expect.equals(2, Helper.foo(1)); + } +} + + +main() { + ParamTest.testMain(); +} diff --git a/tests/language/src/ParameterInitializer1NegativeTest.dart b/tests/language/src/ParameterInitializer1NegativeTest.dart new file mode 100644 index 00000000000..c433dcef612 --- /dev/null +++ b/tests/language/src/ParameterInitializer1NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Fails because this.x parameter is used in a function. + +class Foo { + var x; + Foo() {} + foo(this.x) { + } +} + + +class ParameterInitializer1NegativeTest { + static testMain() { + new Foo().foo(2); + } +} + +main() { + ParameterInitializer1NegativeTest.testMain(); +} diff --git a/tests/language/src/ParameterInitializer2NegativeTest.dart b/tests/language/src/ParameterInitializer2NegativeTest.dart new file mode 100644 index 00000000000..c0758f5f963 --- /dev/null +++ b/tests/language/src/ParameterInitializer2NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Fails because this.x parameter is used in a setter. + +class Foo { + var x; + Foo() {} + set y(this.x) { + } +} + + +class ParameterInitializer2NegativeTest { + static testMain() { + (new Foo()).y = 2; + } +} + +main() { + ParameterInitializer2NegativeTest.testMain(); +} diff --git a/tests/language/src/ParameterInitializer2Test.dart b/tests/language/src/ParameterInitializer2Test.dart new file mode 100644 index 00000000000..e93ba6202d0 --- /dev/null +++ b/tests/language/src/ParameterInitializer2Test.dart @@ -0,0 +1,81 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test Parameter Intializer. + + +class ParameterInitializer2Test { + static testMain() { + var a = new A(123); + Expect.equals(123, a.x); + + var b = new B(123); + Expect.equals(123, b.x); + + var c = new C(123); + Expect.equals(123, c.x); + + var d = new D(123); + Expect.equals(123, d.x); + + var e = new E(1); + Expect.equals(4, e.x); + + var f = new F(1,2,3,4); + Expect.equals(4, f.z); + } +} + +// untyped +class A { + A(this.x) { + } + int x; +} + +// typed +class B { + B(int this.x) { + } + int x; +} + +// const typed +class C { + const C(int this.x); + final int x; +} + +// const untyped +class D { + const D(this.x); + final x; +} + +// make sure this. references work properly in the constructor scope. +class E { + E(this.x) { + var myVar = this.x * 2; + this.x = myVar + 1; + x = myVar + 2; + var foo = x + 1; + } + int x; +} + + +// mixed +class F { + F(x, this.y_, int w, int this.z) : x_ = x, w_ = w { } + F.foobar(this.z, int this.x_, int this.az_) { } + int x_; + int y_; + int w_; + int z; + int az_; +} + +main() { + ParameterInitializer2Test.testMain(); +} diff --git a/tests/language/src/ParameterInitializer3NegativeTest.dart b/tests/language/src/ParameterInitializer3NegativeTest.dart new file mode 100644 index 00000000000..b6425c40bb8 --- /dev/null +++ b/tests/language/src/ParameterInitializer3NegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Fails because this.x parameter is used in a factory. + +class Foo { + var x; + factory Foo(this.x) { + return new Foo.named(); + } + Foo.named() {} +} + + +class ParameterInitializer3NegativeTest { + static testMain() { + new Foo(2); + } +} + +main() { + ParameterInitializer3NegativeTest.testMain(); +} diff --git a/tests/language/src/ParameterInitializer4NegativeTest.dart b/tests/language/src/ParameterInitializer4NegativeTest.dart new file mode 100644 index 00000000000..9b32fae0dd9 --- /dev/null +++ b/tests/language/src/ParameterInitializer4NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Fails because this.x parameter is used in a static function. + +class Foo { + var x; + static foo(this.x) { + } +} + + +class ParameterInitializer4NegativeTest { + static testMain() { + Foo.foo(); + } +} + +main() { + ParameterInitializer4NegativeTest.testMain(); +} diff --git a/tests/language/src/ParameterInitializerTest.dart b/tests/language/src/ParameterInitializerTest.dart new file mode 100644 index 00000000000..4dbfbb19ab1 --- /dev/null +++ b/tests/language/src/ParameterInitializerTest.dart @@ -0,0 +1,71 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ParameterInitializerTest { + + static testMain() { + new Foo.untyped(1); + new Foo.supertype(1); + new Foo.subtype(1); + + var obj = new Foo(1); + Expect.equals(2, obj.x); + + obj = new SubFoo(42); + Expect.equals(1, obj.x); + + obj = new SubSubFoo(42); + Expect.equals(1, obj.x); + } +} + +class Foo { + Foo(num this.x) { + // Reference to x must resolve to the field. + x++; + Expect.equals(this.x, x); + } + + Foo.untyped(this.x) {} + Foo.supertype(Object this.x) {} + Foo.subtype(int this.x) {} + + num x; +} + +class SubFoo extends Foo { + SubFoo(num y) : super(y), x_ = 0 { + // Subfoo.setter of x has been invoked in the Foo constructor. + Expect.equals(x, 1); + Expect.equals(x_, 1); + + // The super.x will resolved to the field in Foo. + Expect.equals(super.x, y); + } + + get x() { + return x_; + } + + set x(num val) { + x_ = val; + } + + num x_; +} + +class SubSubFoo extends SubFoo { + SubSubFoo(num y) : super(y) { + // Subfoo.setter of x has been invoked in the Foo constructor. + Expect.equals(x, 1); + Expect.equals(x_, 1); + + // There is no way to get to the field in Foo. + Expect.equals(super.x, 1); + } +} + +main() { + ParameterInitializerTest.testMain(); +} diff --git a/tests/language/src/ParseTypesTest.dart b/tests/language/src/ParseTypesTest.dart new file mode 100644 index 00000000000..bc30665cc83 --- /dev/null +++ b/tests/language/src/ParseTypesTest.dart @@ -0,0 +1,38 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing parsing of "standard" types. + +class ParseTypesTest { + static bool callBool1() { + return true; + } + + static bool callBool2() { + return false; + } + + static int callInt() { + return 2; + } + + static String callString() { + return "Hey"; + } + + static double callDouble() { + return 4.0; + } + + static void testMain() { + Expect.equals(true, ParseTypesTest.callBool1()); + Expect.equals(false, ParseTypesTest.callBool2()); + Expect.equals(2, ParseTypesTest.callInt()); + Expect.equals("Hey", ParseTypesTest.callString()); + Expect.equals(4.0, ParseTypesTest.callDouble()); + } +} + +main() { + ParseTypesTest.testMain(); +} diff --git a/tests/language/src/Prefix10NegativeTest.dart b/tests/language/src/Prefix10NegativeTest.dart new file mode 100644 index 00000000000..0e9567acef5 --- /dev/null +++ b/tests/language/src/Prefix10NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +// Type parameters can shadow a library prefix. + +#import("library10.dart", prefix:"T"); +class P { + P.named(T this.fld); + T fld; + main() { + var i = new T.Library10(10); // This should be an error. + Expect.equals(10, i.fld); + } +} + +main() { + var i = new P.named(10); + i.main(); +} diff --git a/tests/language/src/Prefix10Test.dart b/tests/language/src/Prefix10Test.dart new file mode 100644 index 00000000000..9050435bacb --- /dev/null +++ b/tests/language/src/Prefix10Test.dart @@ -0,0 +1,48 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart", prefix : "lib10"); +#import("library11.dart", prefix : "lib11"); +class Prefix10Test { + static Test1() { + var result = 0; + var obj = new lib10.Library10(1); + result = obj.fld; + Expect.equals(1, result); + result += obj.func(); + Expect.equals(3, result); + result += lib10.Library10.static_func(); + Expect.equals(6, result); + result += lib10.Library10.static_fld; + Expect.equals(10, result); + } + static Test2() { + var result = 0; + var obj = new lib11.Library11(4); + result = obj.fld; + Expect.equals(4, result); + result += obj.func(); + Expect.equals(7, result); + result += lib11.Library11.static_func(); + Expect.equals(9, result); + result += lib11.Library11.static_fld; + Expect.equals(10, result); + } + static Test3() { + Expect.equals(10, lib10.top_level10); + Expect.equals(20, lib10.top_level_func10()); + } + static Test4() { + Expect.equals(100, lib11.top_level11); + Expect.equals(200, lib11.top_level_func11()); + } +} + +main() { + Prefix10Test.Test1(); + Prefix10Test.Test2(); + Prefix10Test.Test3(); + Prefix10Test.Test4(); +} diff --git a/tests/language/src/Prefix11NegativeTest.dart b/tests/language/src/Prefix11NegativeTest.dart new file mode 100644 index 00000000000..e5e3500958e --- /dev/null +++ b/tests/language/src/Prefix11NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library12.dart", prefix:"lib12"); +class Prefix11NegativeTest { + static Test1() { + // Symbols in libraries imported by the prefixed library should not be + // visible here. + var result = 0; + var obj = new lib12.Library11(1); + result = obj.fld; + Expect.equals(1, result); + result += obj.func(); + Expect.equals(4, result); + } +} + +main() { + Prefix11NegativeTest.Test1(); +} diff --git a/tests/language/src/Prefix11Test.dart b/tests/language/src/Prefix11Test.dart new file mode 100644 index 00000000000..49cf742d16a --- /dev/null +++ b/tests/language/src/Prefix11Test.dart @@ -0,0 +1,48 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart"); +#import("library11.dart", prefix : "lib11"); +class Prefix11Test { + static Test1() { + var result = 0; + var obj = new Library10(1); + result = obj.fld; + Expect.equals(1, result); + result += obj.func(); + Expect.equals(3, result); + result += Library10.static_func(); + Expect.equals(6, result); + result += Library10.static_fld; + Expect.equals(10, result); + } + static Test2() { + var result = 0; + var obj = new lib11.Library11(4); + result = obj.fld; + Expect.equals(4, result); + result += obj.func(); + Expect.equals(7, result); + result += lib11.Library11.static_func(); + Expect.equals(9, result); + result += lib11.Library11.static_fld; + Expect.equals(10, result); + } + static Test3() { + Expect.equals(10, top_level10); + Expect.equals(20, top_level_func10()); + } + static Test4() { + Expect.equals(100, lib11.top_level11); + Expect.equals(200, lib11.top_level_func11()); + } +} + +main() { + Prefix11Test.Test1(); + Prefix11Test.Test2(); + Prefix11Test.Test3(); + Prefix11Test.Test4(); +} diff --git a/tests/language/src/Prefix12NegativeTest.dart b/tests/language/src/Prefix12NegativeTest.dart new file mode 100644 index 00000000000..1b982f1baf3 --- /dev/null +++ b/tests/language/src/Prefix12NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library12.dart", prefix:"lib12"); +class Prefix12NegativeTest { + static Test1() { + // Symbols in libraries imported by the prefixed library should not be + // visible here. + var obj = lib12.top_level11; + Expect.equals(100, obj); + } +} + +main() { + Prefix12NegativeTest.Test1(); +} diff --git a/tests/language/src/Prefix12Test.dart b/tests/language/src/Prefix12Test.dart new file mode 100644 index 00000000000..c3d5601c9ac --- /dev/null +++ b/tests/language/src/Prefix12Test.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library11.dart", prefix : "lib11"); +class Prefix12Test { + static Test1() { + var result = 0; + var obj = new lib11.Library11.namedConstructor(10); + result = obj.fld; + Expect.equals(10, result); + } + static Test2() { + int result = 0; + var obj = new lib11.Library111.namedConstructor(10); + result = obj.fld; + Expect.equals(10, result); + } +} + +main() { + Prefix12Test.Test1(); + Prefix12Test.Test2(); +} diff --git a/tests/language/src/Prefix1NegativeTest.dart b/tests/language/src/Prefix1NegativeTest.dart new file mode 100644 index 00000000000..ca4b24e903d --- /dev/null +++ b/tests/language/src/Prefix1NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library1.dart"); +class Prefix1NegativeTest { + static Main() { + // This is a syntax error as library1 was not imported with a prefix. + return library1.foo; + } +} + +main() { + Prefix1NegativeTest.Main(); +} diff --git a/tests/language/src/Prefix2NegativeTest.dart b/tests/language/src/Prefix2NegativeTest.dart new file mode 100644 index 00000000000..71b4e206dff --- /dev/null +++ b/tests/language/src/Prefix2NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library2.dart", prefix: "lib2"); +class Prefix2NegativeTest { + static Main() { + // This is a syntax error as multiple prefixes are not possible. + return lib2.Library2.main() + lib2.lib1.foo; + } +} + +main() { + Prefix2NegativeTest.Main(); +} diff --git a/tests/language/src/Prefix3NegativeTest.dart b/tests/language/src/Prefix3NegativeTest.dart new file mode 100644 index 00000000000..c94598a9c79 --- /dev/null +++ b/tests/language/src/Prefix3NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +// Using the same prefix name while importing two different libraries is +// an error. +#import("library1.dart", prefix: "lib2"); +#import("library2.dart", prefix: "lib2"); +class Prefix3NegativeTest { + static Main() { + } +} + +main() { + Prefix3NegativeTest.Main(); +} diff --git a/tests/language/src/Prefix4NegativeTest.dart b/tests/language/src/Prefix4NegativeTest.dart new file mode 100644 index 00000000000..c1227289f7a --- /dev/null +++ b/tests/language/src/Prefix4NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart"); +class Prefix4NegativeTest { + static Test1() { + // Library prefixes in the imported libraries should not be visible here. + var result = 0; + var obj = new lib11.Library11(1); + result = obj.fld; + Expect.equals(1, result); + result += obj.func(); + Expect.equals(3, result); + } +} + +main() { + Prefix4NegativeTest.Test1(); +} diff --git a/tests/language/src/Prefix5NegativeTest.dart b/tests/language/src/Prefix5NegativeTest.dart new file mode 100644 index 00000000000..dd0526adb40 --- /dev/null +++ b/tests/language/src/Prefix5NegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart"); +class Prefix5NegativeTest { + static Test1() { + // Library prefixes in the imported libraries should not be visible here. + var result = 0; + result += lib11.Library11.static_func(); + Expect.equals(6, result); + result += lib11.Library11.static_fld; + Expect.equals(10, result); + } +} + +main() { + Prefix5NegativeTest.Test1(); +} diff --git a/tests/language/src/Prefix6NegativeTest.dart b/tests/language/src/Prefix6NegativeTest.dart new file mode 100644 index 00000000000..bd075375cc7 --- /dev/null +++ b/tests/language/src/Prefix6NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart", prefix:"lib10"); +class Prefix6NegativeTest { + static Test1() { + // Variables in the local scope hide the library prefix. + var lib10 = 0; + var result = 0; + result += lib10.Library10.static_func(); // This should fail. + } +} + +main() { + Prefix6NegativeTest.Test1(); +} diff --git a/tests/language/src/Prefix7NegativeTest.dart b/tests/language/src/Prefix7NegativeTest.dart new file mode 100644 index 00000000000..90166b90f24 --- /dev/null +++ b/tests/language/src/Prefix7NegativeTest.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#import("library10.dart", prefix:"lib10"); + +// Top level variables cannot shadow library prefixes, they should collide. + +var lib10; + +main() { +} diff --git a/tests/language/src/Prefix8NegativeTest.dart b/tests/language/src/Prefix8NegativeTest.dart new file mode 100644 index 00000000000..93e34779eba --- /dev/null +++ b/tests/language/src/Prefix8NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +// Local variables can shadow class names and hence should result in an +// error. + +class Test { + Test.named(int this.fld); + int fld; +} + +main() { + var Test; + var i = new Test.named(10); // This should be an error. + Expect.equals(10, i.fld); +} diff --git a/tests/language/src/Prefix9NegativeTest.dart b/tests/language/src/Prefix9NegativeTest.dart new file mode 100644 index 00000000000..1d8d9187535 --- /dev/null +++ b/tests/language/src/Prefix9NegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +// Local variables can shadow type parameters and hence should result in an +// error. + +class Test { + Test.named(T this.fld); + T fld; +} + +class Param { + Param.named(int this.fld); + int fld; +} + +main() { + Param test = new Param.named(10); + var Param; + var i = new Test.named(test); // This should be an error. + Expect.equals(10, i.fld.fld); +} diff --git a/tests/language/src/PrefixTest.dart b/tests/language/src/PrefixTest.dart new file mode 100644 index 00000000000..f2255a9a6be --- /dev/null +++ b/tests/language/src/PrefixTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#import("PrefixTest1.dart"); + +class PrefixTest { + static testMain() { + Expect.equals(Prefix.getSource(), Prefix.getImport() + 1); + } +} + +main() { + PrefixTest.testMain(); +} diff --git a/tests/language/src/PrefixTest1.dart b/tests/language/src/PrefixTest1.dart new file mode 100644 index 00000000000..6c1bed99ba4 --- /dev/null +++ b/tests/language/src/PrefixTest1.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("PrefixTest1.dart"); + +#import("PrefixTest2.dart", prefix: "prefix"); +class Prefix { + static final int foo = 43; + + static getSource() { + return foo; + } + + static getImport() { + return prefix.Prefix.foo; + } +} diff --git a/tests/language/src/PrefixTest2.dart b/tests/language/src/PrefixTest2.dart new file mode 100644 index 00000000000..84242e2e426 --- /dev/null +++ b/tests/language/src/PrefixTest2.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library("PrefixTest2.dart"); + +class Prefix { + static final int foo = 42; +} diff --git a/tests/language/src/Private1.dart b/tests/language/src/Private1.dart new file mode 100644 index 00000000000..6841cda7045 --- /dev/null +++ b/tests/language/src/Private1.dart @@ -0,0 +1,90 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing access to private fields. + +main() { + testPrivateTopLevel(); + testPrivateClasses(); +} + +void expectCatch(f) { + bool threw = false; + try { + f(); + } catch (var e) { + threw = true; + } + Expect.equals(true, threw); +} + +String _private1() => "private1"; +final String _private1Field = "private1Field"; + +void testPrivateTopLevel() { + Expect.equals("private1", _private1()); + Expect.equals("private2", _private2()); + Expect.equals("private1Field", _private1Field); + Expect.equals("private2Field", _private2Field); +} + +class _A { + _A() : fieldA = 499; + + int fieldA; +} + +class AExposed extends _A { + AExposed() : super(); +} + +class B { + int _fieldB; + B() : _fieldB = 42; +} + +class C1 { + int _field1; + C1() : _field1 = 499; + + field1a() => _field1; +} + +class C3 extends C2 { + int _field2; + C3() : super(), _field2 = 42; + + field2a() => _field2; + field1c() => _field1; +} + +int c_field1a(c) => c._field1; +int c_field2a(c) => c._field2; + +void testPrivateClasses() { + _A a = new _A(); + Expect.equals(499, a.fieldA); + Expect.equals(499, accessFieldA2(a)); + Expect.equals(499, LibOther3.accessFieldA3(a)); + + var a2 = new AImported(); + Expect.equals(499, a2.getFieldA()); + + B b = new B(); + Expect.equals(42, b._fieldB); + Expect.equals(42, accessFieldB2(b)); + expectCatch(() => LibOther3.accessFieldB3(b)); + + C4 c = new C4(); + Expect.equals(499, c_field1a(c)); + Expect.equals(499, c.field1a()); + Expect.equals(42, c_field2a(c)); + Expect.equals(42, c.field2a()); + Expect.equals(99, LibOther3.c_field1b(c)); + Expect.equals(99, c.field1b()); + Expect.equals(1024, LibOther3.c_field2b(c)); + Expect.equals(1024, c.field2b()); + Expect.equals(499, c.field1c()); + Expect.equals(99, c.field1d()); +} diff --git a/tests/language/src/Private2.dart b/tests/language/src/Private2.dart new file mode 100644 index 00000000000..793e83b6402 --- /dev/null +++ b/tests/language/src/Private2.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing access to private fields. + +String _private2() { return "private2"; } +final String _private2Field = "private2Field"; + +accessFieldA2(_A a) { return a.fieldA; } +accessFieldB2(B b) { return b._fieldB; } diff --git a/tests/language/src/Private2Lib.dart b/tests/language/src/Private2Lib.dart new file mode 100644 index 00000000000..0443f26751b --- /dev/null +++ b/tests/language/src/Private2Lib.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields across class hierarchies. + +class B extends A { + B() : super(); +} diff --git a/tests/language/src/Private2Lib.lib b/tests/language/src/Private2Lib.lib new file mode 100644 index 00000000000..41e1dd1f4aa --- /dev/null +++ b/tests/language/src/Private2Lib.lib @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields across class hierarchies. + +#library("Private2Lib"); + +#import("Private2Test.dart"); +#source("Private2Lib.dart"); diff --git a/tests/language/src/Private2Main.dart b/tests/language/src/Private2Main.dart new file mode 100644 index 00000000000..a39ff70b282 --- /dev/null +++ b/tests/language/src/Private2Main.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields across class hierarchies. + +class A { + var _f; + var g; + A() : _f = 42, g = 43; +} + +class C extends B { + C() : super(); +} + +main() { + var a = new A(); + print(a.g); + print(a._f); + var o = new C(); + print(o.g); // Access to public field in A. + print(o._f); // Access to private field in A is allowed. +} diff --git a/tests/language/src/Private2Test.dart b/tests/language/src/Private2Test.dart new file mode 100644 index 00000000000..3560a9d7f3f --- /dev/null +++ b/tests/language/src/Private2Test.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields across class hierarchies. + +#library("Private2Test"); + +#import("Private2Lib.lib"); +#source("Private2Main.dart"); diff --git a/tests/language/src/Private3.dart b/tests/language/src/Private3.dart new file mode 100644 index 00000000000..93a3d415040 --- /dev/null +++ b/tests/language/src/Private3.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing access to private fields. + +class LibOther3 { + static accessFieldA3(var a) => a.fieldA; + static accessFieldB3(var b) => b._fieldB; + static int c_field1b(c) => c._field1; + static int c_field2b(c) => c._field2; +} + +class AImported extends AExposed { + AImported() : super(); + getFieldA() => fieldA; +} + +class C2 extends C1 { + int _field1; + C2() : super(), _field1 = 99; + + field1b() => _field1; +} + +class C4 extends C3 { + int _field2; + C4() : super(), _field2 = 1024; + + field2b() => _field2; + field1d() => _field1; +} diff --git a/tests/language/src/Private3Test.dart b/tests/language/src/Private3Test.dart new file mode 100644 index 00000000000..15f32184f71 --- /dev/null +++ b/tests/language/src/Private3Test.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields. + +#import("PrivateLib"); + +#source("PrivateMain.dart"); +#source("PrivateOther.dart"); diff --git a/tests/language/src/PrivateFactoryResolutionNegativeTest.dart b/tests/language/src/PrivateFactoryResolutionNegativeTest.dart new file mode 100644 index 00000000000..92b07c99ab2 --- /dev/null +++ b/tests/language/src/PrivateFactoryResolutionNegativeTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class PrivateFactoryResolutionTest { + + static testMain() { + new TypeError._uninstantiable(); + } +} + +main() { + PrivateFactoryResolutionNegativeTest.testMain(); +} diff --git a/tests/language/src/PrivateLib b/tests/language/src/PrivateLib new file mode 100644 index 00000000000..b8f8d3a2f7c --- /dev/null +++ b/tests/language/src/PrivateLib @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields. + +#library("PrivateLib"); + +#source("PrivateLib.dart"); diff --git a/tests/language/src/PrivateLib.dart b/tests/language/src/PrivateLib.dart new file mode 100644 index 00000000000..cb9331e6d95 --- /dev/null +++ b/tests/language/src/PrivateLib.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields. + +class PrivateLib { + + final _myPrecious; + + const PrivateLib() : this._myPrecious = "The Ring"; + +} diff --git a/tests/language/src/PrivateMain.dart b/tests/language/src/PrivateMain.dart new file mode 100644 index 00000000000..371eb425807 --- /dev/null +++ b/tests/language/src/PrivateMain.dart @@ -0,0 +1,57 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields. + +main() { + PrivateMain.main(); +} + +class PrivateMain { + + static final _myPrecious = "A Ring"; + + static accessMyPrivates() { + var value = 0; + try { + value = _myPrecious; + } catch (var e) { + value = -1; + } + Expect.equals("A Ring", value); + } + + static accessMyLibPrivates() { + var value = 0; + var the_other = new PrivateOther(); + try { + value = the_other._myPrecious; + } catch (var e, var trace) { + print(e); + print(trace); + Expect.equals(true, e is NoSuchMethodException); + value = -1; + } + Expect.equals("Another Ring", value); + } + + static accessOtherLibPrivates() { + var value = 0; + var the_other = new PrivateLib(); + try { + value = the_other._myPrecious; + } catch (var e, var trace) { + print(e); + print(trace); + Expect.equals(true, e is NoSuchMethodException); + value = -1; + } + Expect.equals(-1, value); + } + + static main() { + accessMyPrivates(); + accessMyLibPrivates(); + accessOtherLibPrivates(); + } +} diff --git a/tests/language/src/PrivateOther.dart b/tests/language/src/PrivateOther.dart new file mode 100644 index 00000000000..c4e19ec7e04 --- /dev/null +++ b/tests/language/src/PrivateOther.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing access to private fields. + +class PrivateOther { + + final _myPrecious; + + const PrivateOther() : this._myPrecious = "Another Ring"; + +} diff --git a/tests/language/src/PrivateOther.lib b/tests/language/src/PrivateOther.lib new file mode 100644 index 00000000000..4e5bb84a896 --- /dev/null +++ b/tests/language/src/PrivateOther.lib @@ -0,0 +1,10 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing access to private fields. + +#library("PrivateOther"); + +#import("PrivateTest.dart"); +#source("Private3.dart"); diff --git a/tests/language/src/PrivateTest.dart b/tests/language/src/PrivateTest.dart new file mode 100644 index 00000000000..218bb270d02 --- /dev/null +++ b/tests/language/src/PrivateTest.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing access to private fields. + +#import("PrivateOther.lib"); +#source("Private1.dart"); +#source("Private2.dart"); diff --git a/tests/language/src/PseudoKWNegativeTest.dart b/tests/language/src/PseudoKWNegativeTest.dart new file mode 100644 index 00000000000..6cc71fb04b2 --- /dev/null +++ b/tests/language/src/PseudoKWNegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that we cannot use a pseudo keyword at the class level code. + +// Using pseudo kw 'operator' as class name is not allowed. +class operator { +} + +class PseudoKWNegativeTest { + + static testMain() { + return 0; + } +} + + +main() { + PseudoKWNegativeTest.testMain(); +} diff --git a/tests/language/src/PseudoKWTest.dart b/tests/language/src/PseudoKWTest.dart new file mode 100644 index 00000000000..b0fc30bb27a --- /dev/null +++ b/tests/language/src/PseudoKWTest.dart @@ -0,0 +1,46 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that we can use pseudo keywords as names in function level code. + + +class PseudoKWTest { + static testMain() { + + // This list is taken from the 'identifier' production + // of the Dart grammar. It lists all the pseudo-keywords + // that are legal identifiers at the function level. + + var abstract = 0; + var class = 0; + var extends = 0; + var factory = 0; + var get = 0; + var implements = 0; + var import = 0; + var interface = 0; + var library = 0; + var native = 0; + var negate = 0; + var operator = 0; + var set = 0; + var source = 0; + var static = 0; + { + void factory(set) { + return 0; + } + } + + get: while (extends > 0) { + break get; + } + + return static + library * class; + } +} + + +main() { + PseudoKWTest.testMain(); +} diff --git a/tests/language/src/RawStringTest.dart b/tests/language/src/RawStringTest.dart new file mode 100644 index 00000000000..6e95d40424a --- /dev/null +++ b/tests/language/src/RawStringTest.dart @@ -0,0 +1,40 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class RawStringTest { + static testMain() { + Expect.equals("abcd", @"abcd"); + Expect.equals("", @""); + Expect.equals("", @''); + Expect.equals("", @""""""); + Expect.equals("", @''''''); + Expect.equals("''''", @"''''"); + Expect.equals('""""', @'""""'); + Expect.equals("1\n2\n3", @"""1 +2 +3"""); + Expect.equals("1\n2\n3", @'''1 +2 +3'''); + Expect.equals("1", @""" +1"""); + Expect.equals("1", @''' +1'''); + Expect.equals("'", @"'"); + Expect.equals('"', @'"'); + Expect.equals("1", @"1"); + Expect.equals("1", @"1"); + Expect.equals("\$", @"$"); + Expect.equals("\\", @"\"); + Expect.equals("\\", @'\'); + Expect.equals("\${12}", @"${12}"); + Expect.equals("\\a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m", + @"\a\b\c\d\e\f\g\h\i\j\k\l\m"); + Expect.equals("\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z", + @"\n\o\p\q\r\s\t\u\v\w\x\y\z"); + } +} +main() { + RawStringTest.testMain(); +} diff --git a/tests/language/src/RegEx2Test.dart b/tests/language/src/RegEx2Test.dart new file mode 100644 index 00000000000..fffa6227f15 --- /dev/null +++ b/tests/language/src/RegEx2Test.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing regular expressions in Dart. + +class RegEx2Test { + static void testMain() { + final helloPattern = new RegExp("with (hello)", ""); + String s = "this is a string with hello somewhere"; + Match match = helloPattern.firstMatch(s); + if (match != null) { + print("got match"); + int groupCount = match.groupCount(); + print("groupCount is " + groupCount); + print("group 0 is " + match.group(0)); + print("group 1 is " + match.group(1)); + } else { + print("match not round"); + } + print("done"); + } +} + +main() { + RegEx2Test.testMain(); +} diff --git a/tests/language/src/RegExp1Test.dart b/tests/language/src/RegExp1Test.dart new file mode 100644 index 00000000000..a4e7a94ba18 --- /dev/null +++ b/tests/language/src/RegExp1Test.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing regular expressions in Dart. + +class RegExp1Test { + static testMain() { + RegExp exp1 = const RegExp("bar|foo", ""); + Expect.equals(true, exp1.hasMatch("foo")); + Expect.equals(true, exp1.hasMatch("bar")); + Expect.equals(false, exp1.hasMatch("gim")); + Expect.equals(true, exp1.hasMatch("just foo")); + Expect.equals("bar|foo", exp1.pattern); + Expect.equals("", exp1.flags); + + RegExp exp2 = const RegExp("o+", "i"); + Expect.equals(true, exp2.hasMatch("this looks good")); + Expect.equals(true, exp2.hasMatch("fOO")); + Expect.equals(false, exp2.hasMatch("bar")); + Expect.equals("o+", exp2.pattern); + Expect.equals("i", exp2.flags); + } +} + +main() { + RegExp1Test.testMain(); +} diff --git a/tests/language/src/RegExp2Test.dart b/tests/language/src/RegExp2Test.dart new file mode 100644 index 00000000000..18d27c39784 --- /dev/null +++ b/tests/language/src/RegExp2Test.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing regular expressions in Dart. + +class RegExp2Test { + static String findImageTag_(String text, String extensions) { + final re = new RegExp('src="(http://\\S+\\.(${extensions}))"', ''); + print('REGEXP findImageTag_ ' + extensions + ' text: \n' + text); + final match = re.firstMatch(text); + print('REGEXP findImageTag_ ' + extensions + ' SUCCESS'); + if (match != null) { + return match[1]; + } else { + return null; + } + } + + + static testMain() { + String text = '''

My last entry was in December of 2009. I suppose I never was particularly good about updating this thing, but it seems a bit ridiculous that I couldn't be bothered to post once about the many, many things that have gone on since then. My apologies. I guess I could start by saying that the world looks like a very different place than it did back in second year.

+ +'''; + String extensions = 'jpg|jpeg|png'; + String tag = findImageTag_(text, extensions); + Expect.equals(true, tag !== null); + } +} + +main() { + RegExp2Test.testMain(); +} diff --git a/tests/language/src/RegExp3Test.dart b/tests/language/src/RegExp3Test.dart new file mode 100644 index 00000000000..3edd36dfbae --- /dev/null +++ b/tests/language/src/RegExp3Test.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing regular expressions in Dart. + +class RegExp3Test { + static testMain() { + var i = 2000; + try { + RegExp exp = new RegExp("[", ""); + i = 100; // Should not reach here. + } catch (IllegalJSRegExpException e) { + i = 0; + } + Expect.equals(0, i); + } +} + +main() { + RegExp3Test.testMain(); +} diff --git a/tests/language/src/RegExpTest.dart b/tests/language/src/RegExpTest.dart new file mode 100644 index 00000000000..8aa96e30a9d --- /dev/null +++ b/tests/language/src/RegExpTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing regular expressions in Dart. + +class RegExpTest { + static test1() { + RegExp exp = const RegExp("(\\w+)", ""); + String str = "Parse my string"; + List matches = new List.from(exp.allMatches(str)); + Expect.equals(3, matches.length); + Expect.equals("Parse", matches[0].group(0)); + Expect.equals("my", matches[1].group(0)); + Expect.equals("string", matches[2].group(0)); + } + + static testMain() { + test1(); + } +} + +main() { + RegExpTest.testMain(); +} diff --git a/tests/language/src/ResolveTest.dart b/tests/language/src/ResolveTest.dart new file mode 100644 index 00000000000..5276158cea2 --- /dev/null +++ b/tests/language/src/ResolveTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing resolving of dynamic and static calls. + +class A { + static staticCall() { return 4; } + dynamicCall() { return 5; } + ovrDynamicCall() { return 6; } +} + +class B extends A { + ovrDynamicCall() { return -6; } +} + +class ResolveTest { + static testMain() { + var b = new B(); + Expect.equals(3, (b.dynamicCall() + A.staticCall() + b.ovrDynamicCall())); + } +} + +main() { + ResolveTest.testMain(); +} diff --git a/tests/language/src/SavannahTest.dart b/tests/language/src/SavannahTest.dart new file mode 100644 index 00000000000..147f19b46d3 --- /dev/null +++ b/tests/language/src/SavannahTest.dart @@ -0,0 +1,84 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test using an identity hash. + +interface BigGame { + final String name; +} + +class Giraffe implements BigGame { + final String name; + final int identityHash_; + + Giraffe(this.name) : identityHash_ = nextId() {} + + int hashCode() { + return identityHash_; + } + + // Calculate identity hash for a giraffe. + static int nextId_; + static int nextId() { + if (nextId_ == null) { + nextId_ = 17; + } + return nextId_++; + } +} + +class Zebra implements BigGame { + final String name; + Zebra(this.name) {} +} + + +class SavannahTest { + + static void testMain() { + Map savannah = new Map(); + Giraffe giraffe1 = new Giraffe("Tony"); + Giraffe giraffe2 = new Giraffe("Rose"); + savannah[giraffe1] = giraffe1.name; + savannah[giraffe2] = giraffe2.name; + + var count = savannah.length; + print("getCount is $count"); + Expect.equals(2, count); + print("giraffe1: " + savannah[giraffe1]); + print("giraffe2: " + savannah[giraffe2]); + Expect.equals("Tony", savannah[giraffe1]); + Expect.equals("Rose", savannah[giraffe2]); + + bool caught = false; + Zebra zebra1 = new Zebra("Paul"); + Zebra zebra2 = new Zebra("Joe"); + try { + savannah[zebra1] = zebra1.name; + savannah[zebra2] = zebra2.name; + } catch (NoSuchMethodException e) { + print("Caught: $e"); + caught = true; + } + Expect.equals(true, caught); + + count = savannah.length; + print("getCount is $count"); + Expect.equals(2, count); + + caught = false; + try { + print("zebra1: " + savannah[zebra1]); + print("zebra2: " + savannah[zebra2]); + } catch (NoSuchMethodException e) { + print("Caught: $e"); + caught = true; + } + Expect.equals(true, caught); + } + +} + +main() { + SavannahTest.testMain(); +} diff --git a/tests/language/src/ScannerTest.dart b/tests/language/src/ScannerTest.dart new file mode 100644 index 00000000000..5bd33495905 --- /dev/null +++ b/tests/language/src/ScannerTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test dart scanner. + +class ScannerTest { + static testMain() { + var s = "Hello\tmy\tfriend\n"; + return s; + } +} +main() { + ScannerTest.testMain(); +} diff --git a/tests/language/src/ScopeNegativeTest.dart b/tests/language/src/ScopeNegativeTest.dart new file mode 100644 index 00000000000..5278880af1e --- /dev/null +++ b/tests/language/src/ScopeNegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing the prohibited use of a variable before it has +// been declared, which is not trivial to detect in the context of a variable +// declaration shadowing another one. + +class ScopeNegativeTest { + static testMain() { + var a = 1; + { + var b = 2; + var c = a; // Use of 'a' prior to its shadow declaration below. + var d = b + c; + var a = 5; // Shadow declaration of 'a'. + return d + a; + } + } +} + + +main() { + ScopeNegativeTest.testMain(); +} diff --git a/tests/language/src/ScopeVariableTest.dart b/tests/language/src/ScopeVariableTest.dart new file mode 100644 index 00000000000..7dc22888a9f --- /dev/null +++ b/tests/language/src/ScopeVariableTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class ScopeVariableTest { + + static void testSimpleScope() { + { + var a = "Test"; + int b = 1; + } + { + var c; + int d; + Expect.equals(true, c === null); + Expect.equals(true, d === null); + } + } + + static void testShadowingScope() { + var a = "Test"; + { + var a; + Expect.equals(true, a === null); + a = "a"; + Expect.equals(true, a == "a"); + } + Expect.equals(true, a == "Test"); + } + + static void testMain() { + testSimpleScope(); + testShadowingScope(); + } +} + +main() { + ScopeVariableTest.testMain(); +} diff --git a/tests/language/src/Script1NegativeLib.dart b/tests/language/src/Script1NegativeLib.dart new file mode 100644 index 00000000000..e0b7e83ae45 --- /dev/null +++ b/tests/language/src/Script1NegativeLib.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library has wrong order of import and source tags. + +#library("Script1NegativeLib"); +#source("ScriptSource.dart"); +#import("ScriptLib.dart"); + +class A { + var a; +} diff --git a/tests/language/src/Script1NegativeTest.dart b/tests/language/src/Script1NegativeTest.dart new file mode 100644 index 00000000000..c5172f7dda6 --- /dev/null +++ b/tests/language/src/Script1NegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library has wrong order of import and source tags. + +#import("Script1NegativeLib.dart"); + +main() { + print("Should not reach here."); +} diff --git a/tests/language/src/Script2NegativeLib.dart b/tests/language/src/Script2NegativeLib.dart new file mode 100644 index 00000000000..58e977f640e --- /dev/null +++ b/tests/language/src/Script2NegativeLib.dart @@ -0,0 +1,13 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library has source file with library tags. + +#library("Script2NegativeLib"); +#import("ScriptLib.dart"); +#source("Script2NegativeSource.dart"); + +class A { + var a; +} diff --git a/tests/language/src/Script2NegativeSource.dart b/tests/language/src/Script2NegativeSource.dart new file mode 100644 index 00000000000..1b2d099dce7 --- /dev/null +++ b/tests/language/src/Script2NegativeSource.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library has source file with library tags. + +#library("Script2NegativeSource"); + +final int script_2_negative_source = 1; diff --git a/tests/language/src/Script2NegativeTest.dart b/tests/language/src/Script2NegativeTest.dart new file mode 100644 index 00000000000..e9c42cccf8d --- /dev/null +++ b/tests/language/src/Script2NegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library has source file with library tags. + +#import("Script2NegativeLib.dart"); + +main() { + print("Should not reach here."); +} diff --git a/tests/language/src/ScriptLib.dart b/tests/language/src/ScriptLib.dart new file mode 100644 index 00000000000..f0b0a81fec9 --- /dev/null +++ b/tests/language/src/ScriptLib.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A perfectly legal dart library for use with script and library tests. + +#library("ScriptLib"); + +final int script_lib = 1; diff --git a/tests/language/src/ScriptNegativeLib.dart b/tests/language/src/ScriptNegativeLib.dart new file mode 100644 index 00000000000..72ea4f91969 --- /dev/null +++ b/tests/language/src/ScriptNegativeLib.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class A { + var a; +} diff --git a/tests/language/src/ScriptNegativeTest.dart b/tests/language/src/ScriptNegativeTest.dart new file mode 100644 index 00000000000..984a443e11f --- /dev/null +++ b/tests/language/src/ScriptNegativeTest.dart @@ -0,0 +1,11 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Imported library does not start with a library tag. + +#import("ScriptNegativeLib.dart"); + +main() { + print("Should not reach here."); +} diff --git a/tests/language/src/ScriptSource.dart b/tests/language/src/ScriptSource.dart new file mode 100644 index 00000000000..15f23dbcd31 --- /dev/null +++ b/tests/language/src/ScriptSource.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A perfectly legal dart source file for use with script and library tests. + +final int script_source = 1; diff --git a/tests/language/src/SecondTest.dart b/tests/language/src/SecondTest.dart new file mode 100644 index 00000000000..a60941df5f3 --- /dev/null +++ b/tests/language/src/SecondTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Second dart test program. + +class Helper { + static empty() { } + static int foo() { return 42; } +} + +class SecondTest { + static testMain() { + Helper.empty(); + Expect.equals(42, Helper.foo()); + } +} + + +main() { + SecondTest.testMain(); +} diff --git a/tests/language/src/Setter0Test.dart b/tests/language/src/Setter0Test.dart new file mode 100644 index 00000000000..6b0502d75f7 --- /dev/null +++ b/tests/language/src/Setter0Test.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing setting/getting of fields when +// only getter/setter methods are specified. + +class First { + First(int val) : a_ = val { } + int a_; +} + +class Second extends First { + static int c; + + Second(int val) : super(val) { } + + static void testStaticMethod() { + int i; + Second.static_a = 20; + i = Second.c; + } + + void set instance_a(int value) { + a_ = a_ + value; + } + int get instance_a() { + return a_; + } + + static void set static_a(int value) { + Second.c = value; + } + + static int get static_d() { + return Second.c; + } +} + +class Setter0Test { + static testMain() { + Second obj = new Second(10); + Expect.equals(10, obj.instance_a); + obj.instance_a = 20; + Expect.equals(30, obj.instance_a); + + Second.testStaticMethod(); + Expect.equals(20, Second.c); + Expect.equals(20, Second.static_d); + } +} + + +main() { + Setter0Test.testMain(); +} diff --git a/tests/language/src/Setter1Test.dart b/tests/language/src/Setter1Test.dart new file mode 100644 index 00000000000..1a14bdfca3f --- /dev/null +++ b/tests/language/src/Setter1Test.dart @@ -0,0 +1,96 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing setting/getting of fields when +// only getter/setter methods are specified. + +class First { + First(int val) : a_ = val { } + + void testMethod() { + a = 20; + } + static void testStaticMethod() { + b = 20; + } + + int get a() { + return a_; + } + void set a(int val) { + a_ = a_ + val; + } + + static int get b() { + return b_; + } + static void set b(int val) { + b_ = val; + } + + int a_; + static int b_; +} + + +class Second { + static int c; + int a_; + + Second(int value) : a_ = value { } + + void testMethod() { + a = 20; + } + + static void testStaticMethod() { + int i; + b = 20; + i = d; + // TODO(asiva): Turn these on once we have error handling. + // i = b; // Should be an error. + // d = 40; // Should be an error. + } + + int get a() { + return a_; + } + void set a(int value) { + a_ = a_ + value; + } + + static void set b(int value) { + Second.c = value; + } + static int get d() { + return Second.c; + } +} + + +class Setter1Test { + static testMain() { + First obj1 = new First(10); + Expect.equals(10, obj1.a); + obj1.testMethod(); + Expect.equals(30, obj1.a); + First.b = 10; + Expect.equals(10, First.b); + First.testStaticMethod(); + Expect.equals(20, First.b); + + Second obj = new Second(10); + Expect.equals(10, obj.a); + obj.testMethod(); + Expect.equals(30, obj.a); + + Second.testStaticMethod(); + Expect.equals(20, Second.c); + Expect.equals(20, Second.d); + } +} + + +main() { + Setter1Test.testMain(); +} diff --git a/tests/language/src/Setter2Test.dart b/tests/language/src/Setter2Test.dart new file mode 100644 index 00000000000..bdfc8a60608 --- /dev/null +++ b/tests/language/src/Setter2Test.dart @@ -0,0 +1,42 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing use of 'this' in an instance method. + +class Nested { + Nested(int val) : a = val { } + int a; + int foo(int i) { + return i; + } +} + +class Second { + int a; + static Nested obj; + + Second(int val) { } + + void bar(int value) { + a = value; + Second.obj.a = Second.obj.foo(this.a); + this.a = 100; + Expect.equals(100, a); + } +} + +class Setter2Test { + static testMain() { + Second obj = new Second(10); + Second.obj = new Nested(10); + Second.obj.a = 10; + Expect.equals(10, Second.obj.a); + Expect.equals(10, Second.obj.foo(10)); + obj.bar(20); + Expect.equals(20, Second.obj.a); + } +} + +main() { + Setter2Test.testMain(); +} diff --git a/tests/language/src/StackOverflowTest.dart b/tests/language/src/StackOverflowTest.dart new file mode 100644 index 00000000000..c1fdd49ad7d --- /dev/null +++ b/tests/language/src/StackOverflowTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart program testing stack overflow. + +class StackOverflowTest { + + static void curseTheRecurse(a, b, c) { + curseTheRecurse(b, c, a); + } + + static void testMain() { + bool exceptionCaught = false; + try { + curseTheRecurse(1, 2, 3); + } catch (StackOverflowException e) { + exceptionCaught = true; + } + Expect.equals(true, exceptionCaught); + } +} + +main() { + StackOverflowTest.testMain(); +} diff --git a/tests/language/src/StackTraceTest.dart b/tests/language/src/StackTraceTest.dart new file mode 100644 index 00000000000..ac507272ec3 --- /dev/null +++ b/tests/language/src/StackTraceTest.dart @@ -0,0 +1,86 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException { + const MyException(String message) : message_ = message; + final String message_; +} + +class Helper { + static int f1(int i) { + try { + i = func(); + i = 10; + } catch (MyException exception, var stacktrace) { + i = 50; + print(exception.message_); + Expect.equals((stacktrace != null), true); + print(stacktrace); + } + try { + int j; + i = func1(); + i = 200; + } catch (MyException exception, var stacktrace) { + i = 50; + print(exception.message_); + Expect.equals((stacktrace != null), true); + print(stacktrace); + } + try { + int j; + i = func2(); + i = 200; + } catch (MyException exception, var stacktrace) { + i = 50; + print(exception.message_); + Expect.equals((stacktrace != null), true); + print(stacktrace); + } finally { + i = i + 800; + } + return i; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException("Exception Test for stack trace being printed"); + } + return 10; + } + + static int func1() { + try { + func(); + } catch (MyException exception) { + throw new MyException("Exception Test for stack trace being printed");; + } + return 10; + } + + static int func2() { + try { + func(); + } catch (MyException exception) { + throw; + } + return 10; + } + +} + +class StackTraceTest { + static testMain() { + Expect.equals(850, Helper.f1(1)); + } +} + +main() { + StackTraceTest.testMain(); +} diff --git a/tests/language/src/StatementTest.dart b/tests/language/src/StatementTest.dart new file mode 100644 index 00000000000..32d472d6f24 --- /dev/null +++ b/tests/language/src/StatementTest.dart @@ -0,0 +1,209 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests all statement types. Not an exhaustive test of all statement semantics. +class StatementTest { + + StatementTest() {} + + static testMain() { + var test = new StatementTest(); + test.testIfStatement(); + test.testForLoop(); + test.testWhileLoops(); + test.testSwitch(); + test.testExceptions(); + test.testBreak(); + test.testContinue(); + test.testFunction(); + test.testReturn(); + } + + testIfStatement() { + // Basic if statements. + if (true) { + Expect.equals(true, true); + } else { + Expect.equals(false, true); + } + + if (false) { + Expect.equals(false, true); + } else { + Expect.equals(true, true); + } + } + + testForLoop() { + int count = 0, count2; + + // Basic for loop. + for (int i = 0; i < 10; ++i) { + ++count; + } + Expect.equals(10, count); + + // For loop with no 'var'. + count2 = 0; + for (count = 0; count < 5; ++count) { + ++count2; + } + Expect.equals(5, count); + Expect.equals(5, count2); + + // For loop with no initializer. + count = count2 = 0; + for (; count < 10; ++count) { + ++count2; + } + Expect.equals(10, count); + Expect.equals(10, count2); + + // For loop with no increment. + for (count = 0; count < 5; ) { + ++count; + } + Expect.equals(5, count); + + // For loop with no test. + for (count = 0; ; ++count) { + if (count == 10) { + break; + } + } + Expect.equals(10, count); + + // For loop with no nothing. + count = 0; + for (;;) { + if (count == 5) { + break; + } + ++count; + } + Expect.equals(5, count); + } + + testWhileLoops() { + // Basic while loop. + int count = 0; + while (count < 10) { + ++count; + } + Expect.equals(10, count); + + // Basic do loop. + count = 0; + do { + ++count; + } while (count < 5); + Expect.equals(5, count); + } + + testSwitch() { + // Int switch. + bool hit0, hit1, hitDefault; + for (int x = 0; x < 3; ++x) { + switch (x) { + case 0: hit0 = true; break; + case 1: hit1 = true; break; + default: hitDefault = true; break; + } + } + Expect.equals(true, hit0); + Expect.equals(true, hit1); + Expect.equals(true, hitDefault); + + // String switch. + var strings = ['a', 'b', 'c']; + bool hitA, hitB; + hitDefault = false; + for (int x = 0; x < 3; ++x) { + switch (strings[x]) { + case 'a': hitA = true; break; + case 'b': hitB = true; break; + default: hitDefault = true; break; + } + } + Expect.equals(true, hitA); + Expect.equals(true, hitB); + Expect.equals(true, hitDefault); + } + + testExceptions() { + // TODO(jgw): Better tests once all the exception semantics are worked out. + bool hitCatch, hitFinally; + try { + throw "foo"; + } catch (var e) { + Expect.equals(true, e == "foo"); + hitCatch = true; + } finally { + hitFinally = true; + } + + Expect.equals(true, hitCatch); + Expect.equals(true, hitFinally); + } + + testBreak() { + var ints = [ + [ 32, 87, 3, 589 ], + [ 12, 1076, 2000, 8 ], + [ 622, 127, 77, 955 ] + ]; + int i, j = 0; + bool foundIt = false; + + search: + for (i = 0; i < ints.length; i++) { + for (j = 0; j < ints[i].length; j++) { + if (ints[i][j] == 12) { + foundIt = true; + break search; + } + } + } + Expect.equals(true, foundIt); + } + + testContinue() { + String searchMe = "Look for a substring in me"; + String substring = "sub"; + bool foundIt = false; + int max = searchMe.length - substring.length; + + test: + for (int i = 0; i <= max; i++) { + int n = substring.length; + int j = i; + int k = 0; + while (n-- != 0) { + if (searchMe[j++] != substring[k++]) { + continue test; + } + } + foundIt = true; + break test; + } + } + + testFunction() { + int foo() { + return 42; + } + Expect.equals(42, foo()); + } + + void testReturn() { + if (true) { + return; + } + Expect.equals(true, false); + } +} + +main() { + StatementTest.testMain(); +} diff --git a/tests/language/src/StaticCallWrongArgumentCountNegativeTest.dart b/tests/language/src/StaticCallWrongArgumentCountNegativeTest.dart new file mode 100644 index 00000000000..2bc05099657 --- /dev/null +++ b/tests/language/src/StaticCallWrongArgumentCountNegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test mismatch in argument counts. + +class StaticCallWrongArgumentCountNegativeTest { + static void testMain() { + Niesen.goodCall(1, 2, 3); + // Bad call. + Niesen.goodCall(1, 2, 3, 4); + } +} + +class Niesen { + static int goodCall(int a, int b, int c) { + return a + b; + } +} + +main() { + StaticCallWrongArgumentCountNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField1RunNegativeTest.dart b/tests/language/src/StaticField1RunNegativeTest.dart new file mode 100644 index 00000000000..fc6ddbab00d --- /dev/null +++ b/tests/language/src/StaticField1RunNegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static field cannot be read as an instance field. + +class Foo { + Foo() {} + static var x; +} + +class StaticField1RunNegativeTest { + static testMain() { + var foo = new Foo(); + var x = foo.x; + } +} + +main() { + StaticField1RunNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField1Test.dart b/tests/language/src/StaticField1Test.dart new file mode 100644 index 00000000000..a365048c579 --- /dev/null +++ b/tests/language/src/StaticField1Test.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static field cannot be read as an instance field. + +class Foo { + Foo() {} + static var x; +} + +class StaticField1Test { + static testMain() { + if (false) { + var foo = new Foo(); + var x = foo.x; + } + } +} + +main() { + StaticField1Test.testMain(); +} diff --git a/tests/language/src/StaticField1aRunNegativeTest.dart b/tests/language/src/StaticField1aRunNegativeTest.dart new file mode 100644 index 00000000000..5b4f44e0303 --- /dev/null +++ b/tests/language/src/StaticField1aRunNegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static method cannot be read as an instance field. + +class Foo { + Foo() {} + static void m() {} +} + +class StaticField1aRunNegativeTest { + static testMain() { + var foo = new Foo(); + var m = foo.m; + } +} + +main() { + StaticField1aRunNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField1aTest.dart b/tests/language/src/StaticField1aTest.dart new file mode 100644 index 00000000000..03a9aa1e28b --- /dev/null +++ b/tests/language/src/StaticField1aTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static method cannot be read as an instance field. + +class Foo { + Foo() {} + static void m() {} +} + +class StaticField1aTest { + static testMain() { + if (false) { + var foo = new Foo(); + var m = foo.m; + } + } +} + +main() { + StaticField1aTest.testMain(); +} diff --git a/tests/language/src/StaticField2RunNegativeTest.dart b/tests/language/src/StaticField2RunNegativeTest.dart new file mode 100644 index 00000000000..fa1fe9a0acb --- /dev/null +++ b/tests/language/src/StaticField2RunNegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static field cannot be set as an instance field. + +class Foo { + Foo() {} + static var x; +} + +class StaticField2RunNegativeTest { + static testMain() { + var foo = new Foo(); + foo.x = 1; + } +} + +main() { + StaticField2RunNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField2Test.dart b/tests/language/src/StaticField2Test.dart new file mode 100644 index 00000000000..23d0dbdc9ed --- /dev/null +++ b/tests/language/src/StaticField2Test.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static field cannot be set as an instance field. + +class Foo { + Foo() {} + static var x; +} + +class StaticField2Test { + static testMain() { + if (false) { + var foo = new Foo(); + foo.x = 1; + } + } +} + +main() { + StaticField2Test.testMain(); +} diff --git a/tests/language/src/StaticField2aRunNegativeTest.dart b/tests/language/src/StaticField2aRunNegativeTest.dart new file mode 100644 index 00000000000..cf45187149b --- /dev/null +++ b/tests/language/src/StaticField2aRunNegativeTest.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static method cannot be set as an instance field. + +class Foo { + Foo() {} + static void m() {} +} + +class StaticField2aRunNegativeTest { + static testMain() { + var foo = new Foo(); + foo.m = 1; + } +} + +main() { + StaticField2aRunNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField2aTest.dart b/tests/language/src/StaticField2aTest.dart new file mode 100644 index 00000000000..34a35bd50a4 --- /dev/null +++ b/tests/language/src/StaticField2aTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a static method cannot be set as an instance field. + +class Foo { + Foo() {} + static void m() {} +} + +class StaticField2aTest { + static testMain() { + if (false) { + var foo = new Foo(); + foo.m = 1; + } + } +} + +main() { + StaticField2aTest.testMain(); +} diff --git a/tests/language/src/StaticField3NegativeTest.dart b/tests/language/src/StaticField3NegativeTest.dart new file mode 100644 index 00000000000..2e3bc6a9243 --- /dev/null +++ b/tests/language/src/StaticField3NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that an instance field cannot be read as a static field. + +class Foo { + Foo() {} + var x; +} + +class StaticField3NegativeTest { + static testMain() { + if (false) { + var x = Foo.x; + } + } +} + +main() { + StaticField3NegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField3aNegativeTest.dart b/tests/language/src/StaticField3aNegativeTest.dart new file mode 100644 index 00000000000..cd10efcb14f --- /dev/null +++ b/tests/language/src/StaticField3aNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that an instance method cannot be read as a static field. + +class Foo { + Foo() {} + void m() {} +} + +class StaticField3aNegativeTest { + static testMain() { + if (false) { + var m = Foo.m; + } + } +} + +main() { + StaticField3aNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField4NegativeTest.dart b/tests/language/src/StaticField4NegativeTest.dart new file mode 100644 index 00000000000..bdd5626b65a --- /dev/null +++ b/tests/language/src/StaticField4NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that an instance field cannot be set as a static field. + +class Foo { + Foo() {} + var x; +} + +class StaticField4NegativeTest { + static testMain() { + if (false) { + Foo.x = 1; + } + } +} + +main() { + StaticField4NegativeTest.testMain(); +} diff --git a/tests/language/src/StaticField4aNegativeTest.dart b/tests/language/src/StaticField4aNegativeTest.dart new file mode 100644 index 00000000000..ad315b9ab72 --- /dev/null +++ b/tests/language/src/StaticField4aNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that an instance method cannot be set as a static field. + +class Foo { + Foo() {} + void m() {} +} + +class StaticField4aNegativeTest { + static testMain() { + if (false) { + Foo.m = 1; + } + } +} + +main() { + StaticField4aNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticFieldTest.dart b/tests/language/src/StaticFieldTest.dart new file mode 100644 index 00000000000..38883fd6714 --- /dev/null +++ b/tests/language/src/StaticFieldTest.dart @@ -0,0 +1,76 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing setting/getting/initializing static fields. + +class First { + First() {} + static var a; + static var b; + static final int c = 1; + static setValues() { + a = 24; + b = 10; + return a + b + c; + } +} + +class Second extends First { + static void testUnqualifiedStatic() { + setValues(); // static function in superclass. + Expect.equals(24, a); // static field in superclass. + Expect.equals(24, First.a); // same field as above. + } +} + +class InitializerTest { + static var one; + static var two = 2; + static var three = 2; + + static checkValueOfThree() { + // We need to keep this check separate to prevent three from + // getting initialized before the += is executed. + Expect.equals(3, three); + } + + static void testStaticFieldInitialization() { + Expect.equals(null, one); + Expect.equals(2, two); + one = 11; + two = 22; + Expect.equals(11, one); + Expect.equals(22, two); + + // Assignment operators exercise a different code path. Make sure + // that initialization works here as well. + three += 1; + checkValueOfThree(); + } +} + + +class StaticFieldTest { + static testMain() { + First.a = 3; + First.b = First.a; + Expect.equals(3, First.a); + Expect.equals(First.a, First.b); + First.b = (First.a = 10); + Expect.equals(10, First.a); + Expect.equals(10, First.b); + First.b = First.a = 15; + Expect.equals(15, First.a); + Expect.equals(15, First.b); + Expect.equals(35, First.setValues()); + Expect.equals(24, First.a); + Expect.equals(10, First.b); + Second.testUnqualifiedStatic(); + } +} + + +main() { + StaticFieldTest.testMain(); + InitializerTest.testStaticFieldInitialization(); +} diff --git a/tests/language/src/StaticFinalField2NegativeTest.dart b/tests/language/src/StaticFinalField2NegativeTest.dart new file mode 100644 index 00000000000..61af0cdd915 --- /dev/null +++ b/tests/language/src/StaticFinalField2NegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Disallow re-assignment of a final static variable. + +class A { + static final x = 1; +} + +main() { + A.x = 2; // <- reassignment not allowed. +} diff --git a/tests/language/src/StaticFinalFieldNegativeTest.dart b/tests/language/src/StaticFinalFieldNegativeTest.dart new file mode 100644 index 00000000000..aa125a859c0 --- /dev/null +++ b/tests/language/src/StaticFinalFieldNegativeTest.dart @@ -0,0 +1,24 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing static final fields. +// This test should fail because fields a and c are static final fields +// and they are missing initializers. + +class A { + const A() : n = 5; + final n; + static final a; + static final b = 3 + 5; + static final c; +} + +class StaticFinalFieldNegativeTest { + static testMain() { + var a = new A(); + } +} + +main() { + StaticFinalFieldNegativeTest.testMain(); +} diff --git a/tests/language/src/StaticFinalFieldTest.dart b/tests/language/src/StaticFinalFieldTest.dart new file mode 100644 index 00000000000..ecedd6ea000 --- /dev/null +++ b/tests/language/src/StaticFinalFieldTest.dart @@ -0,0 +1,56 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing static final fields. + +interface Spain { + static final AG = "Antoni Gaudi"; + static final SD = "Salvador Dali"; +} + +interface Switzerland { + static final AG = "Alberto Giacometti"; + static final LC = "Le Corbusier"; +} + +class A implements Switzerland { + const A() : n = 5; + final n; + static final a = const A(); + static final b = 3 + 5; + static final c = A.b + 7; + static final d = const A(); + static final s1 = "hula"; + static final s2 = "hula"; + static final s3 = "hop"; + static final d1 = 1.1; + static final d2 = 0.55 + 0.55; + static final artist2 = Switzerland.AG; + static final architect1 = Spain.AG; + static final array1 = const [1, 2]; + static final map1 = const {"Monday": 1, "Tuesday": 2, }; + static final map2 = const {"$s1$s3": b}; +} + +class StaticFinalFieldTest { + static testMain() { + Expect.equals(15, A.c); + Expect.equals(8, A.b); + Expect.equals(5, A.a.n); + Expect.equals(true, 8 === A.b); + Expect.equals(true, A.a === A.d); + Expect.equals(true, A.s1 === A.s2); + Expect.equals(false, A.s1 === A.s3); + Expect.equals(false, A.s1 === A.b); + Expect.equals(true, A.d1 === A.d2); + Expect.equals(true, Spain.SD == "Salvador Dali"); + Expect.equals(true, A.artist2 == "Alberto Giacometti"); + Expect.equals(true, A.architect1 == "Antoni Gaudi"); + Expect.equals(2, A.map1["Tuesday"]); + Expect.equals(8, A.map2["hulahop"]); + } +} + +main() { + StaticFinalFieldTest.testMain(); +} diff --git a/tests/language/src/StaticImplicitClosureTest.dart b/tests/language/src/StaticImplicitClosureTest.dart new file mode 100644 index 00000000000..a6fe3340435 --- /dev/null +++ b/tests/language/src/StaticImplicitClosureTest.dart @@ -0,0 +1,31 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing invocation of implicit closures. + +class First { + First() {} + static int get a() { + return 10; + } + static var b; + static int foo() { return 30; } +} + +class StaticImplicitClosureTest { + static void testMain() { + Function func = () => 20; + Expect.equals(10, First.a); + First.b = First.a; + Expect.equals(10, First.b); + First.b = func; + Expect.equals(20, First.b()); + Function fa = First.foo; + Expect.equals(30, fa()); + } +} + + +main() { + StaticImplicitClosureTest.testMain(); +} diff --git a/tests/language/src/StaticTopLevelTest.dart b/tests/language/src/StaticTopLevelTest.dart new file mode 100644 index 00000000000..8255d9f989e --- /dev/null +++ b/tests/language/src/StaticTopLevelTest.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +static method() { } /// 00: compile-time error +static var field; /// 01: compile-time error +static final constant = 42; /// 02: compile-time error + +static int typedMethod() => 87; /// 03: compile-time error +static int typedField; /// 04: compile-time error +static final int typedConstant = 99; /// 05: compile-time error + +void main() { +} diff --git a/tests/language/src/StringConcatTest.dart b/tests/language/src/StringConcatTest.dart new file mode 100644 index 00000000000..fbc303df440 --- /dev/null +++ b/tests/language/src/StringConcatTest.dart @@ -0,0 +1,64 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// String concatenation test. + +interface V { + static final Version = "7.3.5.3"; +} + + +class StringConcatTest { + + static final Tag = "version-" + V.Version; + + static Answer() { + return 42; + } + + static testMain() { + int nofExceptions = 0; + + var x = 3; + var y = 5; + Expect.equals("" + x + y, "35"); + Expect.equals(x + y, 8); + + var s1 = "The answer is " + Answer() + '.'; + Expect.equals(s1, "The answer is 42."); + + Expect.equals("version-7.3.5.3", Tag); + + // Adding a number to a string value creates a new, concatenated + // string. + s1 = "Grandmaster Flash and the Furious "; + s1 = s1 + (4 + 1); + Expect.equals(true, s1.endsWith("Furious 5")); + + // Adding a string to a number is not supported. + try { + String cantDo = x + " should't work"; // throws noSuchMethodException. + Expect.equals(1, 0); // this should never be executed. + } catch(NoSuchMethodException e) { + // In default mode. + nofExceptions++; + } catch (TypeError e) { + // In type checked mode. + nofExceptions++; + } + + // Check that compile time constants are canonicalized. + // TODO(hausner): Add more examples once we concatenate + // CT constants other than string literals at compile time. + var fake = "Milli" + " " + "Vanilli"; + Expect.equals(fake, "Milli Vanilli"); + Expect.equals(true, fake === "Milli Vanilli"); + Expect.equals(true, fake === "Milli " + 'Vanilli'); + + Expect.equals(nofExceptions, 1); + } +} + +main() { + StringConcatTest.testMain(); +} diff --git a/tests/language/src/StringEscapesTest.dart b/tests/language/src/StringEscapesTest.dart new file mode 100644 index 00000000000..8f711c29f32 --- /dev/null +++ b/tests/language/src/StringEscapesTest.dart @@ -0,0 +1,65 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringEscapesTest { + + static testMain() { + testDelimited(); + testFixed2(); + testFixed4(); + testEscapes(); + testLiteral(); + } + + static testDelimited() { + String str = "Foo\u{1}Bar\u{000001}Baz\u{D7FF}Boo"; + Expect.equals(15, str.length); + Expect.equals(1, str.charCodeAt(3)); + Expect.equals(1, str.charCodeAt(7)); + Expect.equals(0xD7FF, str.charCodeAt(11)); + Expect.equals('B'.charCodeAt(0), str.charCodeAt(12)); + } + + static testEscapes() { + String str = "Foo\fBar\vBaz\bBoo"; + Expect.equals(15, str.length); + Expect.equals(12, str.charCodeAt(3)); + Expect.equals('B'.charCodeAt(0), str.charCodeAt(4)); + Expect.equals(11, str.charCodeAt(7)); + Expect.equals('z'.charCodeAt(0), str.charCodeAt(10)); + Expect.equals(8, str.charCodeAt(11)); + Expect.equals('o'.charCodeAt(0), str.charCodeAt(14)); + str = "Abc\rDef\nGhi\tJkl"; + Expect.equals(15, str.length); + Expect.equals(13, str.charCodeAt(3)); + Expect.equals('D'.charCodeAt(0), str.charCodeAt(4)); + Expect.equals(10, str.charCodeAt(7)); + Expect.equals('G'.charCodeAt(0), str.charCodeAt(8)); + Expect.equals(9, str.charCodeAt(11)); + Expect.equals('J'.charCodeAt(0), str.charCodeAt(12)); + } + + static testFixed2() { + String str = "Foo\xFFBar"; + Expect.equals(7, str.length); + Expect.equals(255, str.charCodeAt(3)); + Expect.equals('B'.charCodeAt(0), str.charCodeAt(4)); + } + + static testFixed4() { + String str = "Foo\u0001Bar"; + Expect.equals(7, str.length); + Expect.equals(1, str.charCodeAt(3)); + Expect.equals('B'.charCodeAt(0), str.charCodeAt(4)); + } + + static testLiteral() { + String str = "\a\c\d\e\g\h\i\j\k\l\$\{\}\""; + Expect.equals(@'acdeghijkl${}"', str); + } +} + +main() { + StringEscapesTest.testMain(); +} diff --git a/tests/language/src/StringInterpolate1NegativeTest.dart b/tests/language/src/StringInterpolate1NegativeTest.dart new file mode 100644 index 00000000000..5a38e5213c6 --- /dev/null +++ b/tests/language/src/StringInterpolate1NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing that the interpolated identifier does not start +// with '$'. + +class StringInterpolate1NegativeTest { + + static testMain() { + var $x = 1; + var s = "eins und $$x macht zwei."; + print(s); + } + +} + +main() { + StringInterpolate1NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolate2NegativeTest.dart b/tests/language/src/StringInterpolate2NegativeTest.dart new file mode 100644 index 00000000000..0acbd7dece7 --- /dev/null +++ b/tests/language/src/StringInterpolate2NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing that the interpolated identifier starts with an +// ident start character. + +class StringInterpolate2NegativeTest { + + static testMain() { + var $x = 1; + var s = "eins und $-x macht zwei."; + print(s); + } + +} + +main() { + StringInterpolate2NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolate2Test.dart b/tests/language/src/StringInterpolate2Test.dart new file mode 100644 index 00000000000..3d7f06e5142 --- /dev/null +++ b/tests/language/src/StringInterpolate2Test.dart @@ -0,0 +1,51 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing string interpolation of expressions. + + +class StringInterpolate2Test { + + static final F1 = "1 + 5 = ${1+5}"; + + static void testMain() { + + Expect.equals("1 + 5 = 6", F1); + + var fib = [1, 1, 2, 3, 5, 8, 13, 21]; + + var i = 5; + var s = "${i}"; + Expect.equals("5", s); + + s = "fib(${i}) = ${fib[i]}"; + Expect.equals("fib(5) = 8", s); + + i = 5; + s = "$i squared is ${((x) => x*x)(i)}"; + Expect.equals("5 squared is 25", s); + + Expect.equals("8", "${fib.length}"); + Expect.equals("8", '${fib. + length}'); + + var map = { "red": 1, "green": 2, "blue": 3 }; + s = "green has value ${map["green"]}"; + Expect.equals("green has value 2", s); + + i = 0; + b() => "${++i}"; + s = "aaa ${"bbb ${b()} bbb"} aaa ${b()}"; + Expect.equals("aaa bbb 1 bbb aaa 2", s); + + // test multiple levels of nesting, including changing quotes and + // multiline string types + s = "a ${(){ return 'b ${(){ return """ +c""";}()}'; }()} d"; + Expect.equals("a b c d", s); + } +} + +main() { + StringInterpolate2Test.testMain(); +} diff --git a/tests/language/src/StringInterpolateNPETest.dart b/tests/language/src/StringInterpolateNPETest.dart new file mode 100644 index 00000000000..4ed439488df --- /dev/null +++ b/tests/language/src/StringInterpolateNPETest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing NPE within string interpolation. + +class A { + A(String this.name) {} + String name; +} + +main() { + A a = new A("Kermit"); + var s = "Hello Mr. ${a.name}"; + Expect.stringEquals("Hello Mr. Kermit", s); + a = null; + try { + s = "Hello Mr. ${a.name}"; + } catch (NullPointerException e) { + return; + } + Expect.fail("NullPointerException not thrown"); +} diff --git a/tests/language/src/StringInterpolateTest.dart b/tests/language/src/StringInterpolateTest.dart new file mode 100644 index 00000000000..3bb8d361f0a --- /dev/null +++ b/tests/language/src/StringInterpolateTest.dart @@ -0,0 +1,58 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing string interpolation. + + +class WhatchamaCallIt { + WhatchamaCallIt() { } + + void foo() { + return "Hansel and $name"; // Field name is defined in subclass. + } +} + +class ThingamaBob extends WhatchamaCallIt { + ThingamaBob(String s) : super(), name = s { } + String name; +} + +class StringInterpolateTest { + + static final String A = "svin"; + static final String B = "hest"; + static final int N = 1 + 1; + static final String Printers = "Printers: $A and $B"; + static final String AAR_Printers = "AAR has $N $Printers."; + + static testMain() { + var x = 1; + var s = "eins und \$x macht zwei."; + print(s); + Expect.equals(@"eins und $x macht zwei.", s); + + s = "eins und $x macht zwei."; + print(s); + Expect.equals(@"eins und 1 macht zwei.", s); + + print(AAR_Printers); + Expect.equals(@"AAR has 2 Printers: svin and hest.", AAR_Printers); + + var s$eins = "eins"; + var $1 = 1; + var zw = "zw"; + var ei = "ei"; + var zw$ei = "\"Martini, dry? Nai zwai.\""; + s = "${s$eins} und ${$1} macht $zw$ei."; + print(s); + Expect.equals(@"eins und 1 macht zwei.", s); + + var t = new ThingamaBob("Gretel"); + print(t.foo()); + Expect.equals(t.foo(), "Hansel and Gretel"); + } +} + +main() { + StringInterpolateTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation1NegativeTest.dart b/tests/language/src/StringInterpolation1NegativeTest.dart new file mode 100644 index 00000000000..fe6f8c92068 --- /dev/null +++ b/tests/language/src/StringInterpolation1NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class A { + final String str; + const A(this.str); +} + +class StringInterpolation1NegativeTest { + // Dollar not followed by "{" or identifier. + static final DOLLAR = const A("$"); + testMain() { + } +} + +main() { + StringInterpolation1NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation2NegativeTest.dart b/tests/language/src/StringInterpolation2NegativeTest.dart new file mode 100644 index 00000000000..ca5e269dedd --- /dev/null +++ b/tests/language/src/StringInterpolation2NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class StringInterpolation2NegativeTest { + testMain() { + print('C;Y1;X4;K"$/Month"'); // Dollar followed by "/". + } +} + +main() { + StringInterpolation2NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation3NegativeTest.dart b/tests/language/src/StringInterpolation3NegativeTest.dart new file mode 100644 index 00000000000..fd957299dbb --- /dev/null +++ b/tests/language/src/StringInterpolation3NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class StringInterpolation3NegativeTest { + testMain() { + print('F;P4;F$2R'); // Dollar followed by a number. + } +} + +main() { + StringInterpolation3NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation4NegativeTest.dart b/tests/language/src/StringInterpolation4NegativeTest.dart new file mode 100644 index 00000000000..bc7db6f933f --- /dev/null +++ b/tests/language/src/StringInterpolation4NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class StringInterpolation4NegativeTest { + testMain() { + // Dollar not followed by "{" or identifier. + print("-" + "$" + "foo"); + } +} + +main() { + StringInterpolation4NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation5NegativeTest.dart b/tests/language/src/StringInterpolation5NegativeTest.dart new file mode 100644 index 00000000000..9d6197d2802 --- /dev/null +++ b/tests/language/src/StringInterpolation5NegativeTest.dart @@ -0,0 +1,15 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class StringInterpolation5NegativeTest { + testMain() { + print("$1,000"); // Dollar followed by a number. + } +} + +main() { + StringInterpolation5NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation6NegativeTest.dart b/tests/language/src/StringInterpolation6NegativeTest.dart new file mode 100644 index 00000000000..e90545fc1b1 --- /dev/null +++ b/tests/language/src/StringInterpolation6NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// A dollar must be followed by a "{" or an identifier. + +class StringInterpolation6NegativeTest { + testMain() { + // Dollar not followed by "{" or identifier. + String regexp = "^(\\d\\d?)[-/](\\d\\d?)$"; + print(regexp); + } +} + +main() { + StringInterpolation6NegativeTest.testMain(); +} diff --git a/tests/language/src/StringInterpolation7Test.dart b/tests/language/src/StringInterpolation7Test.dart new file mode 100644 index 00000000000..a75080417db --- /dev/null +++ b/tests/language/src/StringInterpolation7Test.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test program testing string interpolation with toString on custom +// classes and on null. + + +class A { + const A(); + String toString() { return "A"; } +} + +class StringInterpolation7Test { + + static testMain() { + A a = new A(); + Expect.equals("A + A", "$a + $a"); + a = null; + Expect.equals("null", "$a"); + } +} + +main() { + StringInterpolation7Test.testMain(); +} diff --git a/tests/language/src/StringInterpolationTest.dart b/tests/language/src/StringInterpolationTest.dart new file mode 100644 index 00000000000..74ae1179736 --- /dev/null +++ b/tests/language/src/StringInterpolationTest.dart @@ -0,0 +1,78 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests for string interpolation +class StringInterpolationTest { + + StringInterpolationTest() {} + + static final int i = 1; + static final String a = ""; + + int j; + int k; + + static testMain(bool alwaysFalse) { + var test = new StringInterpolationTest(); + test.j = 3; + test.k = 5; + + // simple string + Expect.equals(" hi ", " hi "); + + var c1 = '1'; + var c2 = '2'; + var c3 = '3'; + var c4 = '4'; + // no chars before/after/between embedded expressions + Expect.equals(" 1", " ${c1}"); + Expect.equals("1 ", "${c1} "); + Expect.equals("1", "${c1}"); + Expect.equals("12", "${c1}${c2}"); + Expect.equals("12 34", "${c1}${c2} ${c3}${c4}"); + + // embedding static fields + Expect.equals(" hi 1 ", " hi ${i} "); + Expect.equals(true, " hi ${i} " === " hi ${i} "); + Expect.equals(" hi ", " hi ${a} "); + + // embedding method parameters + Expect.equals("param = 9", test.embedParams(9)); + + // embedding a class field + Expect.equals("j = 3", test.embedSingleField()); + + // embedding more than one (non-constant) expression + Expect.equals(" hi 1 ", " hi ${i} ${a}"); + Expect.equals("j = 3; k = 5", test.embedMultipleFields()); + + // escaping $ - doesn't start the embedded expression + Expect.equals("\$", "escaped \${3+2}"[12]); + Expect.equals("{", "escaped \${3+2}"[13]); + Expect.equals("3", "escaped \${3+2}"[14]); + Expect.equals("+", "escaped \${3+2}"[15]); + Expect.equals("2", "escaped \${3+2}"[16]); + Expect.equals("}", "escaped \${3+2}"[17]); + + if (alwaysFalse) { + "${i.toHorse()}"; /// 01: static type error + } + } + + String embedParams(int z) { + return "param = ${z}"; + } + + String embedSingleField() { + return "j = ${j}"; + } + + String embedMultipleFields() { + return "j = ${j}; k = ${k}"; + } +} + +main() { + StringInterpolationTest.testMain(false); +} diff --git a/tests/language/src/StringJoinTest.dart b/tests/language/src/StringJoinTest.dart new file mode 100644 index 00000000000..d33233113a1 --- /dev/null +++ b/tests/language/src/StringJoinTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Regression test ensuring that only ObjectArrays are handed to the VM code. + +class StringJoinTest { + static testMain() { + List ga = new List(); + ga.add("a"); + ga.add("b"); + Expect.equals("ab", Strings.join(ga, "")); + } +} + +main() { + StringJoinTest.testMain(); +} diff --git a/tests/language/src/StringTest.dart b/tests/language/src/StringTest.dart new file mode 100644 index 00000000000..9cbb3e6014a --- /dev/null +++ b/tests/language/src/StringTest.dart @@ -0,0 +1,51 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Replace with shared test once interface issues clarified. + +class StringTest { + + static testMain() { + testCodePoints(); + testNoSuchMethod(); + testStringsJoin(); + testCharCodes(); + } + + static testCodePoints() { + String str = "string"; + for (int i = 0; i < str.length; i++) { + Expect.equals(true, str[i] is String); + Expect.equals(true, str.charCodeAt(i) is int); + } + } + + static testStringsJoin() { + List a = new List(2); + a[0] = "Hello"; + a[1] = "World"; + String s = Strings.join(a, "*^*"); + Expect.equals("Hello*^*World", s); + } + + static testNoSuchMethod() { + String a = "Hello"; + bool exception_caught = false; + try { + a[1] = 12; // Throw exception. + } catch (NoSuchMethodException e) { + exception_caught = true; + } + Expect.equals(true, exception_caught); + } + + static testCharCodes() { + String s = new String.fromCharCodes(const [0x41, 0xC1, 0x424]); + Expect.equals("A", s[0]); + Expect.equals(0x424, s.charCodeAt(2)); + } +} + +main() { + StringTest.testMain(); +} diff --git a/tests/language/src/StringUnicode1NegativeTest.dart b/tests/language/src/StringUnicode1NegativeTest.dart new file mode 100644 index 00000000000..72c06e1456e --- /dev/null +++ b/tests/language/src/StringUnicode1NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringUnicode1NegativeTest { + + static testMain() { + // (backslash) uXXXX must have exactly 4 hex digits + String str = "Foo\u00"; + str = "Foo\uDEEMBar"; + } +} + +main() { + StringUnicode1NegativeTest.testMain(); +} diff --git a/tests/language/src/StringUnicode2NegativeTest.dart b/tests/language/src/StringUnicode2NegativeTest.dart new file mode 100644 index 00000000000..c38040c574b --- /dev/null +++ b/tests/language/src/StringUnicode2NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringUnicode2NegativeTest { + + static testMain() { + // \u{X*} should have 1-6 hex digits + String str = "Foo\u{}Bar"; + str = "Foo\u{000000000}Bar"; + str = "Foo\u{DEAF!}Bar"; + } +} + +main() { + StringUnicode2NegativeTest.testMain(); +} diff --git a/tests/language/src/StringUnicode3NegativeTest.dart b/tests/language/src/StringUnicode3NegativeTest.dart new file mode 100644 index 00000000000..15cdf3822bd --- /dev/null +++ b/tests/language/src/StringUnicode3NegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringUnicode3NegativeTest { + + static testMain() { + // (backslash) xXX must have exactly 2 hex digits + String str = "Foo\x0"; + str = "Foo\xF Bar"; + } +} + +main() { + StringUnicode3NegativeTest.testMain(); +} diff --git a/tests/language/src/StringUnicode4NegativeTest.dart b/tests/language/src/StringUnicode4NegativeTest.dart new file mode 100644 index 00000000000..b4ee30fa814 --- /dev/null +++ b/tests/language/src/StringUnicode4NegativeTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class StringUnicode4NegativeTest { + + static testMain() { + // Unicode escapes must refer to valid Unicode points and not surrogate characters + String str = "Foo\u{FFFFFF}"; + str = "Foo\uD800"; + str = "Foo\uDC00"; + } +} + +main() { + StringUnicode4NegativeTest.testMain(); +} diff --git a/tests/language/src/SuperCallTest.dart b/tests/language/src/SuperCallTest.dart new file mode 100644 index 00000000000..1f56c1ceedb --- /dev/null +++ b/tests/language/src/SuperCallTest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing super calls + +class A { + A() : field = 0 {} + int field; + incrField() { + field++; + } + timesX(v) { + return v * 2; + } +} + +class B extends A { + incrField() { + field++; + super.incrField(); + } + + timesX(v) { + return super.timesX(v) * 3; + } + + B() : super() {} +} + +class SuperCallTest { + static testMain() { + var b = new B(); + b.incrField(); + Expect.equals(2, b.field); + Expect.equals(12, b.timesX(2)); + } +} + +main() { + SuperCallTest.testMain(); +} diff --git a/tests/language/src/SuperFieldTest.dart b/tests/language/src/SuperFieldTest.dart new file mode 100644 index 00000000000..bb8e6d4a3bc --- /dev/null +++ b/tests/language/src/SuperFieldTest.dart @@ -0,0 +1,56 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing super field access. + + +class A { + A() { + city = "Bern"; + } + String greeting() { + return "Gruezi"; + } + String city; +} + + +class B extends A { + B() : super() {} + String greeting() { + return "Hola " + super.greeting(); + } +} + + +class C extends B { + C() : super() {} + String greeting() { + return "Servus " + super.greeting(); + } + String get city() { + return "Basel " + super.city; + } +} + + +class SuperFieldTest { + static testMain() { + A a = new A(); + B b = new B(); + C c = new C(); + Expect.equals("Gruezi", a.greeting()); + Expect.equals("Hola Gruezi", b.greeting()); + Expect.equals("Servus Hola Gruezi", c.greeting()); + + Expect.equals("Bern", a.city); + Expect.equals("Bern", b.city); + Expect.equals("Basel Bern", c.city); + c.city = "Zurich"; + Expect.equals("Basel Zurich", c.city); + } +} + +main() { + SuperFieldTest.testMain(); +} diff --git a/tests/language/src/SuperImplicitClosureTest.dart b/tests/language/src/SuperImplicitClosureTest.dart new file mode 100644 index 00000000000..b25bf0479db --- /dev/null +++ b/tests/language/src/SuperImplicitClosureTest.dart @@ -0,0 +1,34 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing invocation of implicit closures. + +class BaseClass { + BaseClass(this._i) {} + int foo() { return _i; } + int _i; +} + +class DerivedClass extends BaseClass { + DerivedClass(this._y, int j) : super(j) {} + int foo() { return _y; } + getSuper() { return super.foo; } + int _y; +} + +class SuperImplicitClosureTest { + static void testMain() { + DerivedClass obj = new DerivedClass(20, 10); + + var ib = obj.foo; + Expect.equals(obj._y, ib()); + + ib = obj.getSuper(); + Expect.equals(obj._i, ib()); + } +} + + +main() { + SuperImplicitClosureTest.testMain(); +} diff --git a/tests/language/src/SuperNegativeTest.dart b/tests/language/src/SuperNegativeTest.dart new file mode 100644 index 00000000000..41e987abc96 --- /dev/null +++ b/tests/language/src/SuperNegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Missing call to super. + +class A { + A() {} +} + +class B extends A { + // Missing call to super. + B() {} +} + +class SuperNegativeTest { + static testMain() { + var b = new B(); + } +} + +main() { + SuperNegativeTest.testMain(); +} diff --git a/tests/language/src/SuperSetterTest.dart b/tests/language/src/SuperSetterTest.dart new file mode 100644 index 00000000000..1c0d6934d01 --- /dev/null +++ b/tests/language/src/SuperSetterTest.dart @@ -0,0 +1,37 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing super setters and getters. + +class Base { + Base() {} + String value_; + + String get value() { return value_; } + String set value(String newValue) { + value_ = 'Base:' + newValue; + } +} + + +class Derived extends Base { + Derived() : super() {} + + String set value(String newValue) { + super.value = 'Derived:' + newValue; + } + String get value() { return super.value; } +} + + +class SuperSetterTest { + static void testMain() { + final b = new Derived(); + b.value = "foo"; + Expect.equals("Base:Derived:foo", b.value); + } +} + +main() { + SuperSetterTest.testMain(); +} diff --git a/tests/language/src/SuperTest.dart b/tests/language/src/SuperTest.dart new file mode 100644 index 00000000000..c5176b85b4f --- /dev/null +++ b/tests/language/src/SuperTest.dart @@ -0,0 +1,54 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests super calls and constructors. +class SuperTest { + static testMain() { + Sup.i = 0; + Sub sub = new Sub(1, 2); + Expect.equals(1, sub.x); + Expect.equals(2, sub.y); + Expect.equals(3, sub.z); + Expect.equals(1, sub.v); + Expect.equals(2, sub.w); + Expect.equals(3, sub.u); + + sub = new Sub.stat(); + Expect.equals(0, sub.x); + Expect.equals(1, sub.y); + Expect.equals(2, sub.v); + Expect.equals(3, sub.w); + Expect.equals(4, sub.z); + Expect.equals(5, sub.u); + } +} + +class Sup { + static int i; + var x, y, z; + + Sup(a, b) : this.x = a, this.y = b { + z = a + b; + } + + Sup.stat() : this.x = i++, this.y = i++ { + z = i++; + } +} + +class Sub extends Sup { + var u, v, w; + + Sub(a, b) : super(a, b), this.v = a, this.w = b { + u = a + b; + } + + Sub.stat() : super.stat(), this.v = i++, this.w = i++ { + u = i++; + } +} + +main() { + SuperTest.testMain(); +} diff --git a/tests/language/src/Switch1NegativeTest.dart b/tests/language/src/Switch1NegativeTest.dart new file mode 100644 index 00000000000..5648b222b49 --- /dev/null +++ b/tests/language/src/Switch1NegativeTest.dart @@ -0,0 +1,23 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that default clause must be last case. + +class Switch1NegativeTest { + + static testMain() { + var a = 5; + var x; + S: switch (a) { + case 1: x = 1; break; + case 6: x = 2; break S; + default: + case 8: break; + } + return a; + } +} + +main() { + Switch1NegativeTest.testMain(); +} diff --git a/tests/language/src/Switch3NegativeTest.dart b/tests/language/src/Switch3NegativeTest.dart new file mode 100644 index 00000000000..12325377009 --- /dev/null +++ b/tests/language/src/Switch3NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that 'continue' to switch statement is illegal. + +class Switch3NegativeTest { + + static testMain() { + var a = 5; + var x; + switch (a) { + case 1: x = 1; break; + case 6: x = 2; continue; // illegal jump target + case 8: break; + } + return a; + } +} + +main() { + Switch3NegativeTest.testMain(); +} diff --git a/tests/language/src/Switch4NegativeTest.dart b/tests/language/src/Switch4NegativeTest.dart new file mode 100644 index 00000000000..e4d0e0d876c --- /dev/null +++ b/tests/language/src/Switch4NegativeTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Discover unresolved case labels. + +class Switch4NegativeTest { + + static testMain() { + var a = 5; + var x; + switch (a) { + case 1: x = 1; continue L; // unresolved forward reference + case 6: x = 2; break; + case 8: break; + } + return a; + } +} + +main() { + Switch4NegativeTest.testMain(); +} diff --git a/tests/language/src/Switch5NegativeTest.dart b/tests/language/src/Switch5NegativeTest.dart new file mode 100644 index 00000000000..69ac10a4242 --- /dev/null +++ b/tests/language/src/Switch5NegativeTest.dart @@ -0,0 +1,26 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Break' to case label is illegal. + +class Switch5NegativeTest { + + static testMain() { + var a = 5; + var x; + switch (a) { + L: + case 1: + x = 1; break; + case 6: + x = 2; break L; // illegal + default: + break; + } + return a; + } +} + +main() { + Switch5NegativeTest.testMain(); +} diff --git a/tests/language/src/Switch6Test.dart b/tests/language/src/Switch6Test.dart new file mode 100644 index 00000000000..a4d9dd33f17 --- /dev/null +++ b/tests/language/src/Switch6Test.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// The break is in the right scope, http://b/3428700 was agreed upon. + +class Switch6Test { + + static testMain() { + var a = 0; + var x = -1; + switch (a) { + case 0: { + x = 0; + break; + } + case 1: + x = 1; + break; + } + Expect.equals(0, x); + } + +} + +main() { + Switch6Test.testMain(); +} diff --git a/tests/language/src/Switch7NegativeTest.dart b/tests/language/src/Switch7NegativeTest.dart new file mode 100644 index 00000000000..c2eceb98cef --- /dev/null +++ b/tests/language/src/Switch7NegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Illegal to reference a labeled case stmt with break + +class Switch7NegativeTest { + + static testMain() { + var x = 1; + L: while (true) { + switch (x) { + L: case 1: // Shadowing another label is OK. + break L; // illegal, can't reference labeled case stmt from break + } + } + } +} + +main() { + Switch7NegativeTest.testMain(); +} diff --git a/tests/language/src/SwitchFallthruTest.dart b/tests/language/src/SwitchFallthruTest.dart new file mode 100644 index 00000000000..226aec7a902 --- /dev/null +++ b/tests/language/src/SwitchFallthruTest.dart @@ -0,0 +1,39 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Check that FallThroughError is thrown if switch clause does not terminate. + +class SwitchFallthruTest { + static String test(int n) { + String result = "foo"; + switch (n) { + case 0: + result = "zero"; + break; + case 1: + result = "one"; + // fall-through, throw implicit FallThroughError here. + case 9: + result = "nine"; + // No implicit FallThroughError at end of switch statement. + } + return result; + } + + static testMain() { + Expect.equals("zero", test(0)); + bool fallthroughCaught = false; + try { + test(1); + } catch (FallThroughError e) { + fallthroughCaught = true; + } + Expect.equals(true, fallthroughCaught); + Expect.equals("nine", test(9)); + Expect.equals("foo", test(99)); + } +} + +main() { + SwitchFallthruTest.testMain(); +} diff --git a/tests/language/src/SwitchLabelTest.dart b/tests/language/src/SwitchLabelTest.dart new file mode 100644 index 00000000000..56c3d5d1230 --- /dev/null +++ b/tests/language/src/SwitchLabelTest.dart @@ -0,0 +1,100 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test switch statement using labels. + +class Switcher { + + Switcher() { } + + say1 (sound) { + var x = 0; + switch (sound) { + MOO: + case "moo": + x = 100; + break; + case "woof": + x = 200; + continue MOO; + default: + x = 300; + break; + } + return x; + } + + say2 (sound) { + var x = 0; + switch (sound) { + WOOF: + case "woof": + x = 200; + break; + case "moo": + x = 100; + continue WOOF; + default: + x = 300; + break; + } + return x; + } + + // forward label to outer switch + say3 (animal, sound) { + var x = 0; + switch (animal) { + case "cow": + switch (sound) { + case "moo": + x = 100; break; + case "muh": + x = 200; break; + default: + continue NIX_UNDERSTAND; + } + break; + case "dog": + if (sound == "woof") { + x = 300; + } else { + continue NIX_UNDERSTAND; + } + break; + NIX_UNDERSTAND: + case "unicorn": + x = 400; + break; + default: + x = 500; + break; + } + return x; + } +} + +class SwitchLabelTest { + static testMain() { + Switcher s = new Switcher(); + Expect.equals(100, s.say1("moo")); + Expect.equals(100, s.say1("woof")); + Expect.equals(300, s.say1("cockadoodledoo")); + + Expect.equals(200, s.say2("moo")); + Expect.equals(200, s.say2("woof")); + Expect.equals(300, s.say2("")); // Dead unicorn says nothing. + + Expect.equals(100, s.say3("cow", "moo")); + Expect.equals(200, s.say3("cow", "muh")); + Expect.equals(400, s.say3("cow", "boeh")); // Don't ask. + Expect.equals(300, s.say3("dog", "woof")); + Expect.equals(400, s.say3("dog", "boj")); // Ĉu vi parolas Esperanton? + Expect.equals(400, s.say3("unicorn", "")); // Still dead. + Expect.equals(500, s.say3("angry bird", "whoooo")); + } +} + +main() { + SwitchLabelTest.testMain(); +} diff --git a/tests/language/src/SwitchScopeTest.dart b/tests/language/src/SwitchScopeTest.dart new file mode 100644 index 00000000000..fc297ca0200 --- /dev/null +++ b/tests/language/src/SwitchScopeTest.dart @@ -0,0 +1,25 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test that a new scope is introduced for each switch case. + +class SwitchScopeTest { + static testMain() { + switch(1) { + case 1: + final v = 1; + break; + case 2: + final v = 2; + Expect.equals(2, v); + break; + default: + final v = 3; + break; + } + } +} + +main() { + SwitchScopeTest.testMain(); +} diff --git a/tests/language/src/SwitchTest.dart b/tests/language/src/SwitchTest.dart new file mode 100644 index 00000000000..a9955a9dae9 --- /dev/null +++ b/tests/language/src/SwitchTest.dart @@ -0,0 +1,68 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test switch statement. + +class Switcher { + + Switcher() { } + + test1 (val) { + var x = 0; + switch (val) { + case 1: + x = 100; break; + case 2: + case 3: + x = 200; break; + case "mister string": + return 300; + case 4: + default: { + x = 400; break; + } + } + return x; + } + + test2 (val) { + switch (val) { + case true: return 100; + case 1: return 200; + case "1": return 300; + default: return 400; + } + } + + test3(val) { + final int temp = 5; + switch (true) { + case temp == val: + return true; + } + return false; + } +} + + +class SwitchTest { + static testMain() { + Switcher s = new Switcher(); + Expect.equals(100, s.test1(1)); + Expect.equals(200, s.test1(2)); + Expect.equals(200, s.test1(3)); + Expect.equals(300, s.test1("mister string")); + Expect.equals(400, s.test1(4)); + Expect.equals(400, s.test1(5)); + + Expect.equals(200, s.test2(1)); + Expect.equals(300, s.test2("1")); + + Expect.equals(true, s.test3(5)); + Expect.equals(false, s.test3(6)); + } +} + +main() { + SwitchTest.testMain(); +} diff --git a/tests/language/src/TernaryTest.dart b/tests/language/src/TernaryTest.dart new file mode 100644 index 00000000000..52b44501820 --- /dev/null +++ b/tests/language/src/TernaryTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing the ternary operator. + +class TernaryTest { + static true_cond() { return true; } + static false_cond() { return false; } + static foo() { return -4; } + static moo() { return +5; } + static testMain() { + Expect.equals(-4, (TernaryTest.true_cond() ? TernaryTest.foo() + : TernaryTest.moo())); + Expect.equals(+5, (TernaryTest.false_cond() ? TernaryTest.foo() + : TernaryTest.moo())); + } +} + +main() { + TernaryTest.testMain(); +} diff --git a/tests/language/src/TestNegativeTest.dart b/tests/language/src/TestNegativeTest.dart new file mode 100644 index 00000000000..831d9ddc76a --- /dev/null +++ b/tests/language/src/TestNegativeTest.dart @@ -0,0 +1,21 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program which has a syntax error. This test is to +// ensure that the resulting parse error message is correctly +// displayed without being garbled. + +class Test { + static foo() { + return "hi + } + static testMain() { + List a = {1 : 1}; + List b = {1 : 1}; + return a == b; + } +} + +main() { + TestNegativeTest.testMain(); +} diff --git a/tests/language/src/ThirdTest.dart b/tests/language/src/ThirdTest.dart new file mode 100644 index 00000000000..1e86feeacb6 --- /dev/null +++ b/tests/language/src/ThirdTest.dart @@ -0,0 +1,52 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Third dart test program. + +class A extends B { + var a; + static var s; + + static foo() { + return s; + } + + A(x, y) : super(y), a = x { } + + value() { + return a + b + foo(); + } +} + + +class B { + var b; + static var s; + + static foo(x) { + return x + s; + } + + value() { + return b + foo(s) + A.foo(); + } + + B(x) : b = x { + b = b + 1; + } +} + + +class ThirdTest { + static testMain() { + var a = new A(1, 2); + var b = new B(3); + A.s = 4; + B.s = 5; + Expect.equals(26, a.value() + b.value()); + } +} + +main() { + ThirdTest.testMain(); +} diff --git a/tests/language/src/Throw1Test.dart b/tests/language/src/Throw1Test.dart new file mode 100644 index 00000000000..d03463a71af --- /dev/null +++ b/tests/language/src/Throw1Test.dart @@ -0,0 +1,71 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class MyException2 implements TestException { + const MyException2([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class MyException3 implements TestException { + const MyException3([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class Helper { + static int f1(int i) { + try { + int j; + j = func(); + if (j > 0) { + throw new MyException2("Test for exception being thrown"); + } + } catch (MyException3 exception) { + i = 100; + print(exception.getMessage()); + } catch (TestException exception) { + i = 50; + print(exception.getMessage()); + } catch (MyException2 exception) { + i = 150; + print(exception.getMessage()); + } catch (MyException exception) { + i = 200; + print(exception.getMessage()); + } finally { + i = i + 800; + } + return i; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class Throw1Test { + static testMain() { + Expect.equals(850, Helper.f1(1)); + } +} + +main() { + Throw1Test.testMain(); +} diff --git a/tests/language/src/Throw2Test.dart b/tests/language/src/Throw2Test.dart new file mode 100644 index 00000000000..7a9d20523e7 --- /dev/null +++ b/tests/language/src/Throw2Test.dart @@ -0,0 +1,84 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class MyException2 implements TestException { + const MyException2([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class MyException3 implements TestException { + const MyException3([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class Helper { + static int f1(int i) { + try { + int j; + j = func(); + } catch (MyException3 exception) { + i = 100; + print(exception.getMessage()); + } catch (MyException2 exception) { + try { + i = func2(); + i = 200; + } catch (TestException exception) { + i = 50; + } + print(exception.getMessage()); + } catch (MyException exception) { + i = func2(); + print(exception.getMessage()); + } finally { + i = i + 800; + } + return i; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException2("Test for exception being thrown"); + } + return i; + } + + static int func2() { + int i = 0; + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException2("Test for exception being thrown"); + } + return i; + } +} + +class Throw2Test { + static testMain() { + Expect.equals(850, Helper.f1(1)); + } +} + +main() { + Throw2Test.testMain(); +} diff --git a/tests/language/src/Throw3Test.dart b/tests/language/src/Throw3Test.dart new file mode 100644 index 00000000000..a8f611950e1 --- /dev/null +++ b/tests/language/src/Throw3Test.dart @@ -0,0 +1,52 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException { + const MyException([String message = ""]) : message_ = message; + final String message_; +} + +class Helper { + static int f1(int i) { + try { + int j; + i = 100; + i = func(); + i = 200; + } catch (MyException exception) { + i = 50; + print(exception.message_); + } finally { + i = i + 800; + } + return i; + } + + static int func() { + try { + int i = 0; + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException("Test for exception being thrown"); + } + } catch (MyException ex) { + print(ex.message_); + throw; // Rethrow the exception. + } + return 10; + } +} + +class Throw3Test { + static testMain() { + Expect.equals(850, Helper.f1(1)); + } +} + +main() { + Throw3Test.testMain(); +} diff --git a/tests/language/src/Throw4Test.dart b/tests/language/src/Throw4Test.dart new file mode 100644 index 00000000000..66e831900f8 --- /dev/null +++ b/tests/language/src/Throw4Test.dart @@ -0,0 +1,77 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException1 { + const MyException1([String message = "1"]) : message_ = message; + final String message_; +} + +class MyException2 { + const MyException2([String message = "2"]) : message_ = message; + final String message_; +} + +class MyException3 { + const MyException3([String message = "3"]) : message_ = message; + final String message_; +} + +class Helper { + Helper() : i = 0 { } + + int f1() { + int j = 0; + try { + j = func(); + } catch (MyException3 exception) { + i = i + 300; + print(exception.message_); + } catch (MyException2 exception) { + i = i + 200; + print(exception.message_); + } catch (MyException1 exception) { + i = i + 100; + print(exception.message_); + } finally { + i = i + 1000; + } + return i; + } + + // No catch in the same function for the type of exception being thrown + // in the try block here. We expect the handler if checks to fall thru, + // the finally block to run and an implicit rethrow to happen. + int func() { + i = 0; + try { + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException1("Test for MyException1 being thrown"); + } + } catch (MyException3 exception) { + i = 300; + print(exception.message_); + } catch (MyException2 exception) { + i = 200; + print(exception.message_); + } finally { + i = 800; + } + return i; + } + int i; +} + +class Throw4Test { + static testMain() { + Expect.equals(1900, new Helper().f1()); + } +} + +main() { + Throw4Test.testMain(); +} diff --git a/tests/language/src/Throw5Test.dart b/tests/language/src/Throw5Test.dart new file mode 100644 index 00000000000..727eb61a32d --- /dev/null +++ b/tests/language/src/Throw5Test.dart @@ -0,0 +1,72 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException1 { + const MyException1([String message = "1"]) : message_ = message; + final String message_; +} + +class MyException2 { + const MyException2([String message = "2"]) : message_ = message; + final String message_; +} + +class MyException3 { + const MyException3([String message = "3"]) : message_ = message; + final String message_; +} + +class Helper { + static int f1(int i) { + try { + int j; + j = func(); + } catch (MyException3 exception) { + i = 300; + print(exception.message_); + } catch (MyException2 exception) { + i = 200; + print(exception.message_); + } catch (MyException1 exception) { + i = 100; + print(exception.message_); + } finally { + i = i + 800; + } + return i; + } + + // No catch in the same function for the type of exception being thrown + // in the try block here. We expect the handler if checks to fall thru and + // implicit rethrow to happen. + static int func() { + int i = 0; + try { + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException1("Test for MyException1 being thrown"); + } + } catch (MyException3 exception) { + i = 300; + print(exception.message_); + } catch (MyException2 exception) { + i = 200; + print(exception.message_); + } + return i; + } +} + +class Throw5Test { + static testMain() { + Expect.equals(900, Helper.f1(1)); + } +} + +main() { + Throw5Test.testMain(); +} diff --git a/tests/language/src/Throw6Test.dart b/tests/language/src/Throw6Test.dart new file mode 100644 index 00000000000..eb7caf85db2 --- /dev/null +++ b/tests/language/src/Throw6Test.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException1 { + const MyException1([String message = "1"]) : message_ = message; + final String message_; +} + +class Helper { + Helper() : i = 0 { } + + int f1() { + int j = 0; + try { + j = func(); + } catch (var exception) { + i = i + 100; + print(exception.message_); + } finally { + i = i + 1000; + } + return i; + } + + // No catch in the same function for the type of exception being thrown + // in the try block here. We expect the handler if checks to fall thru, + // the finally block to run and an implicit rethrow to happen. + int func() { + i = 0; + try { + while (i < 10) { + i++; + } + if (i > 0) { + throw new MyException1("Test for MyException1 being thrown"); + } + } finally { + i = 800; + } + return i; + } + int i; +} + +class Throw6Test { + static testMain() { + Expect.equals(1900, new Helper().f1()); + } +} + +main() { + Throw6Test.testMain(); +} diff --git a/tests/language/src/Throw7NegativeTest.dart b/tests/language/src/Throw7NegativeTest.dart new file mode 100644 index 00000000000..66cf1b551af --- /dev/null +++ b/tests/language/src/Throw7NegativeTest.dart @@ -0,0 +1,45 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException1 { + const MyException1(String message = "1") : message_ = message; + final String message_; +} + +class Helper { + Helper() : i = 0 { } + + int f1() { + int j = 0; + try { + j = i; + } catch (var exception) { + i = i + 100; + print(exception.message_); + } + // Since there is a generic 'catch all' statement preceding this + // we expect to get a dead code error/warning over here. + catch (MyException1 exception) { + i = i + 100; + print(exception.message_); + } + finally { + i = i + 1000; + } + return i; + } + + int i; +} + +class Throw7NegativeTest { + static testMain() { + new Helper().f1(); + } +} + +main() { + Throw7NegativeTest.testMain(); +} diff --git a/tests/language/src/ThrowTest.dart b/tests/language/src/ThrowTest.dart new file mode 100644 index 00000000000..c2bb95eb432 --- /dev/null +++ b/tests/language/src/ThrowTest.dart @@ -0,0 +1,45 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing throw statement + +class MyException { + const MyException(String this.message_); + final String message_; +} + +class Helper { + static int f1(int i) { + try { + int j; + j = func(); + if (j > 0) { + throw new MyException("Test for exception being thrown"); + } + } catch (MyException exception) { + i = 100; + print(exception.message_); + } finally { + i = i + 800; + } + return i; + } + + static int func() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class ThrowTest { + static testMain() { + Expect.equals(900, Helper.f1(1)); + } +} + +main() { + ThrowTest.testMain(); +} diff --git a/tests/language/src/ToStringAsFixedTest.dart b/tests/language/src/ToStringAsFixedTest.dart new file mode 100644 index 00000000000..a07cb5bcfb6 --- /dev/null +++ b/tests/language/src/ToStringAsFixedTest.dart @@ -0,0 +1,119 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Test basic integer operations. + +class ToStringAsFixedTest { + static void testMain() { + Expect.equals("2.000", 2.0.toStringAsFixed(3)); + Expect.equals("2.100", 2.1.toStringAsFixed(3)); + Expect.equals("2.120", 2.12.toStringAsFixed(3)); + Expect.equals("2.123", 2.123.toStringAsFixed(3)); + Expect.equals("2.124", 2.1239.toStringAsFixed(3)); + Expect.equals("NaN", (0.0 / 0.0).toStringAsFixed(3)); + Expect.equals("Infinity", (1.0/0.0).toStringAsFixed(3)); + Expect.equals("-Infinity", (-1.0/0.0).toStringAsFixed(3)); + // FIXME: currently bigint formatting produces hexes. + // Expect.equals("1.1111111111111111e+21", 1111111111111111111111.0.toStringAsFixed(8)); + Expect.equals("0.1", 0.1.toStringAsFixed(1)); + Expect.equals("0.10", 0.1.toStringAsFixed(2)); + Expect.equals("0.100", 0.1.toStringAsFixed(3)); + Expect.equals("0.01", 0.01.toStringAsFixed(2)); + Expect.equals("0.010", 0.01.toStringAsFixed(3)); + Expect.equals("0.0100", 0.01.toStringAsFixed(4)); + Expect.equals("0.00", 0.001.toStringAsFixed(2)); + Expect.equals("0.001", 0.001.toStringAsFixed(3)); + Expect.equals("0.0010", 0.001.toStringAsFixed(4)); + Expect.equals("1.0000", 1.0.toStringAsFixed(4)); + Expect.equals("1.0", 1.0.toStringAsFixed(1)); + Expect.equals("1", 1.0.toStringAsFixed(0)); + Expect.equals("12", 12.0.toStringAsFixed(0)); + Expect.equals("1", 1.1.toStringAsFixed(0)); + Expect.equals("12", 12.1.toStringAsFixed(0)); + Expect.equals("1", 1.12.toStringAsFixed(0)); + Expect.equals("12", 12.12.toStringAsFixed(0)); + Expect.equals("0.0000006", 0.0000006.toStringAsFixed(7)); + Expect.equals("0.00000006", 0.00000006.toStringAsFixed(8)); + Expect.equals("0.000000060", 0.00000006.toStringAsFixed(9)); + Expect.equals("0.0000000600", 0.00000006.toStringAsFixed(10)); + Expect.equals("0", 0.0.toStringAsFixed(0)); + Expect.equals("0.0", 0.0.toStringAsFixed(1)); + Expect.equals("0.00", 0.0.toStringAsFixed(2)); + + // FIXME: currently bigint formatting produces hexes. + // Expect.equals("-1.1111111111111111e+21", (-1111111111111111111111.0).toStringAsFixed(8)); + Expect.equals("-0.1", (-0.1).toStringAsFixed(1)); + Expect.equals("-0.10", (-0.1).toStringAsFixed(2)); + Expect.equals("-0.100", (-0.1).toStringAsFixed(3)); + Expect.equals("-0.01", (-0.01).toStringAsFixed(2)); + Expect.equals("-0.010", (-0.01).toStringAsFixed(3)); + Expect.equals("-0.0100", (-0.01).toStringAsFixed(4)); + Expect.equals("-0.00", (-0.001).toStringAsFixed(2)); + Expect.equals("-0.001", (-0.001).toStringAsFixed(3)); + Expect.equals("-0.0010", (-0.001).toStringAsFixed(4)); + Expect.equals("-1.0000", (-1.0).toStringAsFixed(4)); + Expect.equals("-1.0", (-1.0).toStringAsFixed(1)); + Expect.equals("-1", (-1.0).toStringAsFixed(0)); + Expect.equals("-1", (-1.1).toStringAsFixed(0)); + Expect.equals("-12", (-12.1).toStringAsFixed(0)); + Expect.equals("-1", (-1.12).toStringAsFixed(0)); + Expect.equals("-12", (-12.12).toStringAsFixed(0)); + Expect.equals("-0.0000006", (-0.0000006).toStringAsFixed(7)); + Expect.equals("-0.00000006", (-0.00000006).toStringAsFixed(8)); + Expect.equals("-0.000000060", (-0.00000006).toStringAsFixed(9)); + Expect.equals("-0.0000000600", (-0.00000006).toStringAsFixed(10)); + Expect.equals("0", (-0.0).toStringAsFixed(0)); + Expect.equals("0.0", (-0.0).toStringAsFixed(1)); + Expect.equals("0.00", (-0.0).toStringAsFixed(2)); + + Expect.equals("1000", 1000.0.toStringAsFixed(0)); + Expect.equals("0", 0.00001.toStringAsFixed(0)); + Expect.equals("0.00001", 0.00001.toStringAsFixed(5)); + Expect.equals("0.00000000000000000010", 0.0000000000000000001.toStringAsFixed(20)); + Expect.equals("0.00001000000000000", 0.00001.toStringAsFixed(17)); + Expect.equals("1.00000000000000000", 1.0.toStringAsFixed(17)); + Expect.equals("1000000000000000128", 1000000000000000128.0.toStringAsFixed(0)); + Expect.equals("100000000000000128.0", 100000000000000128.0.toStringAsFixed(1)); + Expect.equals("10000000000000128.00", 10000000000000128.0.toStringAsFixed(2)); + // FIXME: currently bigint formatting produces hexes. + // Expect.equals("10000000000000128.00000000000000000000", 10000000000000128.0.toStringAsFixed(20)); + Expect.equals("0", 0.0.toStringAsFixed(0)); + Expect.equals("-42.000", (-42.0).toStringAsFixed(3)); + Expect.equals("-1000000000000000128", (-1000000000000000128.0).toStringAsFixed(0)); + Expect.equals("-0.00000000000000000010", (-0.0000000000000000001).toStringAsFixed(20)); + // FIXME: currently bigint formatting produces hexes. + // Expect.equals("0.12312312312312299889", 0.123123123123123.toStringAsFixed(20)); + // Test that we round up even when the last digit generated is even. + // dtoa does not do this in its original form. + Expect.equals("1", 0.5.toStringAsFixed(0)); + Expect.equals("-1", (-0.5).toStringAsFixed(0)); + Expect.equals("1.3", 1.25.toStringAsFixed(1)); + // This is bizare, but Spidermonkey and KJS behave the same. + // FIXME: consider if we'd like to unify this corner case. + // Expect.equals("234.2040", 234.20405.toStringAsFixed(4)); + Expect.equals("234.2041", 234.2040506.toStringAsFixed(4)); + { + bool thrown = false; + try { + 0.0.toStringAsFixed(-1); + } catch (final e) { + thrown = true; + } + Expect.equals(true, thrown); + } + { + bool thrown = false; + try { + 0.0.toStringAsFixed(22); + } catch (final e) { + thrown = true; + } + Expect.equals(true, thrown); + } + } +} + + +main() { + ToStringAsFixedTest.testMain(); +} diff --git a/tests/language/src/TopLevelEntry.dart b/tests/language/src/TopLevelEntry.dart new file mode 100644 index 00000000000..1b483b62fc9 --- /dev/null +++ b/tests/language/src/TopLevelEntry.dart @@ -0,0 +1,6 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { +} diff --git a/tests/language/src/TopLevelEntryTest.dart b/tests/language/src/TopLevelEntryTest.dart new file mode 100644 index 00000000000..1c4b7ede68a --- /dev/null +++ b/tests/language/src/TopLevelEntryTest.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source('TopLevelEntry.dart'); diff --git a/tests/language/src/TopLevelFile1.dart b/tests/language/src/TopLevelFile1.dart new file mode 100644 index 00000000000..160d3007ee4 --- /dev/null +++ b/tests/language/src/TopLevelFile1.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + Expect.equals(topLevelVar, 42); + Expect.equals(topLevelMethod(), 87); +} diff --git a/tests/language/src/TopLevelFile2.dart b/tests/language/src/TopLevelFile2.dart new file mode 100644 index 00000000000..26f4fd21fbf --- /dev/null +++ b/tests/language/src/TopLevelFile2.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +final topLevelVar = 42; + +topLevelMethod() => 87; diff --git a/tests/language/src/TopLevelFile3.dart b/tests/language/src/TopLevelFile3.dart new file mode 100644 index 00000000000..a42c558c751 --- /dev/null +++ b/tests/language/src/TopLevelFile3.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +main() { + Expect.equals(42, prefix.topLevelVar); +} diff --git a/tests/language/src/TopLevelFuncTest.dart b/tests/language/src/TopLevelFuncTest.dart new file mode 100644 index 00000000000..910595c13aa --- /dev/null +++ b/tests/language/src/TopLevelFuncTest.dart @@ -0,0 +1,60 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing top-level variables. + + +class TopLevelFuncTest { + static testMain() { + var z = [1, 10, 100, 1000]; + Expect.equals(Sum(z), 1111); + + var w = Window; + Expect.equals(w, "window"); + + Expect.equals(null, rgb); + Color = "ff0000"; + Expect.equals(rgb, "#ff0000"); + CheckColor("#ff0000"); + + Expect.equals("5", digits[5]); + + var e1 = Enumerator; + var e2 = Enumerator; + Expect.equals(0, e1()); + Expect.equals(1, e1()); + Expect.equals(2, e1()); + Expect.equals(0, e2()); + } +} + +void CheckColor(String expected) { + Expect.equals(expected, rgb); +} + +int Sum(List v) { + int s = 0; + for (int i = 0; i < v.length; i++) { + s += v[i]; + } + return s; +} + +get Window() { return "win" + "dow"; } + +String rgb; + +void set Color(col) { rgb = "#$col"; } + +List get digits() { + return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; +} + +Function get Enumerator() { + int k = 0; + return () => k++; +} + +main() { + TopLevelFuncTest.testMain(); +} diff --git a/tests/language/src/TopLevelGetterArrowSyntaxTest.dart b/tests/language/src/TopLevelGetterArrowSyntaxTest.dart new file mode 100644 index 00000000000..2e3a1b3fa01 --- /dev/null +++ b/tests/language/src/TopLevelGetterArrowSyntaxTest.dart @@ -0,0 +1,9 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +get getter() => 42; + +main() { + Expect.equals(42, getter); +} diff --git a/tests/language/src/TopLevelInInitializerTest.dart b/tests/language/src/TopLevelInInitializerTest.dart new file mode 100644 index 00000000000..9f86d8158b9 --- /dev/null +++ b/tests/language/src/TopLevelInInitializerTest.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that constructor initializers can access top level elements. + +final topLevelField = 1; +topLevelMethod() => 1; +get topLevelGetter() { return 1; } + +class Foo { + Foo.one() : x = topLevelField; + Foo.second() : x = topLevelMethod; + Foo.third() : x = topLevelGetter; + var x; +} + +main() { + Expect.equals(topLevelField, new Foo.one().x); + Expect.equals(topLevelMethod(), new Foo.second().x()); + Expect.equals(topLevelGetter, new Foo.third().x); +} diff --git a/tests/language/src/TopLevelMethodTest.dart b/tests/language/src/TopLevelMethodTest.dart new file mode 100644 index 00000000000..a86b7763160 --- /dev/null +++ b/tests/language/src/TopLevelMethodTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +untypedTopLevel() { + return 1; +} + +class TopLevelMethodTest { + static void testMain() { + Expect.equals(1, untypedTopLevel()); + } +} + +main() { + TopLevelMethodTest.testMain(); +} diff --git a/tests/language/src/TopLevelMultipleFilesTest.dart b/tests/language/src/TopLevelMultipleFilesTest.dart new file mode 100644 index 00000000000..43ed1267799 --- /dev/null +++ b/tests/language/src/TopLevelMultipleFilesTest.dart @@ -0,0 +1,7 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#source('TopLevelFile1.dart'); +#source('TopLevelFile2.dart'); + diff --git a/tests/language/src/TopLevelNonPrefixedLibraryTest.dart b/tests/language/src/TopLevelNonPrefixedLibraryTest.dart new file mode 100644 index 00000000000..029cd3689f5 --- /dev/null +++ b/tests/language/src/TopLevelNonPrefixedLibraryTest.dart @@ -0,0 +1,6 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#import('TopLevelPrefixedLibraryTest.lib'); +#source('TopLevelFile1.dart'); diff --git a/tests/language/src/TopLevelPrefixedLibraryTest.lib b/tests/language/src/TopLevelPrefixedLibraryTest.lib new file mode 100644 index 00000000000..dd1d049a39e --- /dev/null +++ b/tests/language/src/TopLevelPrefixedLibraryTest.lib @@ -0,0 +1,6 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#library('TopLevelPrefixedLibrary'); +#source('TopLevelFile2.dart'); diff --git a/tests/language/src/TopLevelVarTest.dart b/tests/language/src/TopLevelVarTest.dart new file mode 100644 index 00000000000..f22aca3cd5d --- /dev/null +++ b/tests/language/src/TopLevelVarTest.dart @@ -0,0 +1,32 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program testing top-level variables. + + +var a, b; + + +class TopLevelVarTest { + static testMain() { + Expect.equals(null, a); + Expect.equals(null, b); + a = b = 100; + b++; + Expect.equals(100, a); + Expect.equals(101, b); + + Expect.equals(111, x); + Expect.equals(112, y); + } +} + + +// Ensure that initializers work for both final and non-final variables. +final int x = 2 * 55 + 1; +int y = x + 1; + + +main() { + TopLevelVarTest.testMain(); +} diff --git a/tests/language/src/TryCatch10NegativeTest.dart b/tests/language/src/TryCatch10NegativeTest.dart new file mode 100644 index 00000000000..ca6463c67da --- /dev/null +++ b/tests/language/src/TryCatch10NegativeTest.dart @@ -0,0 +1,19 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to check that catch clause specifies a type. + + +class TryCatch10NegativeTest { + static void testMain() { + try { + throw "Hello"; + } catch (e) { // Need final, var or type. + Expec.equals(true, false); + } + } +} + +main() { + TryCatch10NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch1NegativeTest.dart b/tests/language/src/TryCatch1NegativeTest.dart new file mode 100644 index 00000000000..3ea1ecb99cf --- /dev/null +++ b/tests/language/src/TryCatch1NegativeTest.dart @@ -0,0 +1,54 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation as there is no catch block following +// a try. + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + try { + int j; + j = f2(); + j = f3(); + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch1NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch1NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch2NegativeTest.dart b/tests/language/src/TryCatch2NegativeTest.dart new file mode 100644 index 00000000000..22cca374f0e --- /dev/null +++ b/tests/language/src/TryCatch2NegativeTest.dart @@ -0,0 +1,54 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation as there is a catch block without +// a try. + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + catch (MyException exception) { + i = 100; + } catch (TestException e, StackTrace trace) { + i = 200; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch2NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch2NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch2Test.dart b/tests/language/src/TryCatch2Test.dart new file mode 100644 index 00000000000..d7d52fc9a06 --- /dev/null +++ b/tests/language/src/TryCatch2Test.dart @@ -0,0 +1,63 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. (Nested try/catch blocks). + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException([String message = ""]) : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + try { + int j; + j = f2(); + i = i + 1; + try { + j = f2() + f3() + j; + i = i + 1; + } catch (TestException e, StackTrace trace) { + j = 50; + } + j = f3() + j; + } catch (MyException exception) { + i = 100; + } catch (TestException e, StackTrace trace) { + i = 200; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch2Test { + static testMain() { + Expect.equals(3, Helper.f1(1)); + } +} + +main() { + TryCatch2Test.testMain(); +} diff --git a/tests/language/src/TryCatch3NegativeTest.dart b/tests/language/src/TryCatch3NegativeTest.dart new file mode 100644 index 00000000000..9d5c0003de4 --- /dev/null +++ b/tests/language/src/TryCatch3NegativeTest.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation as duplicate var definition + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + try { + int j; + j = f2(); + j = f3(); + } catch (TestException e, StackTrace e) { + i = 200; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch3NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch3NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch3Test.dart b/tests/language/src/TryCatch3Test.dart new file mode 100644 index 00000000000..ac6831eff02 --- /dev/null +++ b/tests/language/src/TryCatch3Test.dart @@ -0,0 +1,114 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException([String this.message_ = ""]); + String getMessage() { return message_; } + final String message_; +} + +class MyParameterizedException implements TestException { + const MyParameterizedException([String this.message_ = ""]); + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } + printStackTrace(TestException ex) { + print(ex); + } +} + +class Helper { + static int test1(int i) { + try { + int j; + j = f2(); + j = f3(); + try { + int k = f2(); + f3(); + } catch (MyException ex) { + int i = 10; + print(i); + } catch (TestException ex) { + int k = 10; + print(k); + } + try { + j = j + 24; + } catch (var e) { + i = 300; + print(e.getMessage()); + } + try { + j += 20; + } catch (final e) { + i = 400; + print(e.getMessage()); + } + try { + j += 40; + } catch (var e) { + i = 600; + print(e.getMessage()); + } + try { + j += 60; + } catch (var e, var trace) { + i = 700; + trace.printStackTrace(e); + print(e.getMessage()); + } + try { + j += 80; + } catch (final MyException e) { + i = 500; + print(e.getMessage()); + } + } catch (MyParameterizedException e, var trace) { + i = 800; + trace.printStackTrace(e); + throw; + } catch (MyException exception) { + i = 100; + print(exception.getMessage()); + } catch (TestException e, StackTrace trace) { + i = 200; + trace.printStackTrace(e); + } finally { + i = 900; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatchTest { + static testMain() { + Expect.equals(900, Helper.test1(1)); + } +} + +main() { + TryCatchTest.testMain(); +} diff --git a/tests/language/src/TryCatch4NegativeTest.dart b/tests/language/src/TryCatch4NegativeTest.dart new file mode 100644 index 00000000000..03024847666 --- /dev/null +++ b/tests/language/src/TryCatch4NegativeTest.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation illegal finally specifier. + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + try { + int j; + j = f2(); + j = f3(); + } finally (e) { + i = 200; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch4NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch4NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch5NegativeTest.dart b/tests/language/src/TryCatch5NegativeTest.dart new file mode 100644 index 00000000000..4b385ee1a05 --- /dev/null +++ b/tests/language/src/TryCatch5NegativeTest.dart @@ -0,0 +1,55 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation, illegal catch specifier. + +interface TestException { + String getMessage(); +} + +class MyException implements TestException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class StackTrace { + StackTrace() { } +} + +class Helper { + static int f1(int i) { + try { + int j; + j = f2(); + j = f3(); + } catch () { + i = 200; + } + return i; + } + + static int f2() { + return 2; + } + + static int f3() { + int i = 0; + while (i < 10) { + i++; + } + return i; + } +} + +class TryCatch5NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch5NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch6NegativeTest.dart b/tests/language/src/TryCatch6NegativeTest.dart new file mode 100644 index 00000000000..bfc601a933c --- /dev/null +++ b/tests/language/src/TryCatch6NegativeTest.dart @@ -0,0 +1,29 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation, illegal throw specifier. + +class Helper { + static int f1(int i) { + try { + int j; + j = 10; + throw; // An exception object is needed here. + } catch (var e) { + i = 200; + } + return i; + } +} + +class TryCatch6NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch6NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch7NegativeTest.dart b/tests/language/src/TryCatch7NegativeTest.dart new file mode 100644 index 00000000000..1574124051b --- /dev/null +++ b/tests/language/src/TryCatch7NegativeTest.dart @@ -0,0 +1,30 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation, illegal throw specifier. + +class Helper { + static int f1(int i) { + try { + int j; + j = 10; + } catch (var e) { + i = 200; + } finally { + throw; // An exception object is needed here. + } + return i; + } +} + +class TryCatch7NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch7NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch8NegativeTest.dart b/tests/language/src/TryCatch8NegativeTest.dart new file mode 100644 index 00000000000..f71d74af6a3 --- /dev/null +++ b/tests/language/src/TryCatch8NegativeTest.dart @@ -0,0 +1,35 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing try/catch statement without any exceptions +// being thrown. +// Negative test should fail compilation, illegal throw specifier. + +class Helper { + static int f1(int i) { + var a; + try { + int j; + j = 10; + } catch (var e) { + i = 200; + a = function f() { + int i = 0; + i = i + 20; + throw; // An exception object is needed here. + }; + } + a(); + return i; + } +} + +class TryCatch8NegativeTest { + static testMain() { + Expect.equals(1, Helper.f1(1)); + } +} + +main() { + TryCatch8NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatch9NegativeTest.dart b/tests/language/src/TryCatch9NegativeTest.dart new file mode 100644 index 00000000000..6ef9eee1e65 --- /dev/null +++ b/tests/language/src/TryCatch9NegativeTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test to check that the catching exception class is defined. + +class TryCatch9NegativeTest { + static void testMain() { + try { + throw "Hello"; + } catch (MammaMia e) { + // Exception undefined, error at compile time expected. Instead we are + // catching all. + } + } +} +main() { + TryCatch9NegativeTest.testMain(); +} diff --git a/tests/language/src/TryCatchTest.dart b/tests/language/src/TryCatchTest.dart new file mode 100644 index 00000000000..2c6f9ed230b --- /dev/null +++ b/tests/language/src/TryCatchTest.dart @@ -0,0 +1,146 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +class MyException { + MyException() {} +} + +class MyException1 extends MyException { + MyException1() : super() {} +} + +class MyException2 extends MyException { + MyException2() : super() {} +} + +class TryCatchTest { + static void test1() { + var foo = 0; + try { + throw new MyException1(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException1 e) { + foo = 2; + } catch (MyException e) { + foo = 3; + } + Expect.equals(2, foo); + } + + static void test2() { + var foo = 0; + try { + throw new MyException1(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException e) { + foo = 2; + } catch (MyException1 e) { + foo = 3; + } + Expect.equals(2, foo); + } + + static void test3() { + var foo = 0; + try { + throw new MyException(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException1 e) { + foo = 2; + } catch (MyException e) { + foo = 3; + } + Expect.equals(3, foo); + } + + static void test4() { + var foo = 0; + try { + try { + throw new MyException(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException1 e) { + foo = 2; + } + } catch (MyException e) { + Expect.equals(0, foo); + foo = 3; + } + Expect.equals(3, foo); + } + + static void test5() { + var foo = 0; + try { + throw new MyException1(); + } catch (MyException2 e) { + foo = 1; + } catch (var e) { + foo = 2; + } + Expect.equals(2, foo); + } + + static void test6() { + var foo = 0; + try { + throw new MyException(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException1 e) { + foo = 2; + } catch (var e) { + foo = 3; + } + Expect.equals(3, foo); + } + + static void test7() { + var foo = 0; + try { + try { + throw new MyException(); + } catch (MyException2 e) { + foo = 1; + } catch (MyException1 e) { + foo = 2; + } + } catch (var e) { + Expect.equals(0, foo); + foo = 3; + } + Expect.equals(3, foo); + } + + static void test8() { + var e = 3; + var caught = false; + try { + throw new MyException(); + } catch (var exc) { + caught = true; + } + Expect.equals(true, caught); + Expect.equals(3, e); + } + + static void testMain() { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); + test7(); + test8(); + } +} + +main() { + TryCatchTest.testMain(); +} diff --git a/tests/language/src/TypeTest.dart b/tests/language/src/TypeTest.dart new file mode 100644 index 00000000000..a55767317ae --- /dev/null +++ b/tests/language/src/TypeTest.dart @@ -0,0 +1,479 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// VMOptions=--enable_type_checks --enable_asserts +// +// Dart test program testing type checks. + +class TypeTest { + static test() { + int result = 0; + try { + int i = "hello"; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result = 1; + Expect.equals("int", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("i", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(12, error.line); + Expect.equals(15, error.column); + } + return result; + } + + static testSideEffect() { + int result = 0; + int index() { + result++; + return 0; + } + try { + List a = new List(1); + a[0] = 0; + a[index()]++; // Type check succeeds, but does not create side effects. + assert(a[0] == 1); + } catch (TypeError error) { + result = 100; + } + return result; + } + + static testArgument() { + int result = 0; + int f(int i) { + return i; + } + try { + int i = f("hello"); // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result = 1; + Expect.equals("int", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("i", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(49, error.line); + Expect.equals(15, error.column); + } + return result; + } + + static testReturn() { + int result = 0; + int f(String s) { + return s; + } + try { + int i = f("hello"); // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result = 1; + Expect.equals("int", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("function result", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(74, error.line); + Expect.equals(14, error.column); + } + return result; + } + + static int field; + static testField() { + int result = 0; + try { + field = "hello"; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result = 1; + Expect.equals("int", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("field", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(99, error.line); + Expect.equals(15, error.column); + } + return result; + } + + static testAnyFunction() { + int result = 0; + Function anyFunction; + f() { }; + anyFunction = f; // No error. + try { + int i = f; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result = 1; + Expect.equals("int", error.dstType); + Expect.equals("() => var", error.srcType); // TODO(regis): => Dynamic. + Expect.equals("i", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(123, error.line); + Expect.equals(15, error.column); + } + return result; + } + + static testVoidFunction() { + int result = 0; + Function anyFunction; + void acceptVoidFunObj(void voidFunObj(Object obj)) { }; + void acceptObjFunObj(Object objFunObj(Object obj)) { }; + void voidFunObj(Object obj) { }; + Object objFunObj(Object obj) { return obj; }; + anyFunction = voidFunObj; // No error. + anyFunction = objFunObj; // No error. + acceptVoidFunObj(voidFunObj); + acceptVoidFunObj(objFunObj); + acceptObjFunObj(objFunObj); + try { + acceptObjFunObj(voidFunObj); // Throws a TypeError. + } catch (TypeError error) { + result = 1; + Expect.equals("(Object) => Object", error.dstType); + Expect.equals("(Object) => void", error.srcType); + Expect.equals("objFunObj", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(145, error.line); + Expect.equals(33, error.column); + } + return result; + } + + static testFunctionNum() { + int result = 0; + Function anyFunction; + void acceptFunNum(void funNum(num num)) { }; + void funObj(Object obj) { }; + void funNum(num num) { }; + void funInt(int i) { }; + void funString(String s) { }; + anyFunction = funObj; // No error. + anyFunction = funNum; // No error. + anyFunction = funInt; // No error. + anyFunction = funString; // No error. + acceptFunNum(funObj); // No error. + acceptFunNum(funNum); // No error. + acceptFunNum(funInt); // No error. + try { + acceptFunNum(funString); // Throws an error. + } catch (TypeError error) { + result = 1; + Expect.equals("(num) => void", error.dstType); + Expect.equals("(String) => void", error.srcType); + Expect.equals("funNum", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(175, error.line); + Expect.equals(28, error.column); + } + return result; + } + + static testBoolCheck() { + int result = 0; + try { + bool i = !"hello"; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(209, error.line); + Expect.equals(17, error.column); + } + try { + while ("hello") {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(225, error.line); + Expect.equals(14, error.column); + } + try { + do {} while ("hello"); // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(241, error.line); + Expect.equals(20, error.column); + } + try { + for (;"hello";) {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(257, error.line); + Expect.equals(13, error.column); + } + try { + int i = "hello" ? 1 : 0; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(273, error.line); + Expect.equals(15, error.column); + } + try { + if ("hello") {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(289, error.line); + Expect.equals(11, error.column); + } + try { + if ("hello" || false) {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(305, error.line); + Expect.equals(11, error.column); + } + try { + if (false || "hello") {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("OneByteString", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(321, error.line); + Expect.equals(20, error.column); + } + try { + if (null) {}; // Throws a TypeError if type checks are enabled. + } catch (TypeError error) { + result++; + Expect.equals("bool", error.dstType); + Expect.equals("Null", error.srcType); + Expect.equals("boolean expression", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(337, error.line); + Expect.equals(11, error.column); + } + return result; + } + + + static int testFactory() { + int result = 0; + try { + var x = new C(); + } catch (TypeError error) { + result++; + Expect.equals("C", error.dstType); + Expect.equals("Smi", error.srcType); + Expect.equals("function result", error.dstName); + int pos = error.url.lastIndexOf("/", error.url.length); + if (pos == -1) { + pos = error.url.lastIndexOf("\\", error.url.length); + } + String subs = error.url.substring(pos + 1, error.url.length); + Expect.equals("TypeTest.dart", subs); + Expect.equals(472, error.line); + Expect.equals(12, error.column); + } + return result; + } + + static int testListAssigment() { + int result = 0; + { + var a = new List(5); + List a0 = a; + List ao = a; + List ai = a; + List an = a; + List as = a; + } + { + var a = new List(5); + List a0 = a; + List ao = a; + try { + List ai = a; + } catch (TypeError error) { + result++; + } + try { + List an = a; + } catch (TypeError error) { + result++; + } + try { + List as = a; + } catch (TypeError error) { + result++; + } + } + { + var a = new List(5); + List a0 = a; + List ao = a; + List ai = a; + List an = a; + try { + List as = a; + } catch (TypeError error) { + result++; + } + } + { + var a = new List(5); + List a0 = a; + List ao = a; + try { + List ai = a; + } catch (TypeError error) { + result++; + } + List an = a; + try { + List as = a; + } catch (TypeError error) { + result++; + } + } + { + var a = new List(5); + List a0 = a; + List ao = a; + try { + List ai = a; + } catch (TypeError error) { + result++; + } + try { + List an = a; + } catch (TypeError error) { + result++; + } + List as = a; + } + return result; + } + + static testMain() { + Expect.equals(1, test()); + Expect.equals(1, testSideEffect()); + Expect.equals(1, testArgument()); + Expect.equals(1, testReturn()); + Expect.equals(1, testField()); + Expect.equals(1, testAnyFunction()); + Expect.equals(1, testVoidFunction()); + Expect.equals(1, testFunctionNum()); + Expect.equals(9, testBoolCheck()); + Expect.equals(1, testFactory()); + Expect.equals(8, testListAssigment()); + } +} + + +class C { + factory C() { + return 1; // Implicit result type is 'C', not int. + } +} + + +main() { + TypeTest.testMain(); +} diff --git a/tests/language/src/TypeVariableBoundsTest.dart b/tests/language/src/TypeVariableBoundsTest.dart new file mode 100644 index 00000000000..efc65653156 --- /dev/null +++ b/tests/language/src/TypeVariableBoundsTest.dart @@ -0,0 +1,63 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test of parameterized factory methods. + +class Foo { + Foo(); + + // F is not assignable to num. + factory IFoo.bad() { return null; } /// 00: compile-time error + + factory IFoo.good() { return null; } + + // The bound of F is Object which is assignable to num. + factory IFoo.ish() { return null; } +} + +interface IFoo factory Foo { +} + +class FBound> {} + +class Bar extends FBound {} + +class SubBar extends Bar {} + +// String is not assignable to num. +class Baz extends Foo {} /// 01: compile-time error + +class Biz extends Foo {} + +Foo fi; + +// String is not assignable to num. +Foo fs; /// 02: static type error + +FBound fb; /// 03: static type error + +class Box { + + // Box.T is not assignable to num. + Foo t; /// 04: static type error + + makeFoo() { + // Box.T is not assignable to num. + return new Foo(); /// 05: compile-time error + } +} + +class TypeVariableBoundsTest { + static testMain() { + // String is not assignable to num. + var v1 = new Foo(); /// 06: compile-time error + + // String is not assignable to num. + Foo v2 = null; /// 07: static type error + } +} + +main() { + TypeVariableBoundsTest.testMain(); +} diff --git a/tests/language/src/TypeVariableScopeTest.dart b/tests/language/src/TypeVariableScopeTest.dart new file mode 100644 index 00000000000..32802f3211b --- /dev/null +++ b/tests/language/src/TypeVariableScopeTest.dart @@ -0,0 +1,42 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that type variables aren't in scope of static methods and factories. + +class Foo { + // T is not in scope for a static method. + static + Foo /// 00: compile-time error + m( + Foo /// 01: compile-time error + f) { + I x; /// 02: compile-time error + } + + // T is not in scope for a static method. + factory I( + I /// 03: compile-time error + i) { + I x; /// 04: compile-time error + } + + // T is not in scope for a static field. + static Foo f1; /// 05: compile-time error + + static + Foo /// 06: compile-time error + get f() { return null; } + + static void set f( + Foo /// 07: compile-time error + value) {} +} + +interface I factory Foo { + I(I i); +} + +main() { + Foo.m(null); +} diff --git a/tests/language/src/TypedMessageTest.dart b/tests/language/src/TypedMessageTest.dart new file mode 100644 index 00000000000..ecbf02356a9 --- /dev/null +++ b/tests/language/src/TypedMessageTest.dart @@ -0,0 +1,54 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing isolate communication with +// typed objects. +// VMOptions=--enable_type_checks --enable_asserts + +class TypedMessageTest { + static void testMain() { + LogClient.test(); + } +} + + +class LogClient { + static void test() { + new LogIsolate().spawn().then((SendPort remote) { + + List msg = new List(5); + for (int i = 0; i < 5; i++) { + msg[i] = i; + } + remote.call(msg).receive((int message, SendPort replyTo) { + Expect.equals(1, message); + }); + }); + } +} + + +class LogIsolate extends Isolate { + LogIsolate() : super() {} + + void main() { + print("Starting log server."); + + this.port.receive((List message, SendPort replyTo) { + print("Log $message"); + Expect.equals(5, message.length); + Expect.equals(0, message[0]); + Expect.equals(1, message[1]); + Expect.equals(2, message[2]); + Expect.equals(3, message[3]); + Expect.equals(4, message[4]); + this.port.close(); + replyTo.send(1, null); + print("Stopping log server."); + }); + } +} + +main() { + TypedMessageTest.testMain(); +} diff --git a/tests/language/src/Unary2Test.dart b/tests/language/src/Unary2Test.dart new file mode 100644 index 00000000000..d3fd59fd880 --- /dev/null +++ b/tests/language/src/Unary2Test.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test for testing binary operations. +// VMOptions=--disassemble --disassemble_stubs --print_classes + +class UnaryTest { + static foo() { return -4; } + static moo() { return +5; } + static testMain() { + Expect.equals(1, (UnaryTest.foo() + UnaryTest.moo())); + } +} + +main() { + UnaryTest.testMain(); +} diff --git a/tests/language/src/UnaryTest.dart b/tests/language/src/UnaryTest.dart new file mode 100644 index 00000000000..109aa7f77a5 --- /dev/null +++ b/tests/language/src/UnaryTest.dart @@ -0,0 +1,17 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Dart test for testing binary operations. + +class UnaryTest { + static foo() { return 4; } + static moo() { return +5; } + static testMain() { + Expect.equals(9.0, (UnaryTest.foo() + UnaryTest.moo())); + } +} + +main() { + UnaryTest.testMain(); +} diff --git a/tests/language/src/UnboundGetterTest.dart b/tests/language/src/UnboundGetterTest.dart new file mode 100644 index 00000000000..fc587121e20 --- /dev/null +++ b/tests/language/src/UnboundGetterTest.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Verify that an unbound getter is properly resolved at runtime. + +class A { + const A(); + foo() { + return y; + } +} + +class B extends A { + final y; + const B(val) : super(), y = val; +} + +class UnboundGetterTest { + static testMain() { + var b = new B(1); + print(b.foo()); + } +} + +main() { + UnboundGetterTest.testMain(); +} diff --git a/tests/language/src/UnhandledExceptionNegativeTest.dart b/tests/language/src/UnhandledExceptionNegativeTest.dart new file mode 100644 index 00000000000..f45091557a3 --- /dev/null +++ b/tests/language/src/UnhandledExceptionNegativeTest.dart @@ -0,0 +1,30 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing unhandled exceptions. + +class MyException { + const MyException(String message = "") : message_ = message; + String getMessage() { return message_; } + final String message_; +} + +class Helper { + static int f1(int i) { + int j; + j = i + 200; + j = j + 300; + throw new MyException("Unhandled Exception"); + return i; + } +} + +class UnhandledExceptionNegativeTest { + static testMain() { + Helper.f1(1); + } +} + +main() { + UnhandledExceptionNegativeTest.testMain(); +} diff --git a/tests/language/src/UnqualNameTest.dart b/tests/language/src/UnqualNameTest.dart new file mode 100644 index 00000000000..57a178c1a86 --- /dev/null +++ b/tests/language/src/UnqualNameTest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program to check that we can resolve unqualified identifiers + + +class B { + B(x, y) : b = y { } + var b; + + get_b() { + // Resolving unqualified instance method. + return really_really_get_it(); + } + + really_really_get_it() { + return 5; + } +} + + +class UnqualNameTest { + + static eleven() { + return 11; + } + + static testMain() { + var o = new B(3, 5); + Expect.equals(11, eleven()); // Unqualified static method call. + Expect.equals(5, o.get_b()); + + // Check whether we handle variable initializers correctly. + var a = 1, x, b = a + 3; + Expect.equals(5, a + b); + } +} + +main() { + UnqualNameTest.testMain(); +} diff --git a/tests/language/src/UnresolvedInFactoryNegativeTest.dart b/tests/language/src/UnresolvedInFactoryNegativeTest.dart new file mode 100644 index 00000000000..8166ac8f510 --- /dev/null +++ b/tests/language/src/UnresolvedInFactoryNegativeTest.dart @@ -0,0 +1,16 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that an unresolved method call in a factory is a resolution +// error. + +class A { + factory A() { + foo(); + } +} + +main() { + new A(); +} diff --git a/tests/language/src/UnresolvedTopLevelMethodNegativeTest.dart b/tests/language/src/UnresolvedTopLevelMethodNegativeTest.dart new file mode 100644 index 00000000000..2fc13cb421c --- /dev/null +++ b/tests/language/src/UnresolvedTopLevelMethodNegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that an unresolved method call at the top level does not crash +// the parser. + +var a = b(); + +main() { + print(a); +} diff --git a/tests/language/src/UnresolvedTopLevelVarNegativeTest.dart b/tests/language/src/UnresolvedTopLevelVarNegativeTest.dart new file mode 100644 index 00000000000..589ddd5e6c1 --- /dev/null +++ b/tests/language/src/UnresolvedTopLevelVarNegativeTest.dart @@ -0,0 +1,12 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Test that an unresolved identifier at the top level does not crash +// the parser. + +var a = b; + +main() { + print(a); +} diff --git a/tests/language/src/VarInitTest.dart b/tests/language/src/VarInitTest.dart new file mode 100644 index 00000000000..562d592ca21 --- /dev/null +++ b/tests/language/src/VarInitTest.dart @@ -0,0 +1,18 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Testing correct initialization of variables in scopes. + +class VarInitTest { + static void testMain() { + for (int i = 0; i < 10; i++) { + var x; + Expect.equals(null, x); + x = 1; + } + } +} + +main() { + VarInitTest.testMain(); +} diff --git a/tests/language/src/WhileTest.dart b/tests/language/src/WhileTest.dart new file mode 100644 index 00000000000..378048a842b --- /dev/null +++ b/tests/language/src/WhileTest.dart @@ -0,0 +1,46 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Dart test program for testing while statement. + +class Helper { + static int f1(bool b) { + while (b) + return 1; + + return 2; + } + + static int f2(bool b) { + while (b) { + return 1; + } + return 2; + } + + static int f3(int n) { + int i = 0; + while (i < n) { + i++; + } + return i; + } +} + +class WhileTest { + static testMain() { + Expect.equals(1, Helper.f1(true)); + Expect.equals(2, Helper.f1(false)); + Expect.equals(1, Helper.f2(true)); + Expect.equals(2, Helper.f2(false)); + Expect.equals(0, Helper.f3(-2)); + Expect.equals(0, Helper.f3(-1)); + Expect.equals(0, Helper.f3(0)); + Expect.equals(1, Helper.f3(1)); + Expect.equals(2, Helper.f3(2)); + } +} + +main() { + WhileTest.testMain(); +} diff --git a/tests/language/src/library1.dart b/tests/language/src/library1.dart new file mode 100644 index 00000000000..6dfa011eb71 --- /dev/null +++ b/tests/language/src/library1.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#library("library1.dart"); + +var foo; diff --git a/tests/language/src/library10.dart b/tests/language/src/library10.dart new file mode 100644 index 00000000000..b8b44c7dae1 --- /dev/null +++ b/tests/language/src/library10.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#library("library10.dart"); + +#import("library11.dart", prefix : "lib11"); +class Library10 { + Library10(this.fld); + func() { + return 2; + } + var fld; + static static_func() { + var result = 0; + var obj = new lib11.Library11(4); + result = obj.fld; + Expect.equals(4, result); + result += obj.func(); + Expect.equals(7, result); + result += lib11.Library11.static_func(); + Expect.equals(9, result); + result += lib11.Library11.static_fld; + Expect.equals(10, result); + Expect.equals(100, lib11.top_level11); + Expect.equals(200, lib11.top_level_func11()); + return 3; + } + static var static_fld = 4; +} + +final int top_level10 = 10; +top_level_func10() { + return 20; +} diff --git a/tests/language/src/library11.dart b/tests/language/src/library11.dart new file mode 100644 index 00000000000..44b44f023c6 --- /dev/null +++ b/tests/language/src/library11.dart @@ -0,0 +1,30 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#library("library11.dart"); + +class Library11 { + Library11(this.fld); + Library11.namedConstructor(this.fld); + func() { + return 3; + } + var fld; + static static_func() { + return 2; + } + static var static_fld = 1; +} + +class Library111 { + Library111.namedConstructor(T this.fld); + T fld; +} + + +final int top_level11 = 100; +top_level_func11() { + return 200; +} diff --git a/tests/language/src/library12.dart b/tests/language/src/library12.dart new file mode 100644 index 00000000000..26b6b4b6464 --- /dev/null +++ b/tests/language/src/library12.dart @@ -0,0 +1,36 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// + +#library("library12.dart"); + +#import("library11.dart"); +class Library12 { + Library12(this.fld); + func() { + return 2; + } + var fld; + static static_func() { + var result = 0; + var obj = new Library11(4); + result = obj.fld; + Expect.equals(4, result); + result += obj.func(); + Expect.equals(7, result); + result += Library11.static_func(); + Expect.equals(9, result); + result += Library11.static_fld; + Expect.equals(10, result); + Expect.equals(100, top_level11); + Expect.equals(200, top_level_func11()); + return 3; + } + static var static_fld = 4; +} + +final int top_level12 = 10; +top_level_func12() { + return 20; +} diff --git a/tests/language/src/readuntil_test.dat b/tests/language/src/readuntil_test.dat new file mode 100644 index 00000000000..0c7c848e70f --- /dev/null +++ b/tests/language/src/readuntil_test.dat @@ -0,0 +1 @@ +Hello Dart, wassup! diff --git a/tests/language/testcfg.py b/tests/language/testcfg.py new file mode 100644 index 00000000000..2df39433e47 --- /dev/null +++ b/tests/language/testcfg.py @@ -0,0 +1,8 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import testing + +def GetConfiguration(context, root): + return testing.StandardTestConfiguration(context, root) diff --git a/tests/stub-generator/src/MintMakerFullyIsolatedTest.dart b/tests/stub-generator/src/MintMakerFullyIsolatedTest.dart new file mode 100644 index 00000000000..66b6486ddd4 --- /dev/null +++ b/tests/stub-generator/src/MintMakerFullyIsolatedTest.dart @@ -0,0 +1,117 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// IsolateStubs=MintMakerFullyIsolatedTest.dart:Mint,Purse + +interface Purse factory PurseImpl { + Purse(); + // FIXME(benl): need to autogen constructors... + void init(Mint$Proxy mint, int balance); + int queryBalance(); + Purse$Proxy sproutPurse(); + void deposit(int amount, Purse$Proxy source); +} + +interface Mint factory MintImpl { + Mint(); + + Purse$Proxy createPurse(int balance); +} + +class MintImpl implements Mint { + + MintImpl() { } + + Purse$Proxy createPurse(int balance) { + Purse$Proxy purse = new Purse$ProxyImpl.createIsolate(); + Mint$Proxy thisProxy = new Mint$ProxyImpl.localProxy(this); + purse.init(thisProxy, balance); + return purse; + } + +} + +class PurseImpl implements Purse { + + // FIXME(benl): autogenerate constructor, get rid of init(...). + //PurseImpl(this._mint, this._balance) { } + PurseImpl() { } + + init(Mint$Proxy mint, int balance) { + this._mint = mint; + this._balance = balance; + } + + int queryBalance() { + return _balance; + } + + Purse$Proxy sproutPurse() { + return _mint.createPurse(0); + } + + void deposit(int amount, Purse$Proxy proxy) { + Purse$ProxyImpl impl = proxy.dynamic; + PurseImpl source = impl.local; + if (source._balance < amount) throw "Not enough dough."; + _balance += amount; + source._balance -= amount; + } + + Mint$Proxy _mint; + int _balance; + +} + +class MintMakerFullyIsolatedTest { + + static void testMain() { + Mint$Proxy mint = new Mint$ProxyImpl.createIsolate(); + Purse$Proxy purse = mint.createPurse(100); + expectEquals(100, purse.queryBalance()); + + Purse$Proxy sprouted = purse.sproutPurse(); + expectEquals(0, sprouted.queryBalance()); + + sprouted.deposit(5, purse); + expectEquals(0 + 5, sprouted.queryBalance()); + expectEquals(100 - 5, purse.queryBalance()); + + sprouted.deposit(42, purse); + expectEquals(0 + 5 + 42, sprouted.queryBalance()); + expectEquals(100 - 5 - 42, purse.queryBalance()); + + expectDone(6); + } + + static List results; + + static void expectEquals(int expected, Promise promise) { + if (results === null) { + results = new List(); + } + results.add(promise.then((int actual) { + Expect.equals(expected, actual); + })); + } + + static void expectDone(int n) { + if (results === null) { + Expect.equals(0, n); + print('##DONE##'); + } else { + Promise done = new Promise(); + done.waitFor(results, results.length); + done.then((ignored) { + Expect.equals(n, results.length); + print('##DONE##'); + }); + } + } + +} + +main() { + MintMakerFullyIsolatedTest.testMain(); +} diff --git a/tests/stub-generator/src/MintMakerPromiseWithStubsTest.dart b/tests/stub-generator/src/MintMakerPromiseWithStubsTest.dart new file mode 100644 index 00000000000..ca8d5b0a51a --- /dev/null +++ b/tests/stub-generator/src/MintMakerPromiseWithStubsTest.dart @@ -0,0 +1,125 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// IsolateStubs=MintMakerPromiseWithStubsTest.dart:Mint,Purse + +interface Mint factory MintImpl { + + Mint(); + + Purse createPurse(int balance); + +} + +interface Purse factory PurseImpl { + + Purse(); + + int queryBalance(); + Purse sproutPurse(); + void deposit(int amount, Purse$Proxy source); + +} + +class MintImpl implements Mint { + + MintImpl() { } + + Purse createPurse(int balance) { + PurseImpl purse = new PurseImpl(); + purse.init(this, balance); + + return purse; + } + +} + +class PurseImpl implements Purse { + + PurseImpl() { } + // TODO(benl): implement stub constructors. + // Note that this constructor should _not_ be in the Purse interface, + // only this isolate is trusted to construct purses. + //PurseImpl(this._mint, this._balance) { } + void init(Mint mint, int balance) { + this._mint = mint; + this._balance = balance; + } + + int queryBalance() { + return _balance; + } + + Purse sproutPurse() { + return _mint.createPurse(0); + } + + void deposit(int amount, Purse$Proxy proxy) { + if (amount < 0) throw "Ha ha"; + // Because we are in the same isolate as the other purse, we can + // retrieve the proxy's local PurseImpl object and act on it + // directly. Further, a forged purse will not be convertible, and + // so an attempt to use it will fail. + PurseImpl source = proxy.dynamic.local; + if (source._balance < amount) throw "Not enough dough."; + _balance += amount; + source._balance -= amount; + } + + Mint _mint; + int _balance; + +} + +class MintMakerPromiseWithStubsTest { + + static void testMain() { + Mint$Proxy mint = new Mint$ProxyImpl.createIsolate(); + Purse$Proxy purse = mint.createPurse(100); + expectEquals(100, purse.queryBalance()); + + Purse$Proxy sprouted = purse.sproutPurse(); + expectEquals(0, sprouted.queryBalance()); + + sprouted.deposit(5, purse); + expectEquals(0 + 5, sprouted.queryBalance()); + expectEquals(100 - 5, purse.queryBalance()); + + sprouted.deposit(42, purse); + expectEquals(0 + 5 + 42, sprouted.queryBalance()); + expectEquals(100 - 5 - 42, purse.queryBalance()); + + expectDone(6); + } + + static List results; + + static void expectEquals(int expected, Promise promise) { + if (results === null) { + results = new List(); + } + results.add(promise.then((int actual) { + Expect.equals(expected, actual); + })); + } + + static void expectDone(int n) { + if (results === null) { + Expect.equals(0, n); + print('##DONE##'); + } else { + Promise done = new Promise(); + done.waitFor(results, results.length); + done.then((ignored) { + Expect.equals(n, results.length); + print('##DONE##'); + }); + } + } + +} + +main() { + MintMakerPromiseWithStubsTest.testMain(); +} diff --git a/tests/stub-generator/stub-generator.status b/tests/stub-generator/stub-generator.status new file mode 100644 index 00000000000..f28aa687c5b --- /dev/null +++ b/tests/stub-generator/stub-generator.status @@ -0,0 +1,28 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +prefix stub-generator + +[ $arch == ia32 ] +MintMakerFullyIsolatedTest: Skip # Bug 5283149 +MintMakerPromiseWithStubsTest: Fail # Bug 5384756 + +[ $arch == dartc ] +MintMakerFullyIsolatedTest: Fail # Bug 5344878 +MintMakerPromiseWithStubsTest: Fail # Bug 5283149 + +[ $arch == x64 ] +*: Skip + +[ $arch == simarm ] +*: Skip + +[ $arch == arm ] +*: Skip + +[ $arch == dartium ] +*: Skip + +[ $arch == chromium ] +*: Skip diff --git a/tests/stub-generator/testcfg.py b/tests/stub-generator/testcfg.py new file mode 100644 index 00000000000..24333edcec5 --- /dev/null +++ b/tests/stub-generator/testcfg.py @@ -0,0 +1,96 @@ +# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import os +import re +import shutil +import tempfile +import test +import testing +import utils + +from os.path import join, exists, isdir + +class DartStubTestCase(testing.StandardTestCase): + def __init__(self, context, path, filename, mode, arch): + super(DartStubTestCase, self).__init__(context, path, filename, mode, arch) + self.filename = filename + self.mode = mode + self.arch = arch + + def GetStubs(self): + source = self.GetSource() + stub_classes = utils.ParseTestOptions(test.ISOLATE_STUB_PATTERN, source, + self.context.workspace) + (interface, _, classes) = stub_classes[0].partition(':') + (interface, _, implementation) = interface.partition('+') + return (interface, classes, implementation) + + def IsFailureOutput(self, output): + return output.exit_code != 0 or not '##DONE##' in output.stdout + + def BeforeRun(self): + command = self.context.GetDartC(self.mode, 'dartc') + (interface, classes, _) = self.GetStubs() + d = join(self.GetPath(), 'generated') + if not isdir(d): + os.mkdir(d) + tmpdir = tempfile.mkdtemp() + src = join(self.GetPath(), interface) + dest = join(self.GetPath(), 'generated', interface) + self.RunCommand(command + [ src, + # dartc generates output even if it has no + # output to generate. + '-out', tmpdir, + '-isolate-stub-out', dest, + '-generate-isolate-stubs', classes ]) + shutil.rmtree(tmpdir) + d = open(dest, 'a') + s = open(src, 'r') + d.write(s.read()) + + def GetCommand(self): + # Parse the options by reading the .dart source file. + source = self.GetSource() + vm_options = utils.ParseTestOptions(test.VM_OPTIONS_PATTERN, source, + self.context.workspace) + dart_options = utils.ParseTestOptions(test.DART_OPTIONS_PATTERN, source, + self.context.workspace) + (interface, _, implementation) = self.GetStubs() + + # Combine everything into a command array and return it. + command = self.context.GetDart(self.mode, self.arch) + files = [ join(self.GetPath(), 'generated', interface) ] + if vm_options: command += vm_options + if dart_options: command += dart_options + else: command += files + return command + + +class DartStubTestConfiguration(testing.StandardTestConfiguration): + def __init__(self, context, root): + super(DartStubTestConfiguration, self).__init__(context, root) + + def ListTests(self, current_path, path, mode, arch): + dartc = self.context.GetDartC(mode, 'dartc') + if not os.access(dartc[0], os.X_OK): + return [] + tests = [] + for root, dirs, files in os.walk(join(self.root, 'src')): + if root.endswith('/generated'): + continue + for f in [x for x in files if self.IsTest(x)]: + test_path = current_path + [ f[:-5] ] # Remove .dart suffix. + if not self.Contains(path, test_path): + continue + tests.append(DartStubTestCase(self.context, + test_path, + join(root, f), + mode, + arch)) + return tests + + +def GetConfiguration(context, root): + return DartStubTestConfiguration(context, root)