Big merge from experimental to bleeding edge.
Review URL: https://codereview.chromium.org//11783009 git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@16687 260f80e4-7a28-3924-810f-c04153c831b5
This commit is contained in:
@@ -353,7 +353,7 @@ class ArgParser {
|
||||
_setOption(Map results, _Option option, value) {
|
||||
// See if it's one of the allowed values.
|
||||
if (option.allowed != null) {
|
||||
_validate(option.allowed.some((allow) => allow == value),
|
||||
_validate(option.allowed.any((allow) => allow == value),
|
||||
'"$value" is not an allowed value for option "${option.name}".');
|
||||
}
|
||||
|
||||
@@ -544,7 +544,7 @@ class ArgResults {
|
||||
}
|
||||
|
||||
/** Get the names of the options as a [Collection]. */
|
||||
Collection<String> get options => _options.keys;
|
||||
Collection<String> get options => _options.keys.toList();
|
||||
}
|
||||
|
||||
class _Option {
|
||||
@@ -630,8 +630,8 @@ class _Usage {
|
||||
if (option.help != null) write(2, option.help);
|
||||
|
||||
if (option.allowedHelp != null) {
|
||||
var allowedNames = option.allowedHelp.keys;
|
||||
allowedNames.sort((a, b) => a.compareTo(b));
|
||||
var allowedNames = option.allowedHelp.keys.toList();
|
||||
allowedNames.sort();
|
||||
newline();
|
||||
for (var name in allowedNames) {
|
||||
write(1, getAllowedTitle(name));
|
||||
|
||||
@@ -450,8 +450,8 @@ main() {
|
||||
parser.addOption('meow', defaultsTo: 'kitty');
|
||||
var args = parser.parse([]);
|
||||
expect(args.options, hasLength(2));
|
||||
expect(args.options.some((o) => o == 'woof'), isTrue);
|
||||
expect(args.options.some((o) => o == 'meow'), isTrue);
|
||||
expect(args.options.any((o) => o == 'woof'), isTrue);
|
||||
expect(args.options.any((o) => o == 'meow'), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -338,7 +338,7 @@ class int32 implements intx {
|
||||
int numberOfTrailingZeros() => _numberOfTrailingZeros(_i);
|
||||
|
||||
List<int> toBytes() {
|
||||
List<int> result = new List<int>(4);
|
||||
List<int> result = new List<int>.fixedLength(4);
|
||||
result[0] = _i & 0xff;
|
||||
result[1] = (_i >> 8) & 0xff;
|
||||
result[2] = (_i >> 16) & 0xff;
|
||||
|
||||
@@ -625,7 +625,7 @@ class int64 implements intx {
|
||||
}
|
||||
|
||||
List<int> toBytes() {
|
||||
List<int> result = new List<int>(8);
|
||||
List<int> result = new List<int>.fixedLength(8);
|
||||
result[0] = _l & 0xff;
|
||||
result[1] = (_l >> 8) & 0xff;
|
||||
result[2] = ((_m << 6) & 0xfc) | ((_l >> 16) & 0x3f);
|
||||
|
||||
@@ -174,7 +174,7 @@ class int64VMTest {
|
||||
testSet.add(new int64.fromInt(pow));
|
||||
}
|
||||
|
||||
TEST_VALUES = new List<int64>(testSet.length);
|
||||
TEST_VALUES = new List<int64>.fixedLength(testSet.length);
|
||||
int index = 0;
|
||||
for (int64 val in testSet) {
|
||||
TEST_VALUES[index++] = val;
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
/// "http://example.com/whatsit/create",
|
||||
/// fields: {"name": "doodle", "color": "blue"})
|
||||
/// .chain((response) => client.get(response.bodyFields['uri']))
|
||||
/// .transform((response) => print(response.body))
|
||||
/// .then((response) => print(response.body))
|
||||
/// .onComplete((_) => client.close());
|
||||
///
|
||||
/// You can also exert more fine-grained control over your requests and
|
||||
@@ -53,6 +53,7 @@
|
||||
|
||||
library http;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:scalarlist';
|
||||
import 'dart:uri';
|
||||
|
||||
@@ -168,6 +169,6 @@ Future<Uint8List> readBytes(url, {Map<String, String> headers}) =>
|
||||
Future _withClient(Future fn(Client)) {
|
||||
var client = new Client();
|
||||
var future = fn(client);
|
||||
future.onComplete((_) => client.close());
|
||||
future.catchError((_) {}).then((_) => client.close());
|
||||
return future;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library base_client;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:scalarlist';
|
||||
import 'dart:uri';
|
||||
@@ -72,7 +73,7 @@ abstract class BaseClient implements Client {
|
||||
/// For more fine-grained control over the request and response, use [send] or
|
||||
/// [get] instead.
|
||||
Future<String> read(url, {Map<String, String> headers}) {
|
||||
return get(url, headers: headers).transform((response) {
|
||||
return get(url, headers: headers).then((response) {
|
||||
_checkResponseSuccess(url, response);
|
||||
return response.body;
|
||||
});
|
||||
@@ -88,7 +89,7 @@ abstract class BaseClient implements Client {
|
||||
/// For more fine-grained control over the request and response, use [send] or
|
||||
/// [get] instead.
|
||||
Future<Uint8List> readBytes(url, {Map<String, String> headers}) {
|
||||
return get(url, headers: headers).transform((response) {
|
||||
return get(url, headers: headers).then((response) {
|
||||
_checkResponseSuccess(url, response);
|
||||
return response.bodyBytes;
|
||||
});
|
||||
@@ -108,7 +109,7 @@ abstract class BaseClient implements Client {
|
||||
[Map<String, String> fields]) {
|
||||
// Wrap everything in a Future block so that synchronous validation errors
|
||||
// are passed asynchronously through the Future chain.
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (url is String) url = new Uri.fromString(url);
|
||||
var request = new Request(method, url);
|
||||
|
||||
@@ -116,7 +117,7 @@ abstract class BaseClient implements Client {
|
||||
if (fields != null && !fields.isEmpty) request.bodyFields = fields;
|
||||
|
||||
return send(request);
|
||||
}).chain(Response.fromStream);
|
||||
}).then(Response.fromStream);
|
||||
}
|
||||
|
||||
/// Throws an error if [response] is not successful.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library base_request;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
import 'dart:uri';
|
||||
@@ -105,7 +106,7 @@ abstract class BaseRequest {
|
||||
/// requests.
|
||||
Future<StreamedResponse> send() {
|
||||
var client = new Client();
|
||||
return client.send(this).transform((response) {
|
||||
return client.send(this).then((response) {
|
||||
// TODO(nweiz): This makes me sick to my stomach, but it's currently the
|
||||
// best way to listen for the response stream being closed. Kill it with
|
||||
// fire once issue 4202 is fixed.
|
||||
@@ -117,7 +118,7 @@ abstract class BaseRequest {
|
||||
});
|
||||
|
||||
return response;
|
||||
});
|
||||
}).catchError((_) { client.close(); });
|
||||
}
|
||||
|
||||
/// Throws an error if this request has been finalized.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library client;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:scalarlist';
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library io_client;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'base_client.dart';
|
||||
@@ -25,6 +26,7 @@ class IOClient extends BaseClient {
|
||||
|
||||
var completer = new Completer<StreamedResponse>();
|
||||
var connection = _inner.openUrl(request.method, request.url);
|
||||
bool completed = false;
|
||||
connection.followRedirects = request.followRedirects;
|
||||
connection.maxRedirects = request.maxRedirects;
|
||||
connection.onError = (e) {
|
||||
@@ -33,9 +35,10 @@ class IOClient extends BaseClient {
|
||||
// onRequest or onResponse callbacks get passed to onError. If the
|
||||
// completer has already fired, we want to re-throw those exceptions
|
||||
// to the top level so that they aren't silently ignored.
|
||||
if (completer.future.isComplete) throw e;
|
||||
if (completed) throw e;
|
||||
|
||||
completer.completeException(e);
|
||||
completed = true;
|
||||
completer.completeError(e);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -57,6 +60,9 @@ class IOClient extends BaseClient {
|
||||
var headers = <String>{};
|
||||
response.headers.forEach((key, value) => headers[key] = value);
|
||||
|
||||
if (completed) return;
|
||||
|
||||
completed = true;
|
||||
completer.complete(new StreamedResponse(
|
||||
response.inputStream,
|
||||
response.statusCode,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library mock_client;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'base_client.dart';
|
||||
@@ -31,7 +32,7 @@ class MockClient extends BaseClient {
|
||||
/// [Response]s.
|
||||
MockClient(MockClientHandler fn)
|
||||
: this._((baseRequest, bodyStream) {
|
||||
return consumeInputStream(bodyStream).chain((bodyBytes) {
|
||||
return consumeInputStream(bodyStream).then((bodyBytes) {
|
||||
var request = new Request(baseRequest.method, baseRequest.url);
|
||||
request.persistentConnection = baseRequest.persistentConnection;
|
||||
request.followRedirects = baseRequest.followRedirects;
|
||||
@@ -41,7 +42,7 @@ class MockClient extends BaseClient {
|
||||
request.finalize();
|
||||
|
||||
return fn(request);
|
||||
}).transform((response) {
|
||||
}).then((response) {
|
||||
var stream = new ListInputStream();
|
||||
stream.write(response.bodyBytes);
|
||||
stream.markEndOfStream();
|
||||
@@ -62,7 +63,7 @@ class MockClient extends BaseClient {
|
||||
/// sends [StreamedResponse]s.
|
||||
MockClient.streaming(MockClientStreamHandler fn)
|
||||
: this._((request, bodyStream) {
|
||||
return fn(request, bodyStream).transform((response) {
|
||||
return fn(request, bodyStream).then((response) {
|
||||
return new StreamedResponse(
|
||||
response.stream,
|
||||
response.statusCode,
|
||||
@@ -78,7 +79,7 @@ class MockClient extends BaseClient {
|
||||
/// Sends a request.
|
||||
Future<StreamedResponse> send(BaseRequest request) {
|
||||
var bodyStream = request.finalize();
|
||||
return async.chain((_) => _handler(request, bodyStream));
|
||||
return async.then((_) => _handler(request, bodyStream));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ class MultipartFile {
|
||||
static Future<MultipartFile> fromFile(String field, File file,
|
||||
{String filename, ContentType contentType}) {
|
||||
if (filename == null) filename = new Path(file.name).filename;
|
||||
return file.length().transform((length) {
|
||||
return file.length().then((length) {
|
||||
return new MultipartFile(field, file.openInputStream(), length,
|
||||
filename: filename,
|
||||
contentType: contentType);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library multipart_request;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'dart:uri';
|
||||
@@ -106,7 +107,7 @@ class MultipartRequest extends BaseRequest {
|
||||
writeAscii('--$boundary\r\n');
|
||||
writeAscii(_headerForFile(file));
|
||||
return writeInputToInput(file.finalize(), stream)
|
||||
.transform((_) => writeLine());
|
||||
.then((_) => writeLine());
|
||||
}).then((_) {
|
||||
// TODO(nweiz): pass any errors propagated through this future on to
|
||||
// the stream. See issue 3657.
|
||||
@@ -156,7 +157,7 @@ class MultipartRequest extends BaseRequest {
|
||||
/// [length].
|
||||
String _boundaryString(int length) {
|
||||
var prefix = "dart-http-boundary-";
|
||||
var list = new List<int>(length - prefix.length);
|
||||
var list = new List<int>.fixedLength(length - prefix.length);
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
list[i] = _BOUNDARY_CHARACTERS[
|
||||
_random.nextInt(_BOUNDARY_CHARACTERS.length)];
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library response;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:scalarlist';
|
||||
|
||||
@@ -65,7 +66,7 @@ class Response extends BaseResponse {
|
||||
/// Creates a new HTTP response by waiting for the full body to become
|
||||
/// available from a [StreamedResponse].
|
||||
static Future<Response> fromStream(StreamedResponse response) {
|
||||
return consumeInputStream(response.stream).transform((body) {
|
||||
return consumeInputStream(response.stream).then((body) {
|
||||
return new Response.bytes(
|
||||
body,
|
||||
response.statusCode,
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
library utils;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:crypto';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
import 'dart:scalarlist';
|
||||
import 'dart:uri';
|
||||
import 'dart:utf';
|
||||
@@ -36,7 +36,7 @@ String mapToQuery(Map<String, String> map) {
|
||||
var pairs = <List<String>>[];
|
||||
map.forEach((key, value) =>
|
||||
pairs.add([encodeUriComponent(key), encodeUriComponent(value)]));
|
||||
return Strings.join(pairs.map((pair) => "${pair[0]}=${pair[1]}"), "&");
|
||||
return Strings.join(pairs.mappedBy((pair) => "${pair[0]}=${pair[1]}"), "&");
|
||||
}
|
||||
|
||||
/// Adds all key/value pairs from [source] to [destination], overwriting any
|
||||
@@ -140,7 +140,7 @@ Future<List<int>> consumeInputStream(InputStream stream) {
|
||||
var buffer = <int>[];
|
||||
stream.onClosed = () => completer.complete(buffer);
|
||||
stream.onData = () => buffer.addAll(stream.read());
|
||||
stream.onError = completer.completeException;
|
||||
stream.onError = completer.completeError;
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@@ -183,10 +183,10 @@ Future get async {
|
||||
/// The return values of all [Future]s are discarded. Any errors will cause the
|
||||
/// iteration to stop and will be piped through the return value.
|
||||
Future forEachFuture(Iterable input, Future fn(element)) {
|
||||
var iterator = input.iterator();
|
||||
var iterator = input.iterator;
|
||||
Future nextElement(_) {
|
||||
if (!iterator.hasNext) return new Future.immediate(null);
|
||||
return fn(iterator.next()).chain(nextElement);
|
||||
if (!iterator.moveNext()) return new Future.immediate(null);
|
||||
return fn(iterator.current).then(nextElement);
|
||||
}
|
||||
return nextElement(null);
|
||||
}
|
||||
|
||||
@@ -10,14 +10,14 @@ library testing;
|
||||
/// allows test code to set up a local request handler in order to fake a server
|
||||
/// that responds to HTTP requests:
|
||||
///
|
||||
/// import 'dart:json';
|
||||
/// import 'dart:json' as json;
|
||||
/// import 'package:http/testing.dart';
|
||||
///
|
||||
/// var client = new MockClient((request) {
|
||||
/// if (request.url.path != "/data.json") {
|
||||
/// return new Response("", 404);
|
||||
/// }
|
||||
/// return new Response(JSON.stringify({
|
||||
/// return new Response(json.stringify({
|
||||
/// 'numbers': [1, 4, 15, 19, 214]
|
||||
/// }, 200, headers: {
|
||||
/// 'content-type': 'application/json'
|
||||
|
||||
@@ -21,12 +21,12 @@ void main() {
|
||||
request.headers[HttpHeaders.CONTENT_TYPE] =
|
||||
'application/json; charset=utf-8';
|
||||
|
||||
var future = client.send(request).chain((response) {
|
||||
var future = client.send(request).then((response) {
|
||||
expect(response.request, equals(request));
|
||||
expect(response.statusCode, equals(200));
|
||||
return consumeInputStream(response.stream);
|
||||
}).transform((bytes) => new String.fromCharCodes(bytes));
|
||||
future.onComplete((_) => client.close());
|
||||
}).then((bytes) => new String.fromCharCodes(bytes));
|
||||
future.catchError((_) {}).then((_) => client.close());
|
||||
|
||||
expect(future, completion(parse(equals({
|
||||
'method': 'POST',
|
||||
|
||||
@@ -16,17 +16,17 @@ main() {
|
||||
tearDown(stopServer);
|
||||
|
||||
test('head', () {
|
||||
expect(http.head(serverUrl).transform((response) {
|
||||
expect(http.head(serverUrl).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, equals(''));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('get', () {
|
||||
expect(http.get(serverUrl, headers: {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'GET',
|
||||
@@ -37,7 +37,7 @@ main() {
|
||||
'x-other-header': ['Other Value']
|
||||
},
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('post', () {
|
||||
@@ -47,7 +47,7 @@ main() {
|
||||
}, fields: {
|
||||
'some-field': 'value',
|
||||
'other-field': 'other value'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'POST',
|
||||
@@ -62,7 +62,7 @@ main() {
|
||||
},
|
||||
'body': 'some-field=value&other-field=other+value'
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('post without fields', () {
|
||||
@@ -70,7 +70,7 @@ main() {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value',
|
||||
'Content-Type': 'text/plain'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'POST',
|
||||
@@ -82,7 +82,7 @@ main() {
|
||||
'x-other-header': ['Other Value']
|
||||
}
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('put', () {
|
||||
@@ -92,7 +92,7 @@ main() {
|
||||
}, fields: {
|
||||
'some-field': 'value',
|
||||
'other-field': 'other value'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'PUT',
|
||||
@@ -107,7 +107,7 @@ main() {
|
||||
},
|
||||
'body': 'some-field=value&other-field=other+value'
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('put without fields', () {
|
||||
@@ -115,7 +115,7 @@ main() {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value',
|
||||
'Content-Type': 'text/plain'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'PUT',
|
||||
@@ -127,14 +127,14 @@ main() {
|
||||
'x-other-header': ['Other Value']
|
||||
}
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('delete', () {
|
||||
expect(http.delete(serverUrl, headers: {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value'
|
||||
}).transform((response) {
|
||||
}).then(expectAsync1((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
expect(response.body, parse(equals({
|
||||
'method': 'DELETE',
|
||||
@@ -145,14 +145,14 @@ main() {
|
||||
'x-other-header': ['Other Value']
|
||||
}
|
||||
})));
|
||||
}), completes);
|
||||
})), completes);
|
||||
});
|
||||
|
||||
test('read', () {
|
||||
expect(http.read(serverUrl, headers: {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value'
|
||||
}), completion(parse(equals({
|
||||
}).then(expectAsync1((val) => val)), completion(parse(equals({
|
||||
'method': 'GET',
|
||||
'path': '/',
|
||||
'headers': {
|
||||
@@ -162,16 +162,17 @@ main() {
|
||||
},
|
||||
}))));
|
||||
});
|
||||
|
||||
|
||||
test('read throws an error for a 4** status code', () {
|
||||
expect(http.read(serverUrl.resolve('/error')), throwsHttpException);
|
||||
expect(http.read(serverUrl.resolve('/error')).then((expectAsync1(x) => x)),
|
||||
throwsHttpException);
|
||||
});
|
||||
|
||||
|
||||
test('readBytes', () {
|
||||
var future = http.readBytes(serverUrl, headers: {
|
||||
'X-Random-Header': 'Value',
|
||||
'X-Other-Header': 'Other Value'
|
||||
}).transform((bytes) => new String.fromCharCodes(bytes));
|
||||
}).then(expectAsync1((bytes) => new String.fromCharCodes(bytes)));
|
||||
|
||||
expect(future, completion(parse(equals({
|
||||
'method': 'GET',
|
||||
@@ -185,7 +186,8 @@ main() {
|
||||
});
|
||||
|
||||
test('readBytes throws an error for a 4** status code', () {
|
||||
expect(http.readBytes(serverUrl.resolve('/error')), throwsHttpException);
|
||||
expect(http.readBytes(serverUrl.resolve('/error')).then((expectAsync1(x) => x)),
|
||||
throwsHttpException);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
library mock_client_test;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as json;
|
||||
import 'dart:uri';
|
||||
|
||||
import 'package:unittest/unittest.dart';
|
||||
@@ -18,14 +19,14 @@ void main() {
|
||||
test('handles a request', () {
|
||||
var client = new MockClient((request) {
|
||||
return new Future.immediate(new http.Response(
|
||||
JSON.stringify(request.bodyFields), 200,
|
||||
json.stringify(request.bodyFields), 200,
|
||||
request: request, headers: {'content-type': 'application/json'}));
|
||||
});
|
||||
|
||||
expect(client.post("http://example.com/foo", fields: {
|
||||
'field1': 'value1',
|
||||
'field2': 'value2'
|
||||
}).transform((response) => response.body), completion(parse(equals({
|
||||
}).then((response) => response.body), completion(parse(equals({
|
||||
'field1': 'value1',
|
||||
'field2': 'value2'
|
||||
}))));
|
||||
@@ -33,7 +34,7 @@ void main() {
|
||||
|
||||
test('handles a streamed request', () {
|
||||
var client = new MockClient.streaming((request, bodyStream) {
|
||||
return consumeInputStream(bodyStream).transform((body) {
|
||||
return consumeInputStream(bodyStream).then((body) {
|
||||
var stream = new ListInputStream();
|
||||
async.then((_) {
|
||||
var bodyString = new String.fromCharCodes(body);
|
||||
@@ -49,8 +50,8 @@ void main() {
|
||||
var request = new http.Request("POST", uri);
|
||||
request.body = "hello, world";
|
||||
var future = client.send(request)
|
||||
.chain(http.Response.fromStream)
|
||||
.transform((response) => response.body);
|
||||
.then(http.Response.fromStream)
|
||||
.then((response) => response.body);
|
||||
expect(future, completion(equals('Request body was "hello, world"')));
|
||||
});
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ class _BodyMatches extends BaseMatcher {
|
||||
bool matches(item, MatchState matchState) {
|
||||
if (item is! http.MultipartRequest) return false;
|
||||
|
||||
var future = consumeInputStream(item.finalize()).transform((bodyBytes) {
|
||||
var future = consumeInputStream(item.finalize()).then((bodyBytes) {
|
||||
var body = decodeUtf8(bodyBytes);
|
||||
var contentType = new ContentType.fromString(
|
||||
item.headers['content-type']);
|
||||
|
||||
@@ -17,11 +17,11 @@ void main() {
|
||||
|
||||
var request = new http.Request('POST', serverUrl);
|
||||
request.body = "hello";
|
||||
var future = request.send().chain((response) {
|
||||
var future = request.send().then((response) {
|
||||
expect(response.statusCode, equals(200));
|
||||
return consumeInputStream(response.stream);
|
||||
}).transform((bytes) => new String.fromCharCodes(bytes));
|
||||
future.onComplete(expectAsync1((_) {
|
||||
}).then((bytes) => new String.fromCharCodes(bytes));
|
||||
future.catchError((_) {}).then(expectAsync1((_) {
|
||||
stopServer();
|
||||
}));
|
||||
|
||||
@@ -192,11 +192,11 @@ void main() {
|
||||
|
||||
var request = new http.Request('POST', serverUrl.resolve('/redirect'))
|
||||
..followRedirects = false;
|
||||
var future = request.send().transform((response) {
|
||||
var future = request.send().then((response) {
|
||||
print("#followRedirects test response received");
|
||||
expect(response.statusCode, equals(302));
|
||||
});
|
||||
future.onComplete(expectAsync1((_) {
|
||||
future.catchError((_) {}).then(expectAsync1((_) {
|
||||
print("#followRedirects test stopping server...");
|
||||
stopServer();
|
||||
print("#followRedirects test server stopped");
|
||||
@@ -215,12 +215,12 @@ void main() {
|
||||
|
||||
var request = new http.Request('POST', serverUrl.resolve('/loop?1'))
|
||||
..maxRedirects = 2;
|
||||
var future = request.send().transformException((e) {
|
||||
var future = request.send().catchError((AsyncError e) {
|
||||
print("#maxRedirects test exception received");
|
||||
expect(e, isRedirectLimitExceededException);
|
||||
expect(e.redirects.length, equals(2));
|
||||
expect(e.error, isRedirectLimitExceededException);
|
||||
expect(e.error.redirects.length, equals(2));
|
||||
});
|
||||
future.onComplete(expectAsync1((_) {
|
||||
future.catchError((_) {}).then(expectAsync1((_) {
|
||||
print("#maxRedirects test stopping server...");
|
||||
stopServer();
|
||||
print("#maxRedirects test server stopped");
|
||||
@@ -318,7 +318,7 @@ void main() {
|
||||
request.body = "Hello, world!";
|
||||
expect(
|
||||
consumeInputStream(request.finalize())
|
||||
.transform((bytes) => new String.fromCharCodes(bytes)),
|
||||
.then((bytes) => new String.fromCharCodes(bytes)),
|
||||
completion(equals("Hello, world!")));
|
||||
});
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ void main() {
|
||||
var stream = new ListInputStream();
|
||||
var streamResponse = new http.StreamedResponse(stream, 200, 13);
|
||||
var future = http.Response.fromStream(streamResponse)
|
||||
.transform((response) => response.body);
|
||||
.then((response) => response.body);
|
||||
expect(future, completion(equals("Hello, world!")));
|
||||
|
||||
stream.write([72, 101, 108, 108, 111, 44, 32]);
|
||||
@@ -58,7 +58,7 @@ void main() {
|
||||
var stream = new ListInputStream();
|
||||
var streamResponse = new http.StreamedResponse(stream, 200, 5);
|
||||
var future = http.Response.fromStream(streamResponse)
|
||||
.transform((response) => response.bodyBytes);
|
||||
.then((response) => response.bodyBytes);
|
||||
expect(future, completion(equals([104, 101, 108, 108, 111])));
|
||||
|
||||
stream.write([104, 101, 108, 108, 111]);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
library test_utils;
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as json;
|
||||
import 'dart:uri';
|
||||
|
||||
import 'package:unittest/unittest.dart';
|
||||
@@ -88,7 +88,7 @@ void startServer() {
|
||||
outputEncoding = Encoding.ASCII;
|
||||
}
|
||||
|
||||
var body = JSON.stringify(content);
|
||||
var body = json.stringify(content);
|
||||
response.contentLength = body.length;
|
||||
response.outputStream.writeString(body, outputEncoding);
|
||||
response.outputStream.close();
|
||||
@@ -118,7 +118,7 @@ class _Parse extends BaseMatcher {
|
||||
|
||||
var parsed;
|
||||
try {
|
||||
parsed = JSON.parse(item);
|
||||
parsed = json.parse(item);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ library intl_basic_example;
|
||||
// These can be replaced with package:intl/... references if using this in
|
||||
// a separate package.
|
||||
// TODO(alanknight): Replace these with package: once pub works in buildbots.
|
||||
import 'dart:async';
|
||||
import '../../lib/date_symbol_data_local.dart';
|
||||
import '../../lib/intl.dart';
|
||||
import '../../lib/message_lookup_local.dart';
|
||||
@@ -57,8 +58,8 @@ runProgram(List<Future> _) {
|
||||
printForLocale(aDate, de, runAt);
|
||||
printForLocale(aDate, th, runAt);
|
||||
// Example making use of the return value from withLocale;
|
||||
var useReturnValue = Intl.withLocale(th.locale, () => runAt('now', 'today'));
|
||||
doThisWithTheOutput(useReturnValue);
|
||||
Intl.withLocale(th.locale, () => runAt('now', 'today'))
|
||||
.then(doThisWithTheOutput);
|
||||
}
|
||||
|
||||
printForLocale(aDate, intl, operation) {
|
||||
@@ -66,5 +67,7 @@ printForLocale(aDate, intl, operation) {
|
||||
var dayFormat = intl.date().add_yMMMMEEEEd();
|
||||
var time = hmsFormat.format(aDate);
|
||||
var day = dayFormat.format(aDate);
|
||||
Intl.withLocale(intl.locale, () { doThisWithTheOutput(operation(time,day));});
|
||||
}
|
||||
Intl.withLocale(intl.locale, () {
|
||||
operation(time,day).then(doThisWithTheOutput);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -186,7 +186,7 @@ class Bidi {
|
||||
static bool isRtlLanguage(String languageString) {
|
||||
return new RegExp(r'^(ar|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_]'
|
||||
r'(Arab|Hebr|Thaa|Nkoo|Tfng))(?!.*[-_](Latn|Cyrl)($|-|_))'
|
||||
r'($|-|_)', ignoreCase : true).hasMatch(languageString);
|
||||
r'($|-|_)', caseSensitive: false).hasMatch(languageString);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -401,4 +401,4 @@ class Bidi {
|
||||
static bool detectRtlDirectionality(String str, {bool isHtml: false}) {
|
||||
return estimateDirectionOfText(str, isHtml: isHtml) == TextDirection.RTL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +279,7 @@ class DateFormat {
|
||||
* Returns a list of all locales for which we have date formatting
|
||||
* information.
|
||||
*/
|
||||
static List<String> allLocalesWithSymbols() => dateTimeSymbols.keys;
|
||||
static List<String> allLocalesWithSymbols() => dateTimeSymbols.keys.toList();
|
||||
|
||||
/**
|
||||
* The named constructors for this class are all conveniences for creating
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
library date_symbol_data_json;
|
||||
|
||||
import 'dart:async';
|
||||
import "date_symbols.dart";
|
||||
import "src/lazy_locale_data.dart";
|
||||
import 'src/date_format_internal.dart';
|
||||
@@ -41,4 +42,4 @@ Future initializeDateFormatting(String locale, String path) {
|
||||
/** Defines how new date symbol entries are created. */
|
||||
DateSymbols _createDateSymbol(Map map) {
|
||||
return new DateSymbols.deserializeFromMap(map);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
*/
|
||||
|
||||
library date_symbol_data;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import "date_symbols.dart";
|
||||
import "src/date_format_internal.dart";
|
||||
import "date_time_patterns.dart";
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
*/
|
||||
library intl;
|
||||
|
||||
import 'dart:async';
|
||||
import 'src/intl_helpers.dart';
|
||||
import 'dart:math';
|
||||
import 'date_symbols.dart';
|
||||
@@ -127,7 +128,7 @@ class Intl {
|
||||
* will be extracted automatically but for the time being it must be passed
|
||||
* explicitly in the [name] and [args] arguments.
|
||||
*/
|
||||
static String message(String message_str, {final String desc: '',
|
||||
static Future<String> message(String message_str, {final String desc: '',
|
||||
final Map examples: const {}, String locale, String name,
|
||||
List<String> args}) {
|
||||
return messageLookup.lookupMessage(
|
||||
@@ -270,4 +271,4 @@ class Intl {
|
||||
if (_defaultLocale == null) _defaultLocale = systemLocale;
|
||||
return _defaultLocale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
library intl_standalone;
|
||||
|
||||
import "dart:async";
|
||||
import "dart:io";
|
||||
import "intl.dart";
|
||||
|
||||
@@ -113,4 +114,4 @@ Future<String> _checkResult(ProcessResult result, RegExp regex) {
|
||||
Future<String> _setLocale(aLocale) {
|
||||
Intl.systemLocale = Intl.canonicalizedLocale(aLocale);
|
||||
return new Future.immediate(Intl.systemLocale);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
library message_lookup_local;
|
||||
|
||||
import 'dart:async';
|
||||
import 'intl.dart';
|
||||
import 'src/intl_helpers.dart';
|
||||
import 'dart:mirrors';
|
||||
@@ -88,13 +89,13 @@ class MessageLookupLocal {
|
||||
* will be extracted automatically but for the time being it must be passed
|
||||
* explicitly in the [name] and [args] arguments.
|
||||
*/
|
||||
String lookupMessage(String message_str, [final String desc='',
|
||||
Future<String> lookupMessage(String message_str, [final String desc='',
|
||||
final Map examples=const {}, String locale,
|
||||
String name, List<String> args]) {
|
||||
if (name == null) return message_str;
|
||||
if (name == null) return new Future.immediate(message_str);
|
||||
// The translations also make use of Intl.message, so we need to not
|
||||
// recurse and just stop when we find the first substitution.
|
||||
if (_lookupInProgress) return message_str;
|
||||
if (_lookupInProgress) return new Future.immediate(message_str);
|
||||
_lookupInProgress = true;
|
||||
var result;
|
||||
try {
|
||||
@@ -108,14 +109,15 @@ class MessageLookupLocal {
|
||||
onFailure: (locale)=>locale);
|
||||
LibraryMirror messagesForThisLocale =
|
||||
_libraries['$_sourcePrefix$verifiedLocale'];
|
||||
if (messagesForThisLocale == null) return message_str;
|
||||
MethodMirror localized = messagesForThisLocale.functions[name];
|
||||
if (localized == null) return message_str;
|
||||
result = messagesForThisLocale.invoke(localized.simpleName, args);
|
||||
if (messagesForThisLocale == null) {
|
||||
return new Future.immediate(message_str);
|
||||
}
|
||||
finally {
|
||||
MethodMirror localized = messagesForThisLocale.functions[name];
|
||||
if (localized == null) return new Future.immediate(message_str);
|
||||
result = messagesForThisLocale.invoke(localized.simpleName, args);
|
||||
} finally {
|
||||
_lookupInProgress = false;
|
||||
}
|
||||
return result.value.reflectee;
|
||||
return result.then((value) => value.reflectee);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*/
|
||||
|
||||
library date_format_internal;
|
||||
import 'dart:async';
|
||||
import 'intl_helpers.dart';
|
||||
import '../date_symbols.dart';
|
||||
|
||||
@@ -64,4 +65,4 @@ void initializeDatePatterns(Function patterns) {
|
||||
|
||||
Future initializeIndividualLocaleDateFormatting(Function init) {
|
||||
return init(dateTimeSymbols, dateTimePatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
library file_data_reader;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'intl_helpers.dart';
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
library intl_helpers;
|
||||
import '../date_symbols.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
/**
|
||||
* This is used as a marker for a locale data map that hasn't been initialized,
|
||||
* and will throw an exception on any usage that isn't the fallback
|
||||
@@ -61,4 +63,4 @@ void initializeInternalMessageLookup(Function lookupFunction) {
|
||||
if (messageLookup is UninitializedLocaleData) {
|
||||
messageLookup = lookupFunction();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
*/
|
||||
|
||||
library lazy_locale_data;
|
||||
import 'dart:async';
|
||||
import 'dart:uri';
|
||||
import 'intl_helpers.dart';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as json;
|
||||
|
||||
/**
|
||||
* This implements the very basic map-type operations which are used
|
||||
@@ -99,7 +100,7 @@ class LazyLocaleData {
|
||||
*/
|
||||
Future initLocale(String localeName) {
|
||||
var data = _reader.read(localeName);
|
||||
return jsonData(data).transform( (input) {
|
||||
return jsonData(data).then( (input) {
|
||||
map[localeName] = _creationFunction(input);});
|
||||
}
|
||||
|
||||
@@ -108,6 +109,6 @@ class LazyLocaleData {
|
||||
* return another future that parses the JSON into a usable format.
|
||||
*/
|
||||
Future jsonData(Future input) {
|
||||
return input.transform( (response) => JSON.parse(response));
|
||||
return input.then( (response) => json.parse(response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
library date_time_format_file_test;
|
||||
|
||||
import 'dart:async';
|
||||
import '../lib/intl.dart';
|
||||
import '../lib/date_symbol_data_file.dart';
|
||||
import 'dart:io';
|
||||
|
||||
@@ -25,8 +25,9 @@ main() {
|
||||
|
||||
void runEverything(_) {
|
||||
// Initialize all locales and wait for them to finish before running tests.
|
||||
var futures = DateFormat.allLocalesWithSymbols().map(
|
||||
(locale) => initializeDateFormatting(locale, url));
|
||||
var futures = DateFormat.allLocalesWithSymbols()
|
||||
.mappedBy((locale) => initializeDateFormatting(locale, url))
|
||||
.toList();
|
||||
Futures.wait(futures).then(expectAsync1((_) {
|
||||
runDateTests(smallSetOfLocales());
|
||||
shutDown();}));
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
library date_time_format_test;
|
||||
|
||||
import 'dart:async';
|
||||
import '../lib/intl.dart';
|
||||
import '../lib/date_time_patterns.dart';
|
||||
import '../lib/date_symbol_data_local.dart';
|
||||
@@ -24,7 +25,8 @@ runWith([Function getSubset]) {
|
||||
|
||||
void runEverything(Function getSubset) {
|
||||
// Initialize all locales and wait for them to finish before running tests.
|
||||
var futures = DateFormat.allLocalesWithSymbols().map(
|
||||
(locale) => initializeDateFormatting(locale, null));
|
||||
var futures = DateFormat.allLocalesWithSymbols()
|
||||
.mappedBy((locale) => initializeDateFormatting(locale, null))
|
||||
.toList();
|
||||
Futures.wait(futures).then((results) => runDateTests(getSubset()));
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ testRoundTripParsing(String localeName, Date date) {
|
||||
DateFormat.ABBR_MONTH_WEEKDAY_DAY];
|
||||
for(int i = 0; i < formatsToTest.length; i++) {
|
||||
var skeleton = formatsToTest[i];
|
||||
if (!badSkeletons.some((x) => x == skeleton)) {
|
||||
if (!badSkeletons.any((x) => x == skeleton)) {
|
||||
var format = new DateFormat(skeleton, localeName);
|
||||
var actualResult = format.format(date);
|
||||
var parsed = format.parse(actualResult);
|
||||
@@ -177,7 +177,7 @@ List<String> allLocales() => DateFormat.allLocalesWithSymbols();
|
||||
*/
|
||||
List oddLocales() {
|
||||
int i = 1;
|
||||
return allLocales().filter((x) => (i++).isOdd);
|
||||
return allLocales().where((x) => (i++).isOdd).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -193,7 +193,7 @@ List smallSetOfLocales() {
|
||||
*/
|
||||
List evenLocales() {
|
||||
int i = 1;
|
||||
return allLocales().filter((x) => !((i++).isOdd));
|
||||
return allLocales().where((x) => !((i++).isOdd)).toList();
|
||||
}
|
||||
|
||||
// TODO(alanknight): Run specific tests for the en_ISO locale which isn't
|
||||
@@ -217,10 +217,14 @@ runDateTests([List<String> subset]) {
|
||||
test('Basic date format parsing', () {
|
||||
var date_format = new DateFormat("d");
|
||||
expect(
|
||||
date_format.parsePattern("hh:mm:ss").map((x) => x.pattern),
|
||||
date_format.parsePattern("hh:mm:ss")
|
||||
.mappedBy((x) => x.pattern)
|
||||
.toList(),
|
||||
orderedEquals(["hh",":", "mm",":","ss"]));
|
||||
expect(
|
||||
date_format.parsePattern("hh:mm:ss").map((x) => x.pattern),
|
||||
date_format.parsePattern("hh:mm:ss")
|
||||
.mappedBy((x) => x.pattern)
|
||||
.toList(),
|
||||
orderedEquals(["hh",":", "mm",":","ss"]));
|
||||
});
|
||||
|
||||
|
||||
@@ -25,13 +25,13 @@ runTests(_) {
|
||||
test('Trivial Message', () {
|
||||
hello() => Intl.message('Hello, world!',
|
||||
desc: 'hello world string');
|
||||
expect(hello(), equals('Hello, world!'));
|
||||
expect(hello(), completion(equals('Hello, world!')));
|
||||
});
|
||||
|
||||
test('Message with one parameter', () {
|
||||
lucky(number) => Intl.message('Your lucky number is $number',
|
||||
desc: 'number str', examples: {'number': 2});
|
||||
expect(lucky(3), equals('Your lucky number is 3'));
|
||||
expect(lucky(3), completion(equals('Your lucky number is 3')));
|
||||
});
|
||||
|
||||
test('Message with multiple plural cases (whole message)', () {
|
||||
@@ -42,9 +42,9 @@ runTests(_) {
|
||||
'other': 'There are $number emails left.'}),
|
||||
desc: 'Message telling user how many emails will be sent.',
|
||||
examples: {'number': 32});
|
||||
expect(emails(5), equals('There are 5 emails left.'));
|
||||
expect(emails(0), equals('There are no emails left.'));
|
||||
expect(emails(1), equals('There is one email left.'));
|
||||
expect(emails(5), completion(equals('There are 5 emails left.')));
|
||||
expect(emails(0), completion(equals('There are no emails left.')));
|
||||
expect(emails(1), completion(equals('There is one email left.')));
|
||||
});
|
||||
|
||||
test('Message with multiple plural cases (partial message)', () {
|
||||
@@ -55,9 +55,9 @@ runTests(_) {
|
||||
'other': 'are'})} $number messages left.",
|
||||
desc: 'Message telling user how many emails will be sent.',
|
||||
examples: {'number': 32});
|
||||
expect(emails(5), equals('There are 5 messages left.'));
|
||||
expect(emails(0), equals('There are 0 messages left.'));
|
||||
expect(emails(1), equals('There is 1 messages left.'));
|
||||
expect(emails(5), completion(equals('There are 5 messages left.')));
|
||||
expect(emails(0), completion(equals('There are 0 messages left.')));
|
||||
expect(emails(1), completion(equals('There is 1 messages left.')));
|
||||
});
|
||||
|
||||
test('Message with dictionary parameter', () {
|
||||
@@ -66,7 +66,7 @@ runTests(_) {
|
||||
desc: "States a person's name.",
|
||||
examples: {'first': 'Ford', 'last': 'Prefect'});
|
||||
expect(hello({'first' : 'Ford', 'last' : 'Prefect'}),
|
||||
equals('Hello, my name is Ford Prefect'));
|
||||
completion(equals('Hello, my name is Ford Prefect')));
|
||||
});
|
||||
|
||||
test('Message with object parameter', () {
|
||||
@@ -75,18 +75,19 @@ runTests(_) {
|
||||
desc: "States a person's name.",
|
||||
examples: {'first': 'Ford', 'last' : 'Prefect'});
|
||||
var ford = new Person('Ford', 'Prefect');
|
||||
expect(hello(ford), equals('Hello, my name is Ford Prefect.'));
|
||||
expect(hello(ford), completion(equals('Hello, my name is Ford Prefect.')));
|
||||
});
|
||||
|
||||
test('WithLocale test', () {
|
||||
hello() => Intl.message('locale=${Intl.getCurrentLocale()}',
|
||||
desc: 'explains the locale');
|
||||
expect(Intl.withLocale('en-US', () => hello()), equals('locale=en-US'));
|
||||
expect(Intl.withLocale('en-US', () => hello()),
|
||||
completion(equals('locale=en-US')));
|
||||
});
|
||||
|
||||
test('Test passing locale', () {
|
||||
hello(a_locale) => Intl.message('locale=${Intl.getCurrentLocale()}',
|
||||
desc: 'explains the locale', locale: a_locale);
|
||||
expect(hello('en-US'), equals('locale=en_US'));
|
||||
expect(hello('en-US'), completion(equals('locale=en_US')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import '../lib/date_symbol_data_local.dart';
|
||||
import '../lib/date_time_patterns.dart';
|
||||
import '../lib/intl.dart';
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as json;
|
||||
import '../test/data_directory.dart';
|
||||
|
||||
main() {
|
||||
@@ -68,10 +68,10 @@ void writeSymbols(locale, symbols) {
|
||||
void writePatterns(locale, patterns) {
|
||||
var file = new File('${dataDirectory}patterns/${locale}.json');
|
||||
var outputStream = file.openOutputStream();
|
||||
outputStream.writeString(JSON.stringify(patterns));
|
||||
outputStream.writeString(json.stringify(patterns));
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
void writeToJSON(dynamic data, OutputStream out) {
|
||||
out.writeString(JSON.stringify(data.serializeToMap()));
|
||||
}
|
||||
out.writeString(json.stringify(data.serializeToMap()));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library authorization_code_grant;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:uri';
|
||||
|
||||
// TODO(nweiz): This should be a "package:" import. See issue 6745.
|
||||
@@ -159,7 +160,7 @@ class AuthorizationCodeGrant {
|
||||
///
|
||||
/// Throws [AuthorizationException] if the authorization fails.
|
||||
Future<Client> handleAuthorizationResponse(Map<String, String> parameters) {
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (_state == _INITIAL_STATE) {
|
||||
throw new StateError(
|
||||
'The authorization URL has not yet been generated.');
|
||||
@@ -211,7 +212,7 @@ class AuthorizationCodeGrant {
|
||||
///
|
||||
/// Throws [AuthorizationException] if the authorization fails.
|
||||
Future<Client> handleAuthorizationCode(String authorizationCode) {
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (_state == _INITIAL_STATE) {
|
||||
throw new StateError(
|
||||
'The authorization URL has not yet been generated.');
|
||||
@@ -238,7 +239,7 @@ class AuthorizationCodeGrant {
|
||||
// it be configurable?
|
||||
"client_id": this.identifier,
|
||||
"client_secret": this.secret
|
||||
}).transform((response) {
|
||||
}).then((response) {
|
||||
var credentials = handleAccessTokenResponse(
|
||||
response, tokenEndpoint, startTime, _scopes);
|
||||
return new Client(
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library client;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:uri';
|
||||
|
||||
import '../../../http/lib/http.dart' as http;
|
||||
@@ -81,14 +82,14 @@ class Client extends http.BaseClient {
|
||||
/// will also automatically refresh this client's [Credentials] before sending
|
||||
/// the request if necessary.
|
||||
Future<http.StreamedResponse> send(http.BaseRequest request) {
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (!credentials.isExpired) return new Future.immediate(null);
|
||||
if (!credentials.canRefresh) throw new ExpirationException(credentials);
|
||||
return refreshCredentials();
|
||||
}).chain((_) {
|
||||
}).then((_) {
|
||||
request.headers['authorization'] = "Bearer ${credentials.accessToken}";
|
||||
return _httpClient.send(request);
|
||||
}).transform((response) {
|
||||
}).then((response) {
|
||||
if (response.statusCode != 401 ||
|
||||
!response.headers.containsKey('www-authenticate')) {
|
||||
return response;
|
||||
@@ -122,7 +123,7 @@ class Client extends http.BaseClient {
|
||||
/// [newScopes]. These must be a subset of the scopes in the
|
||||
/// [Credentials.scopes] field of [Client.credentials].
|
||||
Future<Client> refreshCredentials([List<String> newScopes]) {
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (!credentials.canRefresh) {
|
||||
var prefix = "OAuth credentials";
|
||||
if (credentials.isExpired) prefix = "$prefix have expired and";
|
||||
@@ -131,7 +132,7 @@ class Client extends http.BaseClient {
|
||||
|
||||
return credentials.refresh(identifier, secret,
|
||||
newScopes: newScopes, httpClient: _httpClient);
|
||||
}).transform((credentials) {
|
||||
}).then((credentials) {
|
||||
_credentials = credentials;
|
||||
return this;
|
||||
});
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
library credentials;
|
||||
|
||||
import 'dart:json';
|
||||
import 'dart:async';
|
||||
import 'dart:json' as JSON;
|
||||
import 'dart:uri';
|
||||
|
||||
import '../../../http/lib/http.dart' as http;
|
||||
@@ -152,7 +153,7 @@ class Credentials {
|
||||
if (httpClient == null) httpClient = new http.Client();
|
||||
|
||||
var startTime = new Date.now();
|
||||
return async.chain((_) {
|
||||
return async.then((_) {
|
||||
if (refreshToken == null) {
|
||||
throw new StateError("Can't refresh credentials without a refresh "
|
||||
"token.");
|
||||
@@ -173,10 +174,10 @@ class Credentials {
|
||||
if (!scopes.isEmpty) fields["scope"] = Strings.join(scopes, ' ');
|
||||
|
||||
return httpClient.post(tokenEndpoint, fields: fields);
|
||||
}).transform((response) {
|
||||
}).then((response) {
|
||||
return handleAccessTokenResponse(
|
||||
response, tokenEndpoint, startTime, scopes);
|
||||
}).transform((credentials) {
|
||||
}).then((credentials) {
|
||||
// The authorization server may issue a new refresh token. If it doesn't,
|
||||
// we should re-use the one we already have.
|
||||
if (credentials.refreshToken != null) return credentials;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
library handle_access_token_response;
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as JSON;
|
||||
import 'dart:uri';
|
||||
|
||||
import '../../../http/lib/http.dart' as http;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
library utils;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:uri';
|
||||
import 'dart:isolate';
|
||||
import 'dart:crypto';
|
||||
@@ -38,7 +39,7 @@ String mapToQuery(Map<String, String> map) {
|
||||
value = (value == null || value.isEmpty) ? null : encodeUriComponent(value);
|
||||
pairs.add([key, value]);
|
||||
});
|
||||
return Strings.join(pairs.map((pair) {
|
||||
return Strings.join(pairs.mappedBy((pair) {
|
||||
if (pair[1] == null) return pair[0];
|
||||
return "${pair[0]}=${pair[1]}";
|
||||
}), "&");
|
||||
@@ -112,8 +113,4 @@ class AuthenticateHeader {
|
||||
}
|
||||
|
||||
/// Returns a [Future] that asynchronously completes to `null`.
|
||||
Future get async {
|
||||
var completer = new Completer();
|
||||
new Timer(0, (_) => completer.complete(null));
|
||||
return completer.future;
|
||||
}
|
||||
Future get async => new Future.delayed(0, () => null);
|
||||
|
||||
@@ -30,6 +30,12 @@ void createGrant() {
|
||||
httpClient: client);
|
||||
}
|
||||
|
||||
void expectFutureThrows(future, predicate) {
|
||||
future.catchError(expectAsync1((AsyncError e) {
|
||||
expect(predicate(e.error), isTrue);
|
||||
}));
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('.getAuthorizationUrl', () {
|
||||
setUp(createGrant);
|
||||
@@ -83,7 +89,8 @@ void main() {
|
||||
|
||||
test("can't be called twice", () {
|
||||
grant.getAuthorizationUrl(redirectUrl);
|
||||
expect(() => grant.getAuthorizationUrl(redirectUrl), throwsStateError);
|
||||
expectFutureThrows(grant.getAuthorizationUrl(redirectUrl),
|
||||
(e) => e is StateError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -91,39 +98,44 @@ void main() {
|
||||
setUp(createGrant);
|
||||
|
||||
test("can't be called before .getAuthorizationUrl", () {
|
||||
expect(grant.handleAuthorizationResponse({}), throwsStateError);
|
||||
expectFutureThrows(grant.handleAuthorizationResponse({}),
|
||||
(e) => e is StateError);
|
||||
});
|
||||
|
||||
test("can't be called twice", () {
|
||||
grant.getAuthorizationUrl(redirectUrl);
|
||||
grant.handleAuthorizationResponse({'code': 'auth code'});
|
||||
expect(grant.handleAuthorizationResponse({'code': 'auth code'}),
|
||||
throwsStateError);
|
||||
expectFutureThrows(
|
||||
grant.handleAuthorizationResponse({'code': 'auth code'}),
|
||||
(e) => e is StateError);
|
||||
});
|
||||
|
||||
test('must have a state parameter if the authorization URL did', () {
|
||||
grant.getAuthorizationUrl(redirectUrl, state: 'state');
|
||||
expect(grant.handleAuthorizationResponse({'code': 'auth code'}),
|
||||
throwsFormatException);
|
||||
expectFutureThrows(
|
||||
grant.handleAuthorizationResponse({'code': 'auth code'}),
|
||||
(e) => e is FormatException);
|
||||
});
|
||||
|
||||
test('must have the same state parameter the authorization URL did', () {
|
||||
grant.getAuthorizationUrl(redirectUrl, state: 'state');
|
||||
expect(grant.handleAuthorizationResponse({
|
||||
expectFutureThrows(grant.handleAuthorizationResponse({
|
||||
'code': 'auth code',
|
||||
'state': 'other state'
|
||||
}), throwsFormatException);
|
||||
}), (e) => e is FormatException);
|
||||
});
|
||||
|
||||
test('must have a code parameter', () {
|
||||
grant.getAuthorizationUrl(redirectUrl);
|
||||
expect(grant.handleAuthorizationResponse({}), throwsFormatException);
|
||||
expectFutureThrows(grant.handleAuthorizationResponse({}),
|
||||
(e) => e is FormatException);
|
||||
});
|
||||
|
||||
test('with an error parameter throws an AuthorizationException', () {
|
||||
grant.getAuthorizationUrl(redirectUrl);
|
||||
expect(grant.handleAuthorizationResponse({'error': 'invalid_request'}),
|
||||
throwsAuthorizationException);
|
||||
expectFutureThrows(
|
||||
grant.handleAuthorizationResponse({'error': 'invalid_request'}),
|
||||
(e) => e is AuthorizationException);
|
||||
});
|
||||
|
||||
test('sends an authorization code request', () {
|
||||
@@ -163,8 +175,8 @@ void main() {
|
||||
test("can't be called twice", () {
|
||||
grant.getAuthorizationUrl(redirectUrl);
|
||||
grant.handleAuthorizationCode('auth code');
|
||||
expect(grant.handleAuthorizationCode('auth code'),
|
||||
throwsStateError);
|
||||
expectFutureThrows(grant.handleAuthorizationCode('auth code'),
|
||||
(e) => e is StateError);
|
||||
});
|
||||
|
||||
test('sends an authorization code request', () {
|
||||
|
||||
@@ -63,7 +63,7 @@ void main() {
|
||||
return new Future.immediate(new http.Response('good job', 200));
|
||||
});
|
||||
|
||||
expect(client.read(requestUri).transform((_) {
|
||||
expect(client.read(requestUri).then((_) {
|
||||
expect(client.credentials.accessToken, equals('new access token'));
|
||||
}), completes);
|
||||
});
|
||||
@@ -104,7 +104,7 @@ void main() {
|
||||
}), 200, headers: {'content-type': 'application/json'}));
|
||||
});
|
||||
|
||||
expect(client.refreshCredentials().transform((_) {
|
||||
expect(client.refreshCredentials().then((_) {
|
||||
expect(client.credentials.accessToken, equals('new access token'));
|
||||
}), completes);
|
||||
});
|
||||
@@ -156,7 +156,7 @@ void main() {
|
||||
});
|
||||
|
||||
expect(
|
||||
client.get(requestUri).transform((response) => response.statusCode),
|
||||
client.get(requestUri).then((response) => response.statusCode),
|
||||
completion(equals(401)));
|
||||
});
|
||||
|
||||
@@ -178,7 +178,7 @@ void main() {
|
||||
});
|
||||
|
||||
expect(
|
||||
client.get(requestUri).transform((response) => response.statusCode),
|
||||
client.get(requestUri).then((response) => response.statusCode),
|
||||
completion(equals(401)));
|
||||
});
|
||||
|
||||
@@ -198,7 +198,7 @@ void main() {
|
||||
});
|
||||
|
||||
expect(
|
||||
client.get(requestUri).transform((response) => response.statusCode),
|
||||
client.get(requestUri).then((response) => response.statusCode),
|
||||
completion(equals(401)));
|
||||
});
|
||||
|
||||
@@ -218,7 +218,7 @@ void main() {
|
||||
});
|
||||
|
||||
expect(
|
||||
client.get(requestUri).transform((response) => response.statusCode),
|
||||
client.get(requestUri).then((response) => response.statusCode),
|
||||
completion(equals(401)));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
library credentials_test;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as JSON;
|
||||
import 'dart:uri';
|
||||
|
||||
import '../../unittest/lib/unittest.dart';
|
||||
@@ -43,15 +44,19 @@ void main() {
|
||||
var credentials = new oauth2.Credentials(
|
||||
'access token', null, tokenEndpoint);
|
||||
expect(credentials.canRefresh, false);
|
||||
expect(credentials.refresh('identifier', 'secret', httpClient: httpClient),
|
||||
throwsStateError);
|
||||
credentials.refresh('identifier', 'secret', httpClient: httpClient)
|
||||
.catchError(expectAsync1((e) {
|
||||
expect(e.error is StateError, isTrue);
|
||||
}));
|
||||
});
|
||||
|
||||
test("can't refresh without a token endpoint", () {
|
||||
var credentials = new oauth2.Credentials('access token', 'refresh token');
|
||||
expect(credentials.canRefresh, false);
|
||||
expect(credentials.refresh('identifier', 'secret', httpClient: httpClient),
|
||||
throwsStateError);
|
||||
credentials.refresh('identifier', 'secret', httpClient: httpClient)
|
||||
.catchError(expectAsync1((e) {
|
||||
expect(e.error is StateError, isTrue);
|
||||
}));
|
||||
});
|
||||
|
||||
test("can refresh with a refresh token and a token endpoint", () {
|
||||
@@ -79,7 +84,7 @@ void main() {
|
||||
|
||||
|
||||
expect(credentials.refresh('identifier', 'secret', httpClient: httpClient)
|
||||
.transform((credentials) {
|
||||
.then((credentials) {
|
||||
expect(credentials.accessToken, equals('new access token'));
|
||||
expect(credentials.refreshToken, equals('new refresh token'));
|
||||
}), completes);
|
||||
@@ -108,7 +113,7 @@ void main() {
|
||||
|
||||
|
||||
expect(credentials.refresh('identifier', 'secret', httpClient: httpClient)
|
||||
.transform((credentials) {
|
||||
.then((credentials) {
|
||||
expect(credentials.accessToken, equals('new access token'));
|
||||
expect(credentials.refreshToken, equals('refresh token'));
|
||||
}), completes);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
library handle_access_token_response_test;
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:json';
|
||||
import 'dart:json' as JSON;
|
||||
import 'dart:uri';
|
||||
|
||||
import '../../unittest/lib/unittest.dart';
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
library utils;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import '../../unittest/lib/unittest.dart';
|
||||
import '../../http/lib/http.dart' as http;
|
||||
import '../../http/lib/testing.dart';
|
||||
|
||||
@@ -356,7 +356,7 @@ class Builder {
|
||||
List<String> split(String path) {
|
||||
var parsed = _parse(path);
|
||||
// Filter out empty parts that exist due to multiple separators in a row.
|
||||
parsed.parts = parsed.parts.filter((part) => part != '');
|
||||
parsed.parts = parsed.parts.where((part) => !part.isEmpty).toList();
|
||||
if (parsed.root != null) parsed.parts.insertRange(0, 1, parsed.root);
|
||||
return parsed.parts;
|
||||
}
|
||||
|
||||
@@ -149,7 +149,8 @@ library serialization;
|
||||
|
||||
import 'src/mirrors_helpers.dart';
|
||||
import 'src/serialization_helpers.dart';
|
||||
import 'dart:json' show JSON;
|
||||
import 'dart:async';
|
||||
import 'dart:json' as json;
|
||||
|
||||
part 'src/reader_writer.dart';
|
||||
part 'src/serialization_rule.dart';
|
||||
@@ -201,7 +202,7 @@ class Serialization {
|
||||
*/
|
||||
bool get selfDescribing {
|
||||
if (_selfDescribing != null) return _selfDescribing;
|
||||
return !_rules.some((x) => x is CustomRule);
|
||||
return !_rules.any((x) => x is CustomRule);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -362,8 +363,8 @@ class Serialization {
|
||||
target = object;
|
||||
candidateRules = _rules;
|
||||
}
|
||||
List applicable = candidateRules.filter(
|
||||
(each) => each.appliesTo(target, w));
|
||||
List applicable =
|
||||
candidateRules.where((each) => each.appliesTo(target, w)).toList();
|
||||
|
||||
if (applicable.isEmpty) {
|
||||
return [addRuleFor(target)];
|
||||
@@ -371,8 +372,8 @@ class Serialization {
|
||||
|
||||
if (applicable.length == 1) return applicable;
|
||||
var first = applicable[0];
|
||||
var finalRules = applicable.filter(
|
||||
(x) => !x.mustBePrimary || (x == first));
|
||||
var finalRules = applicable.where(
|
||||
(x) => !x.mustBePrimary || (x == first)).toList();
|
||||
|
||||
if (finalRules.isEmpty) throw new SerializationException(
|
||||
'No valid rule found for object $object');
|
||||
@@ -436,4 +437,4 @@ class Serialization {
|
||||
class SerializationException implements Exception {
|
||||
final String message;
|
||||
const SerializationException([this.message]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,14 +239,17 @@ class BasicRule extends SerializationRule {
|
||||
* Or, in the special case of null, two nulls.
|
||||
*/
|
||||
pullStateFrom(Iterator stream) {
|
||||
var dataLength = stream.next();
|
||||
stream.moveNext();
|
||||
var dataLength = stream.current;
|
||||
var ruleData = new List();
|
||||
for (var i = 0; i < dataLength; i++) {
|
||||
var subList = new List();
|
||||
ruleData.add(subList);
|
||||
for (var j = 0; j < fields.length; j++) {
|
||||
var a = stream.next();
|
||||
var b = stream.next();
|
||||
stream.moveNext();
|
||||
var a = stream.current;
|
||||
stream.moveNext();
|
||||
var b = stream.current;
|
||||
if (!(a is int)) {
|
||||
// This wasn't a reference, so just use the first object as a literal.
|
||||
// particularly used for the case of null.
|
||||
@@ -360,7 +363,10 @@ class _NamedField extends _Field {
|
||||
setter(object, value);
|
||||
}
|
||||
|
||||
valueIn(InstanceMirror mirror) => mirror.getField(name).value.reflectee;
|
||||
valueIn(InstanceMirror mirror) {
|
||||
var futureValue = deprecatedFutureValue(mirror.getField(name));
|
||||
return futureValue.reflectee;
|
||||
}
|
||||
|
||||
/** Return the function to use to set our value. */
|
||||
Function get setter =>
|
||||
@@ -404,7 +410,7 @@ class _ConstantField extends _Field {
|
||||
* are kept in a separate object, which also has the ability to compute the
|
||||
* default fields to use reflectively.
|
||||
*/
|
||||
class _FieldList implements Iterable {
|
||||
class _FieldList extends Iterable {
|
||||
/**
|
||||
* All of our fields, indexed by name. Note that the names are not
|
||||
* necessarily strings.
|
||||
@@ -472,12 +478,12 @@ class _FieldList implements Iterable {
|
||||
void addAllNotExplicitlyExcluded(List<String> aCollection) {
|
||||
if (aCollection == null) return;
|
||||
var names = aCollection;
|
||||
names = names.filter((x) => !_excludeFields.contains(x));
|
||||
names = names.where((x) => !_excludeFields.contains(x));
|
||||
addAllByName(names);
|
||||
}
|
||||
|
||||
/** Add all the fields with the given names without any special properties. */
|
||||
void addAllByName(List<String> names) {
|
||||
void addAllByName(Iterable<String> names) {
|
||||
for (var each in names) {
|
||||
allFields.putIfAbsent(each, () => new _Field(each, this));
|
||||
}
|
||||
@@ -493,7 +499,7 @@ class _FieldList implements Iterable {
|
||||
contents;
|
||||
}
|
||||
|
||||
Iterator iterator() => contents.iterator();
|
||||
Iterator get iterator => contents.iterator;
|
||||
|
||||
/** Return a cached, sorted list of all the fields. */
|
||||
List<_Field> get contents {
|
||||
@@ -524,11 +530,16 @@ class _FieldList implements Iterable {
|
||||
}
|
||||
|
||||
List get constructorFields => _constructorFields;
|
||||
List constructorFieldNames() => constructorFields.map((x) => x.name);
|
||||
List constructorFieldIndices() => constructorFields.map((x) => x.index);
|
||||
List regularFields() => contents.filter((x) => !x.usedInConstructor);
|
||||
List regularFieldNames() => regularFields().map((x) => x.name);
|
||||
List regularFieldIndices() => regularFields().map((x) => x.index);
|
||||
List constructorFieldNames() =>
|
||||
constructorFields.mappedBy((x) => x.name).toList();
|
||||
List constructorFieldIndices() =>
|
||||
constructorFields.mappedBy((x) => x.index).toList();
|
||||
List regularFields() =>
|
||||
contents.where((x) => !x.usedInConstructor).toList();
|
||||
List regularFieldNames() =>
|
||||
regularFields().mappedBy((x) => x.name).toList();
|
||||
List regularFieldIndices() =>
|
||||
regularFields().mappedBy((x) => x.index).toList();
|
||||
|
||||
|
||||
/**
|
||||
@@ -539,16 +550,16 @@ class _FieldList implements Iterable {
|
||||
*/
|
||||
void figureOutFields() {
|
||||
List names(Collection<DeclarationMirror> mirrors) =>
|
||||
mirrors.map((each) => each.simpleName);
|
||||
mirrors.mappedBy((each) => each.simpleName).toList();
|
||||
|
||||
if (!_shouldFigureOutFields || !regularFields().isEmpty) return;
|
||||
var fields = publicFields(mirror);
|
||||
var getters = publicGetters(mirror);
|
||||
var gettersWithSetters = getters.filter( (each)
|
||||
=> mirror.setters["${each.simpleName}="] != null);
|
||||
var gettersThatMatchConstructor = getters.filter((each)
|
||||
var gettersWithSetters = getters.where( (each)
|
||||
=> mirror.setters["${each.simpleName}="] != null).toList();
|
||||
var gettersThatMatchConstructor = getters.where((each)
|
||||
=> (named(each.simpleName) != null) &&
|
||||
(named(each.simpleName).usedInConstructor));
|
||||
(named(each.simpleName).usedInConstructor)).toList();
|
||||
addAllNotExplicitlyExcluded(names(fields));
|
||||
addAllNotExplicitlyExcluded(names(gettersWithSetters));
|
||||
addAllNotExplicitlyExcluded(names(gettersThatMatchConstructor));
|
||||
@@ -594,10 +605,11 @@ class Constructor {
|
||||
*/
|
||||
constructFrom(state, Reader r) {
|
||||
// TODO(alanknight): Handle named parameters
|
||||
Collection inflated = fieldNumbers.map(
|
||||
(x) => (x is int) ? reflect(r.inflateReference(state[x])) : reflect(x));
|
||||
Collection inflated = fieldNumbers.mappedBy(
|
||||
(x) => (x is int) ? reflect(r.inflateReference(state[x])) : reflect(x))
|
||||
.toList();
|
||||
var result = type.newInstance(name, inflated);
|
||||
return result.value;
|
||||
return deprecatedFutureValue(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -616,4 +628,4 @@ class _MapWrapper {
|
||||
get length => _map.length;
|
||||
|
||||
asMap() => _map;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import 'serialization_helpers.dart';
|
||||
* fields.
|
||||
*/
|
||||
List<VariableMirror> publicFields(ClassMirror mirror) {
|
||||
var mine = mirror.variables.values.filter(
|
||||
var mine = mirror.variables.values.where(
|
||||
(x) => !(x.isPrivate || x.isStatic));
|
||||
var mySuperclass = mirror.superclass;
|
||||
if (mySuperclass != mirror) {
|
||||
@@ -42,13 +42,13 @@ bool hasField(String name, ClassMirror mirror) {
|
||||
* Return a list of all the getters of a class, including inherited
|
||||
* getters. Note that this allows private getters, but excludes statics.
|
||||
*/
|
||||
List<MethodMirror> publicGetters(ClassMirror mirror) {
|
||||
var mine = mirror.getters.values.filter((x) => !(x.isPrivate || x.isStatic));
|
||||
Iterable<MethodMirror> publicGetters(ClassMirror mirror) {
|
||||
var mine = mirror.getters.values.where((x) => !(x.isPrivate || x.isStatic));
|
||||
var mySuperclass = mirror.superclass;
|
||||
if (mySuperclass != mirror) {
|
||||
return append(publicGetters(mirror.superclass), mine);
|
||||
} else {
|
||||
return mine;
|
||||
return mine.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,8 +67,8 @@ bool hasGetter(String name, ClassMirror mirror) {
|
||||
*/
|
||||
List<MethodMirror> publicGettersWithMatchingSetters(ClassMirror mirror) {
|
||||
var setters = mirror.setters;
|
||||
return publicGetters(mirror).filter((each) =>
|
||||
setters["${each.simpleName}="] != null);
|
||||
return publicGetters(mirror).where((each) =>
|
||||
setters["${each.simpleName}="] != null).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,4 +76,4 @@ List<MethodMirror> publicGettersWithMatchingSetters(ClassMirror mirror) {
|
||||
* as literals, so we have to be passed an instance and then extract a
|
||||
* ClassMirror from that. Given a horrible name as an extra reminder to fix it.
|
||||
*/
|
||||
ClassMirror turnInstanceIntoSomethingWeCanUse(x) => reflect(x).type;
|
||||
ClassMirror turnInstanceIntoSomethingWeCanUse(x) => reflect(x).type;
|
||||
|
||||
@@ -226,7 +226,7 @@ class Writer {
|
||||
* our custom JSON format.
|
||||
*/
|
||||
String toStringFormat() {
|
||||
return JSON.stringify(toMaps());
|
||||
return json.stringify(toMaps());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -260,7 +260,7 @@ class Writer {
|
||||
* stored in the output under "roots" in the default format.
|
||||
*/
|
||||
_rootReferences(roots) =>
|
||||
roots.map(_referenceFor);
|
||||
roots.mappedBy(_referenceFor).toList();
|
||||
|
||||
/**
|
||||
* Given an object, return a reference for it if one exists. If there's
|
||||
@@ -369,7 +369,7 @@ class Reader {
|
||||
// When we set the data, initialize the object storage to a matching size.
|
||||
void set data(List<List> newData) {
|
||||
_data = newData;
|
||||
objects = _data.map((x) => new List(x.length));
|
||||
objects = _data.mappedBy((x) => new List(x.length)).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -379,7 +379,7 @@ class Reader {
|
||||
*/
|
||||
read(String input, [Map externals = const {}]) {
|
||||
namedObjects = externals;
|
||||
var topLevel = JSON.parse(input);
|
||||
var topLevel = json.parse(input);
|
||||
var ruleString = topLevel["rules"];
|
||||
readRules(ruleString, externals);
|
||||
data = topLevel["data"];
|
||||
@@ -415,7 +415,7 @@ class Reader {
|
||||
var ruleString = topLevel[0];
|
||||
readRules(ruleString, externals);
|
||||
var flatData = topLevel[1];
|
||||
var stream = flatData.iterator();
|
||||
var stream = flatData.iterator;
|
||||
var tempData = new List(rules.length);
|
||||
for (var eachRule in rules) {
|
||||
tempData[eachRule.number] = eachRule.pullStateFrom(stream);
|
||||
@@ -425,10 +425,13 @@ class Reader {
|
||||
inflateForRule(eachRule);
|
||||
}
|
||||
var rootsAsInts = topLevel[2];
|
||||
var rootStream = rootsAsInts.iterator();
|
||||
var rootStream = rootsAsInts.iterator;
|
||||
var roots = new List();
|
||||
while (rootStream.hasNext) {
|
||||
roots.add(new Reference(this, rootStream.next(), rootStream.next()));
|
||||
while (rootStream.moveNext()) {
|
||||
var first = rootStream.current;
|
||||
rootStream.moveNext();
|
||||
var second = rootStream.current;
|
||||
roots.add(new Reference(this, first, second));
|
||||
}
|
||||
var x = inflateReference(roots[0]);
|
||||
return inflateReference(roots.first);
|
||||
@@ -646,5 +649,5 @@ class DesignatedRuleForObject {
|
||||
|
||||
DesignatedRuleForObject(this.target, this.rulePredicate);
|
||||
|
||||
possibleRules(List rules) => rules.filter(rulePredicate);
|
||||
possibleRules(List rules) => rules.where(rulePredicate).toList();
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ doNothing(x) => x;
|
||||
|
||||
/** Concatenate two lists. Handle the case where one or both might be null. */
|
||||
// TODO(alanknight): Remove once issue 5342 is resolved.
|
||||
List append(List a, List b) {
|
||||
List append(Iterable a, Iterable b) {
|
||||
if (a == null) {
|
||||
return (b == null) ? [] : new List.from(b);
|
||||
}
|
||||
@@ -29,11 +29,11 @@ List append(List a, List b) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a sorted version of [aCollection], using the default sort criterion.
|
||||
* Always returns a List, regardless of the type of [aCollection].
|
||||
* Return a sorted version of [anIterable], using the default sort criterion.
|
||||
* Always returns a List, regardless of the type of [anIterable].
|
||||
*/
|
||||
List sorted(aCollection) {
|
||||
var result = new List.from(aCollection);
|
||||
List sorted(anIterable) {
|
||||
var result = new List.from(anIterable);
|
||||
result.sort();
|
||||
return result;
|
||||
}
|
||||
@@ -105,9 +105,10 @@ class MapLikeIterableForList extends MapLikeIterable {
|
||||
MapLikeIterableForList(collection) : super(collection);
|
||||
|
||||
void forEach(f) {
|
||||
Iterator iterator = collection.iterator();
|
||||
Iterator iterator = collection.iterator;
|
||||
for (var i = 0; i < collection.length; i++) {
|
||||
f(i, iterator.next());
|
||||
iterator.moveNext();
|
||||
f(i, iterator.current);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +130,13 @@ values(x) {
|
||||
throw new ArgumentError("Invalid argument");
|
||||
}
|
||||
|
||||
mapValues(x, f) {
|
||||
if (x is Set) return x.mappedBy(f).toSet();
|
||||
if (x is Iterable) return x.mappedBy(f).toList();
|
||||
if (x is Map) return new ListLikeIterable(x).map(f);
|
||||
throw new ArgumentError("Invalid argument");
|
||||
}
|
||||
|
||||
/**
|
||||
* A class for iterating over things as if they were Lists, which primarily
|
||||
* means that forEach passes one argument, and map() returns a new Map
|
||||
@@ -159,7 +167,7 @@ class ListLikeIterable {
|
||||
/**
|
||||
* Return an iterator that behaves like a List iterator, taking one parameter.
|
||||
*/
|
||||
Iterator iterator() => collection.values.iterator();
|
||||
Iterator get iterator => collection.values.iterator;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -150,16 +150,19 @@ abstract class SerializationRule {
|
||||
* iterator in a flat format.
|
||||
*/
|
||||
pullStateFrom(Iterator stream) {
|
||||
var numberOfEntries = stream.next();
|
||||
stream.moveNext();
|
||||
var numberOfEntries = stream.current;
|
||||
var ruleData = new List();
|
||||
for (var i = 0; i < numberOfEntries; i++) {
|
||||
var subLength = dataLengthIn(stream);
|
||||
var subList = [];
|
||||
ruleData.add(subList);
|
||||
for (var j = 0; j < subLength; j++) {
|
||||
var a = stream.next();
|
||||
var b = stream.next();
|
||||
if (!(a is int)) {
|
||||
stream.moveNext();
|
||||
var a = stream.current;
|
||||
stream.moveNext();
|
||||
var b = stream.current;
|
||||
if (a is! int) {
|
||||
// This wasn't a reference, just use the first object as a literal.
|
||||
// particularly used for the case of null.
|
||||
subList.add(a);
|
||||
@@ -174,11 +177,11 @@ abstract class SerializationRule {
|
||||
/**
|
||||
* Return the length of the list of data we expect to see on a particular
|
||||
* iterator in a flat format. This may have been encoded in the stream if we
|
||||
* are variable length, or it may be constant. Note that this is expressed in
|
||||
*
|
||||
* are variable length, or it may be constant. Returns null if the [Iterator]
|
||||
* is empty.
|
||||
*/
|
||||
dataLengthIn(Iterator stream) =>
|
||||
writeLengthInFlatFormat ? stream.next() : dataLength;
|
||||
writeLengthInFlatFormat ? (stream..moveNext()).current : dataLength;
|
||||
|
||||
/**
|
||||
* If the data is fixed length, return it here. Unused in the non-flat
|
||||
@@ -231,15 +234,19 @@ class ListRule extends SerializationRule {
|
||||
// TODO(alanknight): This is much too close to the basicRule implementation,
|
||||
// and I'd refactor them if I didn't think this whole mechanism needed to
|
||||
// change soon.
|
||||
var length = stream.next();
|
||||
stream.moveNext();
|
||||
var length = stream.current;
|
||||
var ruleData = new List();
|
||||
for (var i = 0; i < length; i++) {
|
||||
var subLength = stream.next();
|
||||
stream.moveNext();
|
||||
var subLength = stream.current;
|
||||
var subList = new List();
|
||||
ruleData.add(subList);
|
||||
for (var j = 0; j < subLength; j++) {
|
||||
var a = stream.next();
|
||||
var b = stream.next();
|
||||
stream.moveNext();
|
||||
var a = stream.current;
|
||||
stream.moveNext();
|
||||
var b = stream.current;
|
||||
if (!(a is int)) {
|
||||
// This wasn't a reference, just use the first object as a literal.
|
||||
// particularly used for the case of null.
|
||||
@@ -320,10 +327,12 @@ class PrimitiveRule extends SerializationRule {
|
||||
* indicating the number of objects and then N simple objects.
|
||||
*/
|
||||
pullStateFrom(Iterator stream) {
|
||||
var length = stream.next();
|
||||
stream.moveNext();
|
||||
var length = stream.current;
|
||||
var ruleData = new List();
|
||||
for (var i = 0; i < length; i++) {
|
||||
ruleData.add(stream.next());
|
||||
stream.moveNext();
|
||||
ruleData.add(stream.current);
|
||||
}
|
||||
return ruleData;
|
||||
}
|
||||
@@ -487,7 +496,7 @@ abstract class CustomRule extends SerializationRule {
|
||||
|
||||
/** Create a lazy list/map that will inflate its items on demand in [r]. */
|
||||
_lazy(l, Reader r) {
|
||||
if (l is List) return new _LazyList(l, r);
|
||||
if (l is List) return l.mappedBy(r.inflateReference);
|
||||
if (l is Map) return new _LazyMap(l, r);
|
||||
throw new SerializationException("Invalid type: must be Map or List - $l");
|
||||
}
|
||||
@@ -510,14 +519,14 @@ class _LazyMap implements Map {
|
||||
|
||||
int get length => _raw.length;
|
||||
bool get isEmpty => _raw.isEmpty;
|
||||
List get keys => _raw.keys;
|
||||
Iterable get keys => _raw.keys;
|
||||
bool containsKey(x) => _raw.containsKey(x);
|
||||
|
||||
// These operations will work, but may be expensive, and are probably
|
||||
// best avoided.
|
||||
get _inflated => keysAndValues(_raw).map(_reader.inflateReference);
|
||||
bool containsValue(x) => _inflated.containsValue(x);
|
||||
List get values => _inflated.values;
|
||||
Iterable get values => _inflated.values;
|
||||
void forEach(f) => _inflated.forEach(f);
|
||||
|
||||
// These operations are all invalid
|
||||
@@ -527,55 +536,3 @@ class _LazyMap implements Map {
|
||||
remove(x) => _throw();
|
||||
clear() => _throw();
|
||||
}
|
||||
|
||||
/**
|
||||
* This provides an implementation of List that wraps a list which may
|
||||
* contain references to (potentially) non-inflated objects. If these
|
||||
* are accessed it will inflate them. This allows us to pass something that
|
||||
* looks like it's just a list of objects to a [CustomRule] without needing
|
||||
* to inflate all the references in advance.
|
||||
*/
|
||||
class _LazyList implements List {
|
||||
_LazyList(this._raw, this._reader);
|
||||
|
||||
List _raw;
|
||||
Reader _reader;
|
||||
|
||||
// This is the only operation that really matters.
|
||||
operator [](x) => _reader.inflateReference(_raw[x]);
|
||||
|
||||
int get length => _raw.length;
|
||||
bool get isEmpty => _raw.isEmpty;
|
||||
get first => _reader.inflateReference(_raw.first);
|
||||
get last => _reader.inflateReference(_raw.last);
|
||||
|
||||
// These operations will work, but may be expensive, and are probably
|
||||
// best avoided.
|
||||
get _inflated => _raw.map(_reader.inflateReference);
|
||||
map(f) => _inflated.map(f);
|
||||
filter(f) => _inflated.filter(f);
|
||||
bool contains(element) => _inflated.filter(element);
|
||||
forEach(f) => _inflated.forEach(f);
|
||||
reduce(x, f) => _inflated.reduce(x, f);
|
||||
every(f) => _inflated(f);
|
||||
some(f) => _inflated(f);
|
||||
iterator() => _inflated.iterator();
|
||||
indexOf(x, [pos = 0]) => _inflated.indexOf(x);
|
||||
lastIndexOf(x, [pos]) => _inflated.lastIndexOf(x);
|
||||
|
||||
// These operations are all invalid
|
||||
_throw() => throw new UnsupportedError("Not modifiable");
|
||||
operator []=(x, y) => _throw();
|
||||
add(x) => _throw();
|
||||
addLast(x) => _throw();
|
||||
addAll(x) => _throw();
|
||||
sort([f]) => _throw();
|
||||
clear() => _throw();
|
||||
removeAt(x) => _throw();
|
||||
removeLast() => _throw();
|
||||
getRange(x, y) => _throw();
|
||||
setRange(x, y, z, [a]) => _throw();
|
||||
removeRange(x, y) => _throw();
|
||||
insertRange(x, y, [z]) => _throw();
|
||||
void set length(x) => _throw();
|
||||
}
|
||||
@@ -192,7 +192,7 @@ main() {
|
||||
var trace = new Trace(new Writer(s));
|
||||
trace.writer.trace = trace;
|
||||
trace.trace(n1);
|
||||
var all = trace.writer.references.keys;
|
||||
var all = trace.writer.references.keys.toSet();
|
||||
expect(all.length, 4);
|
||||
expect(all.contains(n1), isTrue);
|
||||
expect(all.contains(n2), isTrue);
|
||||
@@ -207,7 +207,7 @@ main() {
|
||||
w.write(n1);
|
||||
expect(w.states.length, 4); // prims, lists, essential lists, basic
|
||||
var children = 0, name = 1, parent = 2;
|
||||
List rootNode = w.states[3].filter((x) => x[name] == "1");
|
||||
List rootNode = w.states[3].where((x) => x[name] == "1").toList();
|
||||
rootNode = rootNode.first;
|
||||
expect(rootNode[parent], isNull);
|
||||
var list = w.states[1].first;
|
||||
@@ -490,7 +490,7 @@ runRoundTripTestFlat(serializerSetUp) {
|
||||
/** Extract the state from [object] using the rules in [s] and return it. */
|
||||
states(object, Serialization s) {
|
||||
var rules = s.rulesFor(object, null);
|
||||
return rules.map((x) => x.extractState(object, doNothing));
|
||||
return rules.mappedBy((x) => x.extractState(object, doNothing)).toList();
|
||||
}
|
||||
|
||||
/** A hard-coded rule for serializing Node instances. */
|
||||
@@ -502,4 +502,4 @@ class NodeRule extends CustomRule {
|
||||
node.parent = state[0];
|
||||
node.children = state[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,10 +172,11 @@ class HtmlEnhancedConfiguration extends Configuration {
|
||||
|
||||
previousGroup = test_.currentGroup;
|
||||
|
||||
var testsInGroup = results.filter(
|
||||
(TestCase t) => t.currentGroup == previousGroup);
|
||||
var testsInGroup = results
|
||||
.where((TestCase t) => t.currentGroup == previousGroup)
|
||||
.toList();
|
||||
var groupTotalTestCount = testsInGroup.length;
|
||||
var groupTestPassedCount = testsInGroup.filter(
|
||||
var groupTestPassedCount = testsInGroup.where(
|
||||
(TestCase t) => t.result == 'pass').length;
|
||||
groupPassFail = groupTotalTestCount == groupTestPassedCount;
|
||||
var passFailClass = "unittest-group-status unittest-group-"
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
*/
|
||||
library matcher;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
part 'src/basematcher.dart';
|
||||
part 'src/collection_matchers.dart';
|
||||
part 'src/core_matchers.dart';
|
||||
|
||||
@@ -844,8 +844,9 @@ class LogEntryList {
|
||||
remainingCount = logs.length;
|
||||
}
|
||||
|
||||
var keyIterator = keys.logs.iterator();
|
||||
LogEntry keyEntry = keyIterator.next();
|
||||
var keyIterator = keys.logs.iterator;
|
||||
keyIterator.moveNext();
|
||||
LogEntry keyEntry = keyIterator.current;
|
||||
MatchState matchState = new MatchState();
|
||||
|
||||
for (LogEntry logEntry in logs) {
|
||||
@@ -869,8 +870,8 @@ class LogEntryList {
|
||||
if (includeKeys) {
|
||||
rtn.logs.add(keyEntry);
|
||||
}
|
||||
if (keyIterator.hasNext) {
|
||||
keyEntry = keyIterator.next();
|
||||
if (keyIterator.moveNext()) {
|
||||
keyEntry = keyIterator.current;
|
||||
} else if (isPreceding) { // We're done.
|
||||
break;
|
||||
}
|
||||
@@ -1460,7 +1461,7 @@ class Mock {
|
||||
if (name == null) { // This log is not shared.
|
||||
log.logs.clear();
|
||||
} else { // This log may be shared.
|
||||
log.logs = log.logs.filter((e) => e.mockName != name);
|
||||
log.logs = log.logs.where((e) => e.mockName != name).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ class _SomeElement extends _CollectionMatcher {
|
||||
_SomeElement(this._matcher);
|
||||
|
||||
bool matches(item, MatchState matchState) {
|
||||
return item.some( (e) => _matcher.matches(e, matchState) );
|
||||
return item.any((e) => _matcher.matches(e, matchState));
|
||||
}
|
||||
|
||||
Description describe(Description description) =>
|
||||
@@ -143,7 +143,7 @@ class _UnorderedEquals extends BaseMatcher {
|
||||
} else if (expectedLength < actualLength) {
|
||||
return 'has too many elements (${actualLength} > ${expectedLength})';
|
||||
}
|
||||
List<bool> matched = new List<bool>(actualLength);
|
||||
List<bool> matched = new List<bool>.fixedLength(actualLength);
|
||||
for (var i = 0; i < actualLength; i++) {
|
||||
matched[i] = false;
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ class Configuration {
|
||||
_receivePort.close();
|
||||
if (success) {
|
||||
_postMessage('unittest-suite-success');
|
||||
_receivePort.close();
|
||||
} else {
|
||||
throw new Exception('Some tests failed.');
|
||||
}
|
||||
@@ -141,7 +142,7 @@ class Configuration {
|
||||
// TODO(nweiz): Use this simpler code once issue 2980 is fixed.
|
||||
// return str.replaceAll(new RegExp("^", multiLine: true), " ");
|
||||
|
||||
return Strings.join(str.split("\n").map((line) => " $line"), "\n");
|
||||
return Strings.join(str.split("\n").mappedBy((line) => " $line"), "\n");
|
||||
}
|
||||
|
||||
/** Handle errors that happen outside the tests. */
|
||||
|
||||
@@ -98,15 +98,15 @@ class _DeepMatcher extends BaseMatcher {
|
||||
if (actual is !Iterable) {
|
||||
return 'is not Iterable';
|
||||
}
|
||||
var expectedIterator = expected.iterator();
|
||||
var actualIterator = actual.iterator();
|
||||
var expectedIterator = expected.iterator;
|
||||
var actualIterator = actual.iterator;
|
||||
var position = 0;
|
||||
String reason = null;
|
||||
while (reason == null) {
|
||||
if (expectedIterator.hasNext) {
|
||||
if (actualIterator.hasNext) {
|
||||
Description r = matcher(expectedIterator.next(),
|
||||
actualIterator.next(),
|
||||
if (expectedIterator.moveNext()) {
|
||||
if (actualIterator.moveNext()) {
|
||||
Description r = matcher(expectedIterator.current,
|
||||
actualIterator.current,
|
||||
'mismatch at position ${position}',
|
||||
depth);
|
||||
if (r != null) reason = r.toString();
|
||||
@@ -114,7 +114,7 @@ class _DeepMatcher extends BaseMatcher {
|
||||
} else {
|
||||
reason = 'shorter than expected';
|
||||
}
|
||||
} else if (actualIterator.hasNext) {
|
||||
} else if (actualIterator.moveNext()) {
|
||||
reason = 'longer than expected';
|
||||
} else {
|
||||
return null;
|
||||
@@ -284,20 +284,20 @@ class Throws extends BaseMatcher {
|
||||
if (item is Future) {
|
||||
// Queue up an asynchronous expectation that validates when the future
|
||||
// completes.
|
||||
item.onComplete(wrapAsync((future) {
|
||||
if (future.hasValue) {
|
||||
expect(false, isTrue, reason:
|
||||
"Expected future to fail, but succeeded with '${future.value}'.");
|
||||
} else if (_matcher != null) {
|
||||
var reason;
|
||||
if (future.stackTrace != null) {
|
||||
var stackTrace = future.stackTrace.toString();
|
||||
stackTrace = " ${stackTrace.replaceAll("\n", "\n ")}";
|
||||
reason = "Actual exception trace:\n$stackTrace";
|
||||
}
|
||||
expect(future.exception, _matcher, reason: reason);
|
||||
item.then((value) {
|
||||
expect(false, isTrue, reason:
|
||||
"Expected future to fail, but succeeded with '$value'.");
|
||||
});
|
||||
|
||||
item.catchError((e) {
|
||||
var reason;
|
||||
if (e.stackTrace != null) {
|
||||
var stackTrace = e.stackTrace.toString();
|
||||
stackTrace = " ${stackTrace.replaceAll("\n", "\n ")}";
|
||||
reason = "Actual exception trace:\n$stackTrace";
|
||||
}
|
||||
}));
|
||||
expect(e.error, _matcher, reason: reason);
|
||||
});
|
||||
|
||||
// It hasn't failed yet.
|
||||
return true;
|
||||
@@ -573,9 +573,9 @@ class _Contains extends BaseMatcher {
|
||||
return item.indexOf(_expected) >= 0;
|
||||
} else if (item is Collection) {
|
||||
if (_expected is Matcher) {
|
||||
return item.some((e) => _expected.matches(e, matchState));
|
||||
return item.any((e) => _expected.matches(e, matchState));
|
||||
} else {
|
||||
return item.some((e) => e == _expected);
|
||||
return item.any((e) => e == _expected);
|
||||
}
|
||||
} else if (item is Map) {
|
||||
return item.containsKey(_expected);
|
||||
@@ -603,7 +603,7 @@ class _In extends BaseMatcher {
|
||||
if (_expected is String) {
|
||||
return _expected.indexOf(item) >= 0;
|
||||
} else if (_expected is Collection) {
|
||||
return _expected.some((e) => e == item);
|
||||
return _expected.any((e) => e == item);
|
||||
} else if (_expected is Map) {
|
||||
return _expected.containsKey(item);
|
||||
}
|
||||
|
||||
@@ -35,18 +35,20 @@ class _Completes extends BaseMatcher {
|
||||
bool matches(item, MatchState matchState) {
|
||||
if (item is! Future) return false;
|
||||
|
||||
item.onComplete(wrapAsync((future) {
|
||||
item.then((value) {
|
||||
if (_matcher != null) expect(value, _matcher);
|
||||
});
|
||||
|
||||
item.catchError((e) {
|
||||
var reason = 'Expected future to complete successfully, but it failed '
|
||||
'with ${future.exception}';
|
||||
'with ${e.error}';
|
||||
if (future.stackTrace != null) {
|
||||
var stackTrace = future.stackTrace.toString();
|
||||
var stackTrace = e.stackTrace.toString();
|
||||
stackTrace = ' ${stackTrace.replaceAll('\n', '\n ')}';
|
||||
reason = '$reason\nStack trace:\n$stackTrace';
|
||||
}
|
||||
|
||||
expect(future.hasValue, isTrue, reason: reason);
|
||||
if (_matcher != null) expect(future.value, _matcher);
|
||||
}));
|
||||
expect(false, isTrue, reason: reason);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -147,6 +147,7 @@
|
||||
*/
|
||||
library unittest;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:isolate';
|
||||
import 'matcher.dart';
|
||||
export 'matcher.dart';
|
||||
@@ -736,7 +737,7 @@ void filterTests(testFilter) {
|
||||
} else if (testFilter is Function) {
|
||||
filterFunction = testFilter;
|
||||
}
|
||||
_tests = _tests.filter(filterFunction);
|
||||
_tests = _tests.where(filterFunction).toList();
|
||||
}
|
||||
|
||||
/** Runs all queued tests, one at a time. */
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
|
||||
library webdriver;
|
||||
|
||||
import 'dart:json';
|
||||
import 'dart:json' as json;
|
||||
import 'dart:uri';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
part 'src/base64decoder.dart';
|
||||
|
||||
@@ -207,7 +206,7 @@ class WebDriverBase {
|
||||
_path = matches[2];
|
||||
var idx = _host.indexOf(':');
|
||||
if (idx >= 0) {
|
||||
_port = parseInt(_host.substring(idx+1));
|
||||
_port = int.parse(_host.substring(idx+1));
|
||||
_host = _host.substring(0, idx);
|
||||
} else {
|
||||
_port = 80;
|
||||
@@ -241,7 +240,7 @@ class WebDriverBase {
|
||||
throw new Exception(
|
||||
'The http method called for ${command} is ${http_method} but it has '
|
||||
'to be POST if you want to pass the JSON params '
|
||||
'${JSON.stringify(params)}');
|
||||
'${json.stringify(params)}');
|
||||
}
|
||||
|
||||
var path = command;
|
||||
@@ -258,7 +257,7 @@ class WebDriverBase {
|
||||
HttpHeaders.CONTENT_TYPE, 'application/json;charset=UTF-8');
|
||||
OutputStream s = r.outputStream;
|
||||
if (params != null && params is Map) {
|
||||
s.writeString(JSON.stringify(params));
|
||||
s.writeString(json.stringify(params));
|
||||
}
|
||||
s.close();
|
||||
};
|
||||
@@ -282,7 +281,7 @@ class WebDriverBase {
|
||||
var value = null;
|
||||
results = sbuf.toString().trim();
|
||||
// For some reason we get a bunch of NULs on the end
|
||||
// of the text and the JSON parser blows up on these, so
|
||||
// of the text and the json.parse blows up on these, so
|
||||
// strip them. We have to do this the hard way as
|
||||
// replaceAll('\0', '') does not work.
|
||||
// These NULs can be seen in the TCP packet, so it is not
|
||||
@@ -301,7 +300,7 @@ class WebDriverBase {
|
||||
if (status == 0 && results.length > 0) {
|
||||
// 4xx responses send plain text; others send JSON.
|
||||
if (r.statusCode < 400) {
|
||||
results = JSON.parse(results);
|
||||
results = json.parse(results);
|
||||
status = results['status'];
|
||||
}
|
||||
if (results is Map && (results as Map).containsKey('value')) {
|
||||
|
||||
@@ -45,6 +45,7 @@ class Builtin {
|
||||
static Dart_NativeFunction BuiltinNativeLookup(Dart_Handle name,
|
||||
int argument_count);
|
||||
|
||||
static const char async_source_[];
|
||||
static const char builtin_source_[];
|
||||
static const char crypto_source_[];
|
||||
static const char io_source_[];
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
const char* DartUtils::original_working_directory = NULL;
|
||||
const char* DartUtils::kDartScheme = "dart:";
|
||||
const char* DartUtils::kDartExtensionScheme = "dart-ext:";
|
||||
const char* DartUtils::kASyncLibURL = "dart:async";
|
||||
const char* DartUtils::kBuiltinLibURL = "dart:builtin";
|
||||
const char* DartUtils::kCoreLibURL = "dart:core";
|
||||
const char* DartUtils::kCryptoLibURL = "dart:crypto";
|
||||
@@ -416,17 +417,17 @@ Dart_Handle DartUtils::PrepareForScriptLoading(const char* package_root,
|
||||
print);
|
||||
|
||||
// Setup the 'timer' factory.
|
||||
Dart_Handle url = NewString(kIsolateLibURL);
|
||||
Dart_Handle url = NewString(kASyncLibURL);
|
||||
DART_CHECK_VALID(url);
|
||||
Dart_Handle isolate_lib = Dart_LookupLibrary(url);
|
||||
DART_CHECK_VALID(isolate_lib);
|
||||
Dart_Handle async_lib = Dart_LookupLibrary(url);
|
||||
DART_CHECK_VALID(async_lib);
|
||||
Dart_Handle io_lib = Builtin::LoadAndCheckLibrary(Builtin::kIOLibrary);
|
||||
Dart_Handle timer_closure =
|
||||
Dart_Invoke(io_lib, NewString("_getTimerFactoryClosure"), 0, NULL);
|
||||
Dart_Handle args[1];
|
||||
args[0] = timer_closure;
|
||||
DART_CHECK_VALID(Dart_Invoke(
|
||||
isolate_lib, NewString("_setTimerFactoryClosure"), 1, args));
|
||||
async_lib, NewString("_setTimerFactoryClosure"), 1, args));
|
||||
|
||||
// Set up package root if specified.
|
||||
if (package_root != NULL) {
|
||||
|
||||
@@ -162,6 +162,7 @@ class DartUtils {
|
||||
|
||||
static const char* kDartScheme;
|
||||
static const char* kDartExtensionScheme;
|
||||
static const char* kASyncLibURL;
|
||||
static const char* kBuiltinLibURL;
|
||||
static const char* kCoreLibURL;
|
||||
static const char* kCryptoLibURL;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// file which is in lib/io/io.dart.
|
||||
|
||||
#library("dart:io");
|
||||
#import("dart:async");
|
||||
#import("dart:crypto");
|
||||
#import("dart:isolate");
|
||||
#import("dart:math");
|
||||
|
||||
@@ -53,7 +53,7 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
throw new ArgumentError("Arguments is not a List: $arguments");
|
||||
}
|
||||
int len = arguments.length;
|
||||
_arguments = new List<String>(len);
|
||||
_arguments = new List<String>.fixedLength(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
var arg = arguments[i];
|
||||
if (arg is !String) {
|
||||
@@ -170,7 +170,7 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
_out.close();
|
||||
_err.close();
|
||||
_exitHandler.close();
|
||||
completer.completeException(
|
||||
completer.completeError(
|
||||
new ProcessException(_path,
|
||||
_arguments,
|
||||
status._errorMessage,
|
||||
@@ -194,7 +194,7 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
// callback when a process terminates.
|
||||
int exitDataRead = 0;
|
||||
final int EXIT_DATA_SIZE = 8;
|
||||
List<int> exitDataBuffer = new List<int>(EXIT_DATA_SIZE);
|
||||
List<int> exitDataBuffer = new List<int>.fixedLength(EXIT_DATA_SIZE);
|
||||
_exitHandler.inputStream.onData = () {
|
||||
|
||||
int exitCode(List<int> ints) {
|
||||
@@ -206,9 +206,8 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
|
||||
void handleExit() {
|
||||
_ended = true;
|
||||
if (_onExit != null) {
|
||||
_onExit(exitCode(exitDataBuffer));
|
||||
}
|
||||
_exitCode = exitCode(exitDataBuffer);
|
||||
if (_onExit != null) _onExit(_exitCode);
|
||||
_out.close();
|
||||
}
|
||||
|
||||
@@ -257,12 +256,28 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
return _kill(this, signal._signalNumber);
|
||||
}
|
||||
|
||||
void add(List<int> data) {
|
||||
stdin.write(data);
|
||||
}
|
||||
|
||||
void close() {
|
||||
stdin.close();
|
||||
}
|
||||
|
||||
void signalError(ASyncError error) {
|
||||
// TODO(ajohnsen): close?
|
||||
}
|
||||
|
||||
Stream<List<int>> get stdoutStream
|
||||
=> new _InputStreamController(stdout).stream;
|
||||
|
||||
Stream<List<int>> get stderrStream
|
||||
=> new _InputStreamController(stderr).stream;
|
||||
|
||||
bool _kill(Process p, int signal) native "Process_Kill";
|
||||
|
||||
void set onExit(void callback(int exitCode)) {
|
||||
if (_ended) {
|
||||
throw new ProcessException(_path, _arguments, "Process killed");
|
||||
}
|
||||
if (_ended) callback(_exitCode);
|
||||
_onExit = callback;
|
||||
}
|
||||
|
||||
@@ -275,6 +290,7 @@ class _ProcessImpl extends NativeFieldWrapperClass1 implements Process {
|
||||
_Socket _out;
|
||||
_Socket _err;
|
||||
Socket _exitHandler;
|
||||
int _exitCode;
|
||||
bool _ended;
|
||||
bool _started;
|
||||
Function _onExit;
|
||||
@@ -346,11 +362,8 @@ class _NonInteractiveProcess {
|
||||
_stderrClosed = true;
|
||||
_checkDone();
|
||||
};
|
||||
});
|
||||
|
||||
processFuture.handleException((error) {
|
||||
_completer.completeException(error);
|
||||
return true;
|
||||
}).catchError((error) {
|
||||
_completer.completeError(error.error);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ class _SocketBase extends NativeFieldWrapperClass1 {
|
||||
static const int _LAST_COMMAND = _SHUTDOWN_WRITE_COMMAND;
|
||||
|
||||
_SocketBase () {
|
||||
_handlerMap = new List(_LAST_EVENT + 1);
|
||||
_handlerMap = new List.fixedLength(_LAST_EVENT + 1);
|
||||
_handlerMask = 0;
|
||||
_canActivateHandlers = true;
|
||||
_closed = true;
|
||||
@@ -339,7 +339,7 @@ class _Socket extends _SocketBase implements Socket {
|
||||
factory _Socket(String host, int port) {
|
||||
Socket socket = new _Socket._internal();
|
||||
_ensureSocketService();
|
||||
List request = new List(2);
|
||||
List request = new List.fixedLength(2);
|
||||
request[0] = HOST_NAME_LOOKUP;
|
||||
request[1] = host;
|
||||
_socketService.call(request).then((response) {
|
||||
|
||||
+156
-36
@@ -61,31 +61,68 @@ class _ObjectArray<E> implements List<E> {
|
||||
|
||||
// Collection interface.
|
||||
|
||||
bool contains(E element) => Collections.contains(this, element);
|
||||
bool contains(E element) {
|
||||
return Collections.contains(this, element);
|
||||
}
|
||||
|
||||
void forEach(f(E element)) {
|
||||
Collections.forEach(this, f);
|
||||
}
|
||||
|
||||
Collection map(f(E element)) {
|
||||
return Collections.map(
|
||||
this, new _GrowableObjectArray.withCapacity(length), f);
|
||||
String join([String separator]) {
|
||||
return Collections.join(this, separator);
|
||||
}
|
||||
|
||||
List mappedBy(f(E element)) {
|
||||
return new MappedList<E, dynamic>(this, f);
|
||||
}
|
||||
|
||||
reduce(initialValue, combine(previousValue, E element)) {
|
||||
return Collections.reduce(this, initialValue, combine);
|
||||
}
|
||||
|
||||
Collection<E> filter(bool f(E element)) {
|
||||
return Collections.filter(this, new _GrowableObjectArray<E>(), f);
|
||||
Iterable<E> where(bool f(E element)) {
|
||||
return new WhereIterable<E>(this, f);
|
||||
}
|
||||
|
||||
List<E> take(int n) {
|
||||
return new ListView<E>(this, 0, n);
|
||||
}
|
||||
|
||||
Iterable<E> takeWhile(bool test(E value)) {
|
||||
return new TakeWhileIterable<E>(this, test);
|
||||
}
|
||||
|
||||
List<E> skip(int n) {
|
||||
return new ListView<E>(this, n, null);
|
||||
}
|
||||
|
||||
Iterable<E> skipWhile(bool test(E value)) {
|
||||
return new SkipWhileIterable<E>(this, test);
|
||||
}
|
||||
|
||||
bool every(bool f(E element)) {
|
||||
return Collections.every(this, f);
|
||||
}
|
||||
|
||||
bool some(bool f(E element)) {
|
||||
return Collections.some(this, f);
|
||||
bool any(bool f(E element)) {
|
||||
return Collections.any(this, f);
|
||||
}
|
||||
|
||||
E firstMatching(bool test(E value), {E orElse()}) {
|
||||
return Collections.firstMatching(this, test, orElse);
|
||||
}
|
||||
|
||||
E lastMatching(bool test(E value), {E orElse()}) {
|
||||
return Collections.lastMatchingInList(this, test, orElse);
|
||||
}
|
||||
|
||||
E singleMatching(bool test(E value)) {
|
||||
return Collections.singleMatching(this, test);
|
||||
}
|
||||
|
||||
E elementAt(int index) {
|
||||
return this[index];
|
||||
}
|
||||
|
||||
bool get isEmpty {
|
||||
@@ -106,7 +143,7 @@ class _ObjectArray<E> implements List<E> {
|
||||
return Arrays.lastIndexOf(this, element, start);
|
||||
}
|
||||
|
||||
Iterator<E> iterator() {
|
||||
Iterator<E> get iterator {
|
||||
return new _FixedSizeArrayIterator<E>(this);
|
||||
}
|
||||
|
||||
@@ -119,7 +156,7 @@ class _ObjectArray<E> implements List<E> {
|
||||
add(element);
|
||||
}
|
||||
|
||||
void addAll(Collection<E> elements) {
|
||||
void addAll(Iterable<E> iterable) {
|
||||
throw new UnsupportedError(
|
||||
"Cannot add to a non-extendable array");
|
||||
}
|
||||
@@ -140,11 +177,31 @@ class _ObjectArray<E> implements List<E> {
|
||||
}
|
||||
|
||||
E get first {
|
||||
return this[0];
|
||||
if (length > 0) return this[0];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
E get last {
|
||||
return this[length - 1];
|
||||
if (length > 0) return this[length - 1];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
E get single {
|
||||
if (length == 1) return this[0];
|
||||
if (length == 0) throw new StateError("No elements");
|
||||
throw new StateError("More than one element");
|
||||
}
|
||||
|
||||
E min([int compare(E a, E b)]) => Collections.min(this, compare);
|
||||
|
||||
E max([int compare(E a, E b)]) => Collections.max(this, compare);
|
||||
|
||||
List<E> toList() {
|
||||
return new List<E>.from(this);
|
||||
}
|
||||
|
||||
Set<E> toSet() {
|
||||
return new Set<E>.from(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,31 +265,68 @@ class _ImmutableArray<E> implements List<E> {
|
||||
|
||||
// Collection interface.
|
||||
|
||||
bool contains(E element) => Collections.contains(this, element);
|
||||
bool contains(E element) {
|
||||
return Collections.contains(this, element);
|
||||
}
|
||||
|
||||
void forEach(f(E element)) {
|
||||
Collections.forEach(this, f);
|
||||
}
|
||||
|
||||
Collection map(f(E element)) {
|
||||
return Collections.map(
|
||||
this, new _GrowableObjectArray.withCapacity(length), f);
|
||||
List mappedBy(f(E element)) {
|
||||
return new MappedList<E, dynamic>(this, f);
|
||||
}
|
||||
|
||||
String join([String separator]) {
|
||||
return Collections.join(this, separator);
|
||||
}
|
||||
|
||||
reduce(initialValue, combine(previousValue, E element)) {
|
||||
return Collections.reduce(this, initialValue, combine);
|
||||
}
|
||||
|
||||
Collection<E> filter(bool f(E element)) {
|
||||
return Collections.filter(this, new _GrowableObjectArray<E>(), f);
|
||||
Iterable<E> where(bool f(E element)) {
|
||||
return new WhereIterable<E>(this, f);
|
||||
}
|
||||
|
||||
List<E> take(int n) {
|
||||
return new ListView<E>(this, 0, n);
|
||||
}
|
||||
|
||||
Iterable<E> takeWhile(bool test(E value)) {
|
||||
return new TakeWhileIterable<E>(this, test);
|
||||
}
|
||||
|
||||
List<E> skip(int n) {
|
||||
return new ListView<E>(this, n, null);
|
||||
}
|
||||
|
||||
Iterable<E> skipWhile(bool test(E value)) {
|
||||
return new SkipWhileIterable<E>(this, test);
|
||||
}
|
||||
|
||||
bool every(bool f(E element)) {
|
||||
return Collections.every(this, f);
|
||||
}
|
||||
|
||||
bool some(bool f(E element)) {
|
||||
return Collections.some(this, f);
|
||||
bool any(bool f(E element)) {
|
||||
return Collections.any(this, f);
|
||||
}
|
||||
|
||||
E firstMatching(bool test(E value), {E orElse()}) {
|
||||
return Collections.firstMatching(this, test, orElse);
|
||||
}
|
||||
|
||||
E lastMatching(bool test(E value), {E orElse()}) {
|
||||
return Collections.lastMatchingInList(this, test, orElse);
|
||||
}
|
||||
|
||||
E singleMatching(bool test(E value)) {
|
||||
return Collections.singleMatching(this, test);
|
||||
}
|
||||
|
||||
E elementAt(int index) {
|
||||
return this[index];
|
||||
}
|
||||
|
||||
bool get isEmpty {
|
||||
@@ -257,7 +351,7 @@ class _ImmutableArray<E> implements List<E> {
|
||||
return Arrays.lastIndexOf(this, element, start);
|
||||
}
|
||||
|
||||
Iterator<E> iterator() {
|
||||
Iterator<E> get iterator {
|
||||
return new _FixedSizeArrayIterator<E>(this);
|
||||
}
|
||||
|
||||
@@ -270,7 +364,7 @@ class _ImmutableArray<E> implements List<E> {
|
||||
add(element);
|
||||
}
|
||||
|
||||
void addAll(Collection<E> elements) {
|
||||
void addAll(Iterable<E> elements) {
|
||||
throw new UnsupportedError(
|
||||
"Cannot add to an immutable array");
|
||||
}
|
||||
@@ -291,34 +385,60 @@ class _ImmutableArray<E> implements List<E> {
|
||||
}
|
||||
|
||||
E get first {
|
||||
return this[0];
|
||||
if (length > 0) return this[0];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
E get last {
|
||||
return this[length - 1];
|
||||
if (length > 0) return this[length - 1];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
E get single {
|
||||
if (length == 1) return this[0];
|
||||
if (length == 0) throw new StateError("No elements");
|
||||
throw new StateError("More than one element");
|
||||
}
|
||||
|
||||
E min([int compare(E a, E b)]) => Collections.min(this, compare);
|
||||
|
||||
E max([int compare(E a, E b)]) => Collections.max(this, compare);
|
||||
|
||||
List<E> toList() {
|
||||
return new List<E>.from(this);
|
||||
}
|
||||
|
||||
Set<E> toSet() {
|
||||
return new Set<E>.from(this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Iterator for arrays with fixed size.
|
||||
class _FixedSizeArrayIterator<E> implements Iterator<E> {
|
||||
final List<E> _array;
|
||||
final int _length; // Cache array length for faster access.
|
||||
int _position;
|
||||
E _current;
|
||||
|
||||
_FixedSizeArrayIterator(List array)
|
||||
: _array = array, _length = array.length, _pos = 0 {
|
||||
: _array = array, _length = array.length, _position = -1 {
|
||||
assert(array is _ObjectArray || array is _ImmutableArray);
|
||||
}
|
||||
|
||||
bool get hasNext {
|
||||
return _length > _pos;
|
||||
}
|
||||
|
||||
E next() {
|
||||
if (!hasNext) {
|
||||
throw new StateError("No more elements");
|
||||
bool moveNext() {
|
||||
int nextPosition = _position + 1;
|
||||
if (nextPosition < _length) {
|
||||
_current = _array[nextPosition];
|
||||
_position = nextPosition;
|
||||
return true;
|
||||
}
|
||||
return _array[_pos++];
|
||||
_position = _length;
|
||||
_current = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
final List<E> _array;
|
||||
final int _length; // Cache array length for faster access.
|
||||
int _pos;
|
||||
E get current {
|
||||
return _current;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,43 @@
|
||||
// returns a _GrowableObjectArray if length is null, otherwise returns
|
||||
// fixed size array.
|
||||
patch class List<E> {
|
||||
/* patch */ factory List([int length = null]) {
|
||||
if (length == null) {
|
||||
return new _GrowableObjectArray<E>();
|
||||
} else {
|
||||
return new _ObjectArray<E>(length);
|
||||
/* patch */ factory List([int length = 0]) {
|
||||
if (length is! int || length < 0) {
|
||||
throw new ArgumentError("Length must be a positive integer: $length.");
|
||||
}
|
||||
_GrowableObjectArray<E> result = new _GrowableObjectArray<E>();
|
||||
result.length = length;
|
||||
return result;
|
||||
}
|
||||
|
||||
/* patch */ factory List.fixedLength(int length, {E fill: null}) {
|
||||
if (length is! int || length < 0) {
|
||||
throw new ArgumentError("Length must be a positive integer: $length.");
|
||||
}
|
||||
_ObjectArray<E> result = new _ObjectArray<E>(length);
|
||||
if (fill != null) {
|
||||
for (int i = 0; i < length; i++) {
|
||||
result[i] = fill;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* patch */ factory List.filled(int length, E fill) {
|
||||
if (length is! int || length < 0) {
|
||||
throw new ArgumentError("Length must be a positive integer: $length.");
|
||||
}
|
||||
_GrowableObjectArray<E> result =
|
||||
new _GrowableObjectArray<E>.withCapacity(length < 4 ? 4 : length);
|
||||
if (length != 0) {
|
||||
result.length = length;
|
||||
if (fill != null) {
|
||||
for (int i = 0; i < length; i++) {
|
||||
result[i] = fill;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Factory constructing a mutable List from a parser generated List literal.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
|
||||
# for 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 file contains all sources for the dart:isolate library.
|
||||
{
|
||||
'sources': [
|
||||
'timer_patch.dart',
|
||||
],
|
||||
}
|
||||
+131
-81
@@ -196,8 +196,12 @@ abstract class _ByteArrayBase {
|
||||
}
|
||||
}
|
||||
|
||||
Collection map(f(element)) {
|
||||
return Collections.map(this, new List(), f);
|
||||
List mappedBy(f(int element)) {
|
||||
return new MappedList<int, dynamic>(this, f);
|
||||
}
|
||||
|
||||
String join([String separator]) {
|
||||
return Collections.join(this, separator);
|
||||
}
|
||||
|
||||
dynamic reduce(dynamic initialValue,
|
||||
@@ -205,16 +209,48 @@ abstract class _ByteArrayBase {
|
||||
return Collections.reduce(this, initialValue, combine);
|
||||
}
|
||||
|
||||
Collection filter(bool f(element)) {
|
||||
return Collections.filter(this, new List(), f);
|
||||
Collection where(bool f(element)) {
|
||||
return new WhereIterable<int>(this, f);
|
||||
}
|
||||
|
||||
List<int> take(int n) {
|
||||
return new ListView<int>(this, 0, n);
|
||||
}
|
||||
|
||||
Iterable<int> takeWhile(bool test(int value)) {
|
||||
return new TakeWhileIterable<int>(this, test);
|
||||
}
|
||||
|
||||
List<int> skip(int n) {
|
||||
return new ListView<int>(this, n, null);
|
||||
}
|
||||
|
||||
Iterable<int> skipWhile(bool test(int value)) {
|
||||
return new SkipWhileIterable<int>(this, test);
|
||||
}
|
||||
|
||||
bool every(bool f(element)) {
|
||||
return Collections.every(this, f);
|
||||
}
|
||||
|
||||
bool some(bool f(element)) {
|
||||
return Collections.some(this, f);
|
||||
bool any(bool f(element)) {
|
||||
return Collections.any(this, f);
|
||||
}
|
||||
|
||||
int firstMatching(bool test(int value), {int orElse()}) {
|
||||
return Collections.firstMatching(this, test, orElse);
|
||||
}
|
||||
|
||||
int lastMatching(bool test(int value), {int orElse()}) {
|
||||
return Collections.lastMatchingInList(this, test, orElse);
|
||||
}
|
||||
|
||||
int singleMatching(bool test(int value)) {
|
||||
return Collections.singleMatching(this, test);
|
||||
}
|
||||
|
||||
int elementAt(int index) {
|
||||
return this[index];
|
||||
}
|
||||
|
||||
bool get isEmpty {
|
||||
@@ -242,7 +278,7 @@ abstract class _ByteArrayBase {
|
||||
"Cannot add to a non-extendable array");
|
||||
}
|
||||
|
||||
void addAll(Collection value) {
|
||||
void addAll(Iterable value) {
|
||||
throw new UnsupportedError(
|
||||
"Cannot add to a non-extendable array");
|
||||
}
|
||||
@@ -271,14 +307,26 @@ abstract class _ByteArrayBase {
|
||||
"Cannot remove from a non-extendable array");
|
||||
}
|
||||
|
||||
get first {
|
||||
return this[0];
|
||||
int get first {
|
||||
if (length > 0) return this[0];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
get last {
|
||||
return this[length - 1];
|
||||
int get last {
|
||||
if (length > 0) return this[length - 1];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
int get single {
|
||||
if (length == 1) return this[0];
|
||||
if (length == 0) throw new StateError("No elements");
|
||||
throw new StateError("More than one element");
|
||||
}
|
||||
|
||||
int min([int compare(int a, int b)]) => Collections.min(this, compare);
|
||||
|
||||
int max([int compare(int a, int b)]) => Collections.max(this, compare);
|
||||
|
||||
void removeRange(int start, int length) {
|
||||
throw new UnsupportedError(
|
||||
"Cannot remove from a non-extendable array");
|
||||
@@ -299,6 +347,14 @@ abstract class _ByteArrayBase {
|
||||
length * this.bytesPerElement());
|
||||
}
|
||||
|
||||
List<int> toList() {
|
||||
return new List<int>.from(this);
|
||||
}
|
||||
|
||||
Set<int> toSet() {
|
||||
return new Set<int>.from(this);
|
||||
}
|
||||
|
||||
int _length() native "ByteArray_getLength";
|
||||
|
||||
void _setRange(int startInBytes, int lengthInBytes,
|
||||
@@ -436,7 +492,7 @@ class _Int8Array extends _ByteArrayBase implements Int8List {
|
||||
_setIndexed(index, _toInt8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -505,7 +561,7 @@ class _Uint8Array extends _ByteArrayBase implements Uint8List {
|
||||
_setIndexed(index, _toUint8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -576,7 +632,7 @@ class _Uint8ClampedArray extends _ByteArrayBase implements Uint8ClampedList {
|
||||
_setIndexed(index, _toClampedUint8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -646,7 +702,7 @@ class _Int16Array extends _ByteArrayBase implements Int16List {
|
||||
_setIndexed(index, _toInt16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -715,7 +771,7 @@ class _Uint16Array extends _ByteArrayBase implements Uint16List {
|
||||
_setIndexed(index, _toUint16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -784,7 +840,7 @@ class _Int32Array extends _ByteArrayBase implements Int32List {
|
||||
_setIndexed(index, _toInt32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -854,7 +910,7 @@ class _Uint32Array extends _ByteArrayBase implements Uint32List {
|
||||
_setIndexed(index, _toUint32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -923,7 +979,7 @@ class _Int64Array extends _ByteArrayBase implements Int64List {
|
||||
_setIndexed(index, _toInt64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -992,7 +1048,7 @@ class _Uint64Array extends _ByteArrayBase implements Uint64List {
|
||||
_setIndexed(index, _toUint64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1061,7 +1117,7 @@ class _Float32Array extends _ByteArrayBase implements Float32List {
|
||||
_setIndexed(index, value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
@@ -1130,7 +1186,7 @@ class _Float64Array extends _ByteArrayBase implements Float64List {
|
||||
_setIndexed(index, value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
@@ -1184,7 +1240,7 @@ class _ExternalInt8Array extends _ByteArrayBase implements Int8List {
|
||||
_setIndexed(index, _toInt8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1234,7 +1290,7 @@ class _ExternalUint8Array extends _ByteArrayBase implements Uint8List {
|
||||
_setIndexed(index, _toUint8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1284,7 +1340,7 @@ class _ExternalInt16Array extends _ByteArrayBase implements Int16List {
|
||||
_setIndexed(index, _toInt16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1334,7 +1390,7 @@ class _ExternalUint16Array extends _ByteArrayBase implements Uint16List {
|
||||
_setIndexed(index, _toUint16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1386,7 +1442,7 @@ class _ExternalInt32Array extends _ByteArrayBase implements Int32List {
|
||||
_setIndexed(index, _toInt32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1438,7 +1494,7 @@ class _ExternalUint32Array extends _ByteArrayBase implements Uint32List {
|
||||
_setIndexed(index, _toUint32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1490,7 +1546,7 @@ class _ExternalInt64Array extends _ByteArrayBase implements Int64List {
|
||||
_setIndexed(index, _toInt64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1542,7 +1598,7 @@ class _ExternalUint64Array extends _ByteArrayBase implements Uint64List {
|
||||
_setIndexed(index, _toUint64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -1594,7 +1650,7 @@ class _ExternalFloat32Array extends _ByteArrayBase implements Float32List {
|
||||
_setIndexed(index, value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
@@ -1646,7 +1702,7 @@ class _ExternalFloat64Array extends _ByteArrayBase implements Float64List {
|
||||
_setIndexed(index, value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
@@ -1690,25 +1746,29 @@ class _ExternalFloat64Array extends _ByteArrayBase implements Float64List {
|
||||
|
||||
|
||||
class _ByteArrayIterator<E> implements Iterator<E> {
|
||||
final List<E> _array;
|
||||
final int _length;
|
||||
int _position;
|
||||
E _current;
|
||||
|
||||
_ByteArrayIterator(List array)
|
||||
: _array = array, _length = array.length, _pos = 0 {
|
||||
: _array = array, _length = array.length, _position = -1 {
|
||||
assert(array is _ByteArrayBase || array is _ByteArrayViewBase);
|
||||
}
|
||||
|
||||
bool get hasNext {
|
||||
return _length > _pos;
|
||||
}
|
||||
|
||||
E next() {
|
||||
if (!hasNext) {
|
||||
throw new StateError("No more elements");
|
||||
bool moveNext() {
|
||||
int nextPosition = _position + 1;
|
||||
if (nextPosition < _length) {
|
||||
_current = _array[nextPosition];
|
||||
_position = nextPosition;
|
||||
return true;
|
||||
}
|
||||
return _array[_pos++];
|
||||
_position = _length;
|
||||
_current = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
final List<E> _array;
|
||||
final int _length;
|
||||
int _pos;
|
||||
E get current => _current;
|
||||
}
|
||||
|
||||
|
||||
@@ -1807,7 +1867,10 @@ class _ByteArrayView implements ByteArray {
|
||||
}
|
||||
|
||||
|
||||
class _ByteArrayViewBase {
|
||||
// TODO(floitsch): extending the collection adds extra cost (because of type
|
||||
// parameters). Consider copying the functions from Collection into this class
|
||||
// and just implementing Collection<int>.
|
||||
class _ByteArrayViewBase extends Collection<int> {
|
||||
num operator[](int index);
|
||||
|
||||
// Methods implementing the Collection interface.
|
||||
@@ -1819,27 +1882,6 @@ class _ByteArrayViewBase {
|
||||
}
|
||||
}
|
||||
|
||||
Collection map(f(element)) {
|
||||
return Collections.map(this, new List(), f);
|
||||
}
|
||||
|
||||
dynamic reduce(dynamic initialValue,
|
||||
dynamic combine(dynamic initialValue, element)) {
|
||||
return Collections.reduce(this, initialValue, combine);
|
||||
}
|
||||
|
||||
Collection filter(bool f(element)) {
|
||||
return Collections.filter(this, new List(), f);
|
||||
}
|
||||
|
||||
bool every(bool f(element)) {
|
||||
return Collections.every(this, f);
|
||||
}
|
||||
|
||||
bool some(bool f(element)) {
|
||||
return Collections.some(this, f);;
|
||||
}
|
||||
|
||||
bool get isEmpty {
|
||||
return this.length == 0;
|
||||
}
|
||||
@@ -1863,7 +1905,7 @@ class _ByteArrayViewBase {
|
||||
"Cannot add to a non-extendable array");
|
||||
}
|
||||
|
||||
void addAll(Collection value) {
|
||||
void addAll(Iterable value) {
|
||||
throw new UnsupportedError(
|
||||
"Cannot add to a non-extendable array");
|
||||
}
|
||||
@@ -1892,12 +1934,20 @@ class _ByteArrayViewBase {
|
||||
"Cannot remove from a non-extendable array");
|
||||
}
|
||||
|
||||
get first {
|
||||
return this[0];
|
||||
int get first {
|
||||
if (length > 0) return this[0];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
get last {
|
||||
return this[length - 1];
|
||||
int get last {
|
||||
if (length > 0) return this[length - 1];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
int get single {
|
||||
if (length == 1) return this[0];
|
||||
if (length == 0) throw new StateError("No elements");
|
||||
throw new StateError("More than one element");
|
||||
}
|
||||
|
||||
void removeRange(int start, int length) {
|
||||
@@ -1942,7 +1992,7 @@ class _Int8ArrayView extends _ByteArrayViewBase implements Int8List {
|
||||
_array.setInt8(_offset + (index * _BYTES_PER_ELEMENT), _toInt8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2014,7 +2064,7 @@ class _Uint8ArrayView extends _ByteArrayViewBase implements Uint8List {
|
||||
_array.setUint8(_offset + (index * _BYTES_PER_ELEMENT), _toUint8(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2086,7 +2136,7 @@ class _Int16ArrayView extends _ByteArrayViewBase implements Int16List {
|
||||
_array.setInt16(_offset + (index * _BYTES_PER_ELEMENT), _toInt16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2158,7 +2208,7 @@ class _Uint16ArrayView extends _ByteArrayViewBase implements Uint16List {
|
||||
_array.setUint16(_offset + (index * _BYTES_PER_ELEMENT), _toUint16(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2230,7 +2280,7 @@ class _Int32ArrayView extends _ByteArrayViewBase implements Int32List {
|
||||
_array.setInt32(_offset + (index * _BYTES_PER_ELEMENT), _toInt32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2302,7 +2352,7 @@ class _Uint32ArrayView extends _ByteArrayViewBase implements Uint32List {
|
||||
_array.setUint32(_offset + (index * _BYTES_PER_ELEMENT), _toUint32(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2374,7 +2424,7 @@ class _Int64ArrayView extends _ByteArrayViewBase implements Int64List {
|
||||
_array.setInt64(_offset + (index * _BYTES_PER_ELEMENT), _toInt64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2446,7 +2496,7 @@ class _Uint64ArrayView extends _ByteArrayViewBase implements Uint64List {
|
||||
_array.setUint64(_offset + (index * _BYTES_PER_ELEMENT), _toUint64(value));
|
||||
}
|
||||
|
||||
Iterator<int> iterator() {
|
||||
Iterator<int> get iterator {
|
||||
return new _ByteArrayIterator<int>(this);
|
||||
}
|
||||
|
||||
@@ -2518,7 +2568,7 @@ class _Float32ArrayView extends _ByteArrayViewBase implements Float32List {
|
||||
_array.setFloat32(_offset + (index * _BYTES_PER_ELEMENT), value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
@@ -2590,7 +2640,7 @@ class _Float64ArrayView extends _ByteArrayViewBase implements Float64List {
|
||||
_array.setFloat64(_offset + (index * _BYTES_PER_ELEMENT), value);
|
||||
}
|
||||
|
||||
Iterator<double> iterator() {
|
||||
Iterator<double> get iterator {
|
||||
return new _ByteArrayIterator<double>(this);
|
||||
}
|
||||
|
||||
|
||||
+15
-2
@@ -79,7 +79,20 @@ DEFINE_NATIVE_ENTRY(Double_trunc_div, 2) {
|
||||
if (FLAG_trace_intrinsified_natives) {
|
||||
OS::Print("Double_trunc_div %f ~/ %f\n", left, right);
|
||||
}
|
||||
return Double::New(trunc(left / right));
|
||||
double result = trunc(left / right);
|
||||
if (isinf(result) || isnan(result)) {
|
||||
const Array& args = Array::Handle(Array::New(1));
|
||||
args.SetAt(0, String::Handle(String::New(
|
||||
"Result of truncating division is Infinity or NaN")));
|
||||
Exceptions::ThrowByType(Exceptions::kUnsupported, args);
|
||||
}
|
||||
if ((Smi::kMinValue <= result) && (result <= Smi::kMaxValue)) {
|
||||
return Smi::New(static_cast<intptr_t>(result));
|
||||
} else if ((Mint::kMinValue <= result) && (result <= Mint::kMaxValue)) {
|
||||
return Mint::New(static_cast<int64_t>(result));
|
||||
} else {
|
||||
return BigintOperations::NewFromDouble(result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -191,7 +204,7 @@ DEFINE_NATIVE_ENTRY(Double_toInt, 1) {
|
||||
if (isinf(arg.value()) || isnan(arg.value())) {
|
||||
const Array& args = Array::Handle(Array::New(1));
|
||||
args.SetAt(0, String::Handle(String::New("Infinity or NaN toInt")));
|
||||
Exceptions::ThrowByType(Exceptions::kFormat, args);
|
||||
Exceptions::ThrowByType(Exceptions::kUnsupported, args);
|
||||
}
|
||||
double result = trunc(arg.value());
|
||||
if ((Smi::kMinValue <= result) && (result <= Smi::kMaxValue)) {
|
||||
|
||||
+34
-21
@@ -6,11 +6,8 @@ class _Double implements double {
|
||||
factory _Double.fromInteger(int value)
|
||||
native "Double_doubleFromInteger";
|
||||
int get hashCode {
|
||||
try {
|
||||
return toInt();
|
||||
} on FormatException catch (e) {
|
||||
return 0;
|
||||
}
|
||||
if (isNaN || isInfinite) return 0;
|
||||
return toInt();
|
||||
}
|
||||
double operator +(num other) {
|
||||
return _add(other.toDouble());
|
||||
@@ -27,10 +24,10 @@ class _Double implements double {
|
||||
}
|
||||
double _mul(double other) native "Double_mul";
|
||||
|
||||
double operator ~/(num other) {
|
||||
int operator ~/(num other) {
|
||||
return _trunc_div(other.toDouble());
|
||||
}
|
||||
double _trunc_div(double other) native "Double_trunc_div";
|
||||
int _trunc_div(double other) native "Double_trunc_div";
|
||||
|
||||
double operator /(num other) {
|
||||
return _div(other.toDouble());
|
||||
@@ -81,7 +78,7 @@ class _Double implements double {
|
||||
double _mulFromInteger(int other) {
|
||||
return new _Double.fromInteger(other) * this;
|
||||
}
|
||||
double _truncDivFromInteger(int other) {
|
||||
int _truncDivFromInteger(int other) {
|
||||
return new _Double.fromInteger(other) ~/ this;
|
||||
}
|
||||
double _moduloFromInteger(int other) {
|
||||
@@ -107,6 +104,20 @@ class _Double implements double {
|
||||
double floor() native "Double_floor";
|
||||
double ceil () native "Double_ceil";
|
||||
double truncate() native "Double_truncate";
|
||||
|
||||
num clamp(num lowerLimit, num upperLimit) {
|
||||
if (lowerLimit is! num) throw new ArgumentError(lowerLimit);
|
||||
if (upperLimit is! num) throw new ArgumentError(upperLimit);
|
||||
|
||||
if (lowerLimit.compareTo(upperLimit) > 0) {
|
||||
throw new ArgumentError(lowerLimit);
|
||||
}
|
||||
if (lowerLimit.isNaN) return lowerLimit;
|
||||
if (this.compareTo(lowerLimit) < 0) return lowerLimit;
|
||||
if (this.compareTo(upperLimit) > 0) return upperLimit;
|
||||
return this;
|
||||
}
|
||||
|
||||
int toInt() native "Double_toInt";
|
||||
double toDouble() { return this; }
|
||||
|
||||
@@ -128,10 +139,12 @@ class _Double implements double {
|
||||
String toStringAsFixed(int fractionDigits) {
|
||||
// See ECMAScript-262, 15.7.4.5 for details.
|
||||
|
||||
if (fractionDigits is! int) {
|
||||
throw new ArgumentError(fractionDigits);
|
||||
}
|
||||
// Step 2.
|
||||
if (fractionDigits < 0 || fractionDigits > 20) {
|
||||
// TODO(antonm): should be proper RangeError or Dart counterpart.
|
||||
throw "Range error";
|
||||
throw new RangeError(fractionDigits);
|
||||
}
|
||||
|
||||
// Step 3.
|
||||
@@ -151,7 +164,7 @@ class _Double implements double {
|
||||
}
|
||||
String _toStringAsFixed(int fractionDigits) native "Double_toStringAsFixed";
|
||||
|
||||
String toStringAsExponential(int fractionDigits) {
|
||||
String toStringAsExponential([int fractionDigits]) {
|
||||
// See ECMAScript-262, 15.7.4.6 for details.
|
||||
|
||||
// The EcmaScript specification checks for NaN and Infinity before looking
|
||||
@@ -159,10 +172,13 @@ class _Double implements double {
|
||||
// look at the fractionDigits first.
|
||||
|
||||
// Step 7.
|
||||
if (fractionDigits != null &&
|
||||
(fractionDigits < 0 || fractionDigits > 20)) {
|
||||
// TODO(antonm): should be proper RangeError or Dart counterpart.
|
||||
throw "Range error";
|
||||
if (fractionDigits != null) {
|
||||
if (fractionDigits is! int) {
|
||||
throw new ArgumentError(fractionDigits);
|
||||
}
|
||||
if (fractionDigits < 0 || fractionDigits > 20) {
|
||||
throw new RangeError(fractionDigits);
|
||||
}
|
||||
}
|
||||
|
||||
if (isNaN) return "NaN";
|
||||
@@ -185,10 +201,11 @@ class _Double implements double {
|
||||
// at the fractionDigits. In Dart we are consistent with toStringAsFixed and
|
||||
// look at the fractionDigits first.
|
||||
|
||||
if (precision is! int) throw new ArgumentError(precision);
|
||||
|
||||
// Step 8.
|
||||
if (precision < 1 || precision > 21) {
|
||||
// TODO(antonm): should be proper RangeError or Dart counterpart.
|
||||
throw "Range error";
|
||||
throw new RangeError(precision);
|
||||
}
|
||||
|
||||
if (isNaN) return "NaN";
|
||||
@@ -200,10 +217,6 @@ class _Double implements double {
|
||||
String _toStringAsPrecision(int fractionDigits)
|
||||
native "Double_toStringAsPrecision";
|
||||
|
||||
String toRadixString(int radix) {
|
||||
return toInt().toRadixString(radix);
|
||||
}
|
||||
|
||||
// Order is: NaN > Infinity > ... > 0.0 > -0.0 > ... > -Infinity.
|
||||
int compareTo(Comparable other) {
|
||||
final int EQUAL = 0, LESS = -1, GREATER = 1;
|
||||
|
||||
@@ -6,6 +6,15 @@
|
||||
// VM implementation of double.
|
||||
|
||||
patch class double {
|
||||
/* patch */
|
||||
static double parse(String string) native "Double_parse";
|
||||
static double _parse(String string) native "Double_parse";
|
||||
|
||||
/* patch */ static double parse(String str,
|
||||
[double handleError(String str)]) {
|
||||
if (handleError == null) return _parse(str);
|
||||
try {
|
||||
return _parse(str);
|
||||
} on FormatException {
|
||||
return handleError(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ patch class Expando<T> {
|
||||
}
|
||||
}
|
||||
if (doCompact) {
|
||||
_data = _data.filter((e) => (e != null));
|
||||
_data = _data.where((e) => (e != null)).toList();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ patch class Expando<T> {
|
||||
_data.add(new _WeakProperty(object, value));
|
||||
}
|
||||
if (doCompact) {
|
||||
_data = _data.filter((e) => (e != null));
|
||||
_data = _data.where((e) => (e != null)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ patch class Function {
|
||||
(positionalArguments != null ? positionalArguments.length : 0);
|
||||
int numNamedArguments = namedArguments != null ? namedArguments.length : 0;
|
||||
int numArguments = numPositionalArguments + numNamedArguments;
|
||||
List arguments = new List(numArguments);
|
||||
List arguments = new List.fixedLength(numArguments);
|
||||
arguments[0] = function;
|
||||
arguments.setRange(1, numPositionalArguments - 1, positionalArguments);
|
||||
List names = new List(numNamedArguments);
|
||||
List names = new List.fixedLength(numNamedArguments);
|
||||
int argumentIndex = numPositionalArguments;
|
||||
int nameIndex = 0;
|
||||
if (numNamedArguments > 0) {
|
||||
|
||||
@@ -131,8 +131,8 @@ class _GrowableObjectArray<T> implements List<T> {
|
||||
add(element);
|
||||
}
|
||||
|
||||
void addAll(Collection<T> collection) {
|
||||
for (T elem in collection) {
|
||||
void addAll(Iterable<T> iterable) {
|
||||
for (T elem in iterable) {
|
||||
add(elem);
|
||||
}
|
||||
}
|
||||
@@ -146,13 +146,25 @@ class _GrowableObjectArray<T> implements List<T> {
|
||||
}
|
||||
|
||||
T get first {
|
||||
return this[0];
|
||||
if (length > 0) return this[0];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
T get last {
|
||||
return this[length - 1];
|
||||
if (length > 0) return this[length - 1];
|
||||
throw new StateError("No elements");
|
||||
}
|
||||
|
||||
T get single {
|
||||
if (length == 1) return this[0];
|
||||
if (length == 0) throw new StateError("No elements");
|
||||
throw new StateError("More than one element");
|
||||
}
|
||||
|
||||
T min([int compare(T a, T b)]) => Collections.min(this, compare);
|
||||
|
||||
T max([int compare(T a, T b)]) => Collections.max(this, compare);
|
||||
|
||||
int indexOf(T element, [int start = 0]) {
|
||||
return Arrays.indexOf(this, element, start, length);
|
||||
}
|
||||
@@ -172,7 +184,9 @@ class _GrowableObjectArray<T> implements List<T> {
|
||||
|
||||
// Collection interface.
|
||||
|
||||
bool contains(T element) => Collections.contains(this, element);
|
||||
bool contains(T element) {
|
||||
return Collections.contains(this, element);
|
||||
}
|
||||
|
||||
void forEach(f(T element)) {
|
||||
// TODO(srdjan): Use Collections.forEach(this, f);
|
||||
@@ -182,25 +196,74 @@ class _GrowableObjectArray<T> implements List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
Collection map(f(T element)) {
|
||||
return Collections.map(this,
|
||||
new _GrowableObjectArray.withCapacity(length), f);
|
||||
String join([String separator]) {
|
||||
if (isEmpty) return "";
|
||||
if (this.length == 1) return "${this[0]}";
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
if (separator == null || separator == "") {
|
||||
for (int i = 0; i < this.length; i++) {
|
||||
buffer.add("${this[i]}");
|
||||
}
|
||||
} else {
|
||||
buffer.add("${this[0]}");
|
||||
for (int i = 1; i < this.length; i++) {
|
||||
buffer.add(separator);
|
||||
buffer.add("${this[i]}");
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
List mappedBy(f(T element)) {
|
||||
return new MappedList<T, dynamic>(this, f);
|
||||
}
|
||||
|
||||
reduce(initialValue, combine(previousValue, T element)) {
|
||||
return Collections.reduce(this, initialValue, combine);
|
||||
}
|
||||
|
||||
Collection<T> filter(bool f(T element)) {
|
||||
return Collections.filter(this, new _GrowableObjectArray<T>(), f);
|
||||
Iterable<T> where(bool f(T element)) {
|
||||
return new WhereIterable<T>(this, f);
|
||||
}
|
||||
|
||||
List<T> take(int n) {
|
||||
return new ListView<T>(this, 0, n);
|
||||
}
|
||||
|
||||
Iterable<T> takeWhile(bool test(T value)) {
|
||||
return new TakeWhileIterable<T>(this, test);
|
||||
}
|
||||
|
||||
List<T> skip(int n) {
|
||||
return new ListView<T>(this, n, null);
|
||||
}
|
||||
|
||||
Iterable<T> skipWhile(bool test(T value)) {
|
||||
return new SkipWhileIterable<T>(this, test);
|
||||
}
|
||||
|
||||
bool every(bool f(T element)) {
|
||||
return Collections.every(this, f);
|
||||
}
|
||||
|
||||
bool some(bool f(T element)) {
|
||||
return Collections.some(this, f);
|
||||
bool any(bool f(T element)) {
|
||||
return Collections.any(this, f);
|
||||
}
|
||||
|
||||
T firstMatching(bool test(T value), {T orElse()}) {
|
||||
return Collections.firstMatching(this, test, orElse);
|
||||
}
|
||||
|
||||
T lastMatching(bool test(T value), {T orElse()}) {
|
||||
return Collections.lastMatchingInList(this, test, orElse);
|
||||
}
|
||||
|
||||
T singleMatching(bool test(T value)) {
|
||||
return Collections.singleMatching(this, test);
|
||||
}
|
||||
|
||||
T elementAt(int index) {
|
||||
return this[index];
|
||||
}
|
||||
|
||||
bool get isEmpty {
|
||||
@@ -220,7 +283,15 @@ class _GrowableObjectArray<T> implements List<T> {
|
||||
return Collections.collectionToString(this);
|
||||
}
|
||||
|
||||
Iterator<T> iterator() {
|
||||
return new SequenceIterator<T>(this);
|
||||
Iterator<T> get iterator {
|
||||
return new ListIterator<T>(this);
|
||||
}
|
||||
|
||||
List<T> toList() {
|
||||
return new List<T>.from(this);
|
||||
}
|
||||
|
||||
Set<T> toSet() {
|
||||
return new Set<T>.from(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,22 +35,12 @@ class ImmutableMap<K, V> implements Map<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
Collection<K> get keys {
|
||||
int numKeys = length;
|
||||
List<K> list = new List<K>(numKeys);
|
||||
for (int i = 0; i < numKeys; i++) {
|
||||
list[i] = kvPairs_[i*2];
|
||||
}
|
||||
return list;
|
||||
Iterable<K> get keys {
|
||||
return new _ImmutableMapKeyIterable<K>(this);
|
||||
}
|
||||
|
||||
Collection<V> get values {
|
||||
int numValues = length;
|
||||
List<V> list = new List<V>(numValues);
|
||||
for (int i = 0; i < numValues; i++) {
|
||||
list[i] = kvPairs_[i*2 + 1];
|
||||
}
|
||||
return list;
|
||||
Iterable<V> get values {
|
||||
return new _ImmutableMapValueIterable<V>(this);
|
||||
}
|
||||
|
||||
bool containsKey(K key) {
|
||||
@@ -92,3 +82,64 @@ class ImmutableMap<K, V> implements Map<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
class _ImmutableMapKeyIterable<E> extends Iterable<E> {
|
||||
final ImmutableMap _map;
|
||||
_ImmutableMapKeyIterable(this._map);
|
||||
|
||||
Iterator<E> get iterator {
|
||||
return new _ImmutableMapKeyIterator<E>(_map);
|
||||
}
|
||||
}
|
||||
|
||||
class _ImmutableMapValueIterable<E> extends Iterable<E> {
|
||||
final ImmutableMap _map;
|
||||
_ImmutableMapValueIterable(this._map);
|
||||
|
||||
Iterator<E> get iterator {
|
||||
return new _ImmutableMapValueIterator<E>(_map);
|
||||
}
|
||||
}
|
||||
|
||||
class _ImmutableMapKeyIterator<E> implements Iterator<E> {
|
||||
ImmutableMap _map;
|
||||
int _index = -1;
|
||||
E _current;
|
||||
|
||||
_ImmutableMapKeyIterator(this._map);
|
||||
|
||||
bool moveNext() {
|
||||
int newIndex = _index + 1;
|
||||
if (newIndex < _map.length) {
|
||||
_index = newIndex;
|
||||
_current = _map.kvPairs_[newIndex * 2];
|
||||
return true;
|
||||
}
|
||||
_current = null;
|
||||
_index = _map.length;
|
||||
return false;
|
||||
}
|
||||
|
||||
E get current => _current;
|
||||
}
|
||||
|
||||
class _ImmutableMapValueIterator<E> implements Iterator<E> {
|
||||
ImmutableMap _map;
|
||||
int _index = -1;
|
||||
E _current;
|
||||
|
||||
_ImmutableMapValueIterator(this._map);
|
||||
|
||||
bool moveNext() {
|
||||
int newIndex = _index + 1;
|
||||
if (newIndex < _map.length) {
|
||||
_index = newIndex;
|
||||
_current = _map.kvPairs_[newIndex * 2 + 1];
|
||||
return true;
|
||||
}
|
||||
_current = null;
|
||||
_index = _map.length;
|
||||
return false;
|
||||
}
|
||||
|
||||
E get current => _current;
|
||||
}
|
||||
|
||||
@@ -131,6 +131,30 @@ class _IntegerImplementation {
|
||||
int ceil() { return this; }
|
||||
int truncate() { return this; }
|
||||
|
||||
num clamp(num lowerLimit, num upperLimit) {
|
||||
if (lowerLimit is! num) throw new ArgumentError(lowerLimit);
|
||||
if (upperLimit is! num) throw new ArgumentError(upperLimit);
|
||||
|
||||
// Special case for integers.
|
||||
if (lowerLimit is int && upperLimit is int) {
|
||||
if (lowerLimit > upperLimit) {
|
||||
throw new ArgumentError(lowerLimit);
|
||||
}
|
||||
if (this < lowerLimit) return lowerLimit;
|
||||
if (this > upperLimit) return upperLimit;
|
||||
return this;
|
||||
}
|
||||
// Generic case involving doubles.
|
||||
if (lowerLimit.compareTo(upperLimit) > 0) {
|
||||
throw new ArgumentError(lowerLimit);
|
||||
}
|
||||
if (lowerLimit.isNaN) return lowerLimit;
|
||||
// Note that we don't need to care for -0.0 for the lower limit.
|
||||
if (this < lowerLimit) return lowerLimit;
|
||||
if (this.compareTo(upperLimit) > 0) return upperLimit;
|
||||
return this;
|
||||
}
|
||||
|
||||
int toInt() { return this; }
|
||||
double toDouble() { return new _Double.fromInteger(this); }
|
||||
|
||||
@@ -146,25 +170,26 @@ class _IntegerImplementation {
|
||||
String toStringAsFixed(int fractionDigits) {
|
||||
return this.toDouble().toStringAsFixed(fractionDigits);
|
||||
}
|
||||
String toStringAsExponential(int fractionDigits) {
|
||||
String toStringAsExponential([int fractionDigits]) {
|
||||
return this.toDouble().toStringAsExponential(fractionDigits);
|
||||
}
|
||||
String toStringAsPrecision(int precision) {
|
||||
return this.toDouble().toStringAsPrecision(precision);
|
||||
}
|
||||
|
||||
String toRadixString(int radix) {
|
||||
final table = const ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
|
||||
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
|
||||
"u", "v", "w", "x", "y", "z"];
|
||||
if (radix < 2 || radix > 36) {
|
||||
if (radix is! int || radix < 2 || radix > 36) {
|
||||
throw new ArgumentError(radix);
|
||||
}
|
||||
final bool isNegative = this < 0;
|
||||
var value = isNegative ? -this : this;
|
||||
int value = isNegative ? -this : this;
|
||||
List temp = new List();
|
||||
while (value > 0) {
|
||||
var digit = value % radix;
|
||||
int digit = value % radix;
|
||||
value ~/= radix;
|
||||
temp.add(digit);
|
||||
}
|
||||
|
||||
@@ -6,5 +6,66 @@
|
||||
// VM implementation of int.
|
||||
|
||||
patch class int {
|
||||
/* patch */ static int parse(String str) native "Integer_parse";
|
||||
static int _parse(String str) native "Integer_parse";
|
||||
|
||||
static void _throwFormatException(String source) {
|
||||
throw new FormatException(source);
|
||||
}
|
||||
|
||||
/* patch */ static int parse(String source,
|
||||
{ int radix,
|
||||
int onError(String str) }) {
|
||||
if (source is! String) throw new ArgumentError(source);
|
||||
if (radix == null) {
|
||||
if (onError == null) return _parse(source);
|
||||
try {
|
||||
return _parse(source);
|
||||
} on FormatException {
|
||||
return onError(source);
|
||||
}
|
||||
}
|
||||
if (radix is! int) throw new ArgumentError("Radix is not an integer");
|
||||
if (radix < 2 || radix > 36) {
|
||||
throw new RangeError("Radix $radix not in range 2..36");
|
||||
}
|
||||
if (onError == null) {
|
||||
onError = _throwFormatException;
|
||||
}
|
||||
// Remove leading and trailing white space.
|
||||
source = source.trim();
|
||||
if (source.isEmpty) return onError(source);
|
||||
|
||||
bool negative = false;
|
||||
int result = 0;
|
||||
|
||||
// The value 99 is used to represent a non-digit. It is too large to be
|
||||
// a digit value in any of the used bases.
|
||||
const NA = 99;
|
||||
const List<int> digits = const <int>[
|
||||
00, 01, 02, 03, 04, 05, 06, 07, 08, 09, NA, NA, NA, NA, NA, NA, // 0x30
|
||||
NA, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40
|
||||
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, NA, NA, NA, NA, NA, // 0x50
|
||||
NA, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x60
|
||||
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, NA, NA, NA, NA, NA, // 0x70
|
||||
];
|
||||
|
||||
int i = 0;
|
||||
int code = source.charCodeAt(i);
|
||||
if (code == 0x2d || code == 0x2b) { // Starts with a plus or minus-sign.
|
||||
negative = (code == 0x2d);
|
||||
if (source.length == 1) return onError(source);
|
||||
i = 1;
|
||||
code = source.charCodeAt(i);
|
||||
}
|
||||
do {
|
||||
if (code < 0x30 || code > 0x7f) return onError(source);
|
||||
int digit = digits[code - 0x30];
|
||||
if (digit >= radix) return onError(source);
|
||||
result = result * radix + digit;
|
||||
i++;
|
||||
if (i == source.length) break;
|
||||
code = source.charCodeAt(i);
|
||||
} while (true);
|
||||
return negative ? -result : result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ class _SendPortImpl implements SendPort {
|
||||
port.receive((value, ignoreReplyTo) {
|
||||
port.close();
|
||||
if (value is Exception) {
|
||||
completer.completeException(value);
|
||||
completer.completeError(value);
|
||||
} else {
|
||||
completer.complete(value);
|
||||
}
|
||||
@@ -122,50 +122,17 @@ _getPortInternal() native "isolate_getPortInternal";
|
||||
|
||||
ReceivePort _portInternal;
|
||||
|
||||
patch ReceivePort get port {
|
||||
if (_portInternal == null) {
|
||||
_portInternal = _getPortInternal();
|
||||
}
|
||||
return _portInternal;
|
||||
}
|
||||
|
||||
patch spawnFunction(void topLevelFunction(),
|
||||
[bool UnhandledExceptionCallback(IsolateUnhandledException e)])
|
||||
native "isolate_spawnFunction";
|
||||
|
||||
patch spawnUri(String uri) native "isolate_spawnUri";
|
||||
|
||||
patch class Timer {
|
||||
/* patch */ factory Timer(int milliseconds, void callback(Timer timer)) {
|
||||
if (_TimerFactory._factory == null) {
|
||||
throw new UnsupportedError("Timer interface not supported.");
|
||||
patch class _Isolate {
|
||||
/* patch */ static ReceivePort get port {
|
||||
if (_portInternal == null) {
|
||||
_portInternal = _getPortInternal();
|
||||
}
|
||||
return _TimerFactory._factory(milliseconds, callback, false);
|
||||
return _portInternal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new repeating timer. The [callback] is invoked every
|
||||
* [milliseconds] millisecond until cancelled.
|
||||
*/
|
||||
/* patch */ factory Timer.repeating(int milliseconds,
|
||||
void callback(Timer timer)) {
|
||||
if (_TimerFactory._factory == null) {
|
||||
throw new UnsupportedError("Timer interface not supported.");
|
||||
}
|
||||
return _TimerFactory._factory(milliseconds, callback, true);
|
||||
}
|
||||
}
|
||||
/* patch */ static spawnFunction(void topLevelFunction(),
|
||||
[bool UnhandledExceptionCallback(IsolateUnhandledException e)])
|
||||
native "isolate_spawnFunction";
|
||||
|
||||
typedef Timer _TimerFactoryClosure(int milliseconds,
|
||||
void callback(Timer timer),
|
||||
bool repeating);
|
||||
|
||||
class _TimerFactory {
|
||||
static _TimerFactoryClosure _factory;
|
||||
}
|
||||
|
||||
// TODO(ahe): Warning: this is NOT called by Dartium. Instead, it sets
|
||||
// [_TimerFactory._factory] directly.
|
||||
void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
|
||||
_TimerFactory._factory = closure;
|
||||
/* patch */ static spawnUri(String uri) native "isolate_spawnUri";
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ patch class Random {
|
||||
|
||||
class _Random implements Random {
|
||||
// Internal state of the random number generator.
|
||||
final _state = new List(2);
|
||||
final _state = new List.fixedLength(2);
|
||||
static const kSTATE_LO = 0;
|
||||
static const kSTATE_HI = 1;
|
||||
|
||||
|
||||
@@ -156,8 +156,8 @@ abstract class _LocalObjectMirrorImpl extends _LocalVMObjectMirrorImpl
|
||||
try {
|
||||
completer.complete(
|
||||
_invoke(this, memberName, positionalArguments));
|
||||
} catch (exception) {
|
||||
completer.completeException(exception);
|
||||
} catch (exception, s) {
|
||||
completer.completeError(exception, s);
|
||||
}
|
||||
return completer.future;
|
||||
}
|
||||
@@ -167,8 +167,8 @@ abstract class _LocalObjectMirrorImpl extends _LocalVMObjectMirrorImpl
|
||||
Completer<InstanceMirror> completer = new Completer<InstanceMirror>();
|
||||
try {
|
||||
completer.complete(_getField(this, fieldName));
|
||||
} catch (exception) {
|
||||
completer.completeException(exception);
|
||||
} catch (exception, s) {
|
||||
completer.completeError(exception, s);
|
||||
}
|
||||
return completer.future;
|
||||
}
|
||||
@@ -180,8 +180,8 @@ abstract class _LocalObjectMirrorImpl extends _LocalVMObjectMirrorImpl
|
||||
Completer<InstanceMirror> completer = new Completer<InstanceMirror>();
|
||||
try {
|
||||
completer.complete(_setField(this, fieldName, arg));
|
||||
} catch (exception) {
|
||||
completer.completeException(exception);
|
||||
} catch (exception, s) {
|
||||
completer.completeError(exception, s);
|
||||
}
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_factory, 4) {
|
||||
GET_NON_NULL_NATIVE_ARGUMENT(
|
||||
Instance, handle_multi_line, arguments->NativeArgAt(2));
|
||||
GET_NON_NULL_NATIVE_ARGUMENT(
|
||||
Instance, handle_ignore_case, arguments->NativeArgAt(3));
|
||||
bool ignore_case = handle_ignore_case.raw() == Bool::True().raw();
|
||||
Instance, handle_case_sensitive, arguments->NativeArgAt(3));
|
||||
bool ignore_case = handle_case_sensitive.raw() != Bool::True().raw();
|
||||
bool multi_line = handle_multi_line.raw() == Bool::True().raw();
|
||||
return Jscre::Compile(pattern, multi_line, ignore_case);
|
||||
}
|
||||
@@ -33,17 +33,17 @@ DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_getPattern, 1) {
|
||||
}
|
||||
|
||||
|
||||
DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_multiLine, 1) {
|
||||
DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_getIsMultiLine, 1) {
|
||||
const JSRegExp& regexp = JSRegExp::CheckedHandle(arguments->NativeArgAt(0));
|
||||
ASSERT(!regexp.IsNull());
|
||||
return Bool::Get(regexp.is_multi_line());
|
||||
}
|
||||
|
||||
|
||||
DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_ignoreCase, 1) {
|
||||
DEFINE_NATIVE_ENTRY(JSSyntaxRegExp_getIsCaseSensitive, 1) {
|
||||
const JSRegExp& regexp = JSRegExp::CheckedHandle(arguments->NativeArgAt(0));
|
||||
ASSERT(!regexp.IsNull());
|
||||
return Bool::Get(regexp.is_ignore_case());
|
||||
return Bool::Get(!regexp.is_ignore_case());
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
patch class RegExp {
|
||||
/* patch */ factory RegExp(String pattern,
|
||||
{bool multiLine: false,
|
||||
bool ignoreCase: false}) {
|
||||
bool caseSensitive: true}) {
|
||||
return new _JSSyntaxRegExp(pattern,
|
||||
multiLine: multiLine,
|
||||
ignoreCase: ignoreCase);
|
||||
caseSensitive: caseSensitive);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ class _JSRegExpMatch implements Match {
|
||||
}
|
||||
|
||||
List<String> groups(List<int> groupsSpec) {
|
||||
var groupsList = new List<String>(groupsSpec.length);
|
||||
var groupsList = new List<String>.fixedLength(groupsSpec.length);
|
||||
for (int i = 0; i < groupsSpec.length; i++) {
|
||||
groupsList[i] = group(groupsSpec[i]);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class _JSSyntaxRegExp implements RegExp {
|
||||
factory _JSSyntaxRegExp(
|
||||
String pattern,
|
||||
{bool multiLine: false,
|
||||
bool ignoreCase: false}) native "JSSyntaxRegExp_factory";
|
||||
bool caseSensitive: true}) native "JSSyntaxRegExp_factory";
|
||||
|
||||
Match firstMatch(String str) {
|
||||
List match = _ExecuteMatch(str, 0);
|
||||
@@ -114,9 +114,9 @@ class _JSSyntaxRegExp implements RegExp {
|
||||
|
||||
String get pattern native "JSSyntaxRegExp_getPattern";
|
||||
|
||||
bool get multiLine native "JSSyntaxRegExp_multiLine";
|
||||
bool get isMultiLine native "JSSyntaxRegExp_getIsMultiLine";
|
||||
|
||||
bool get ignoreCase native "JSSyntaxRegExp_ignoreCase";
|
||||
bool get isCaseSensitive native "JSSyntaxRegExp_getIsCaseSensitive";
|
||||
|
||||
int get _groupCount native "JSSyntaxRegExp_getGroupCount";
|
||||
|
||||
|
||||
+131
-29
@@ -155,6 +155,41 @@ class _StringBase {
|
||||
return _substringUnchecked(startIndex, endIndex);
|
||||
}
|
||||
|
||||
String slice([int startIndex, int endIndex]) {
|
||||
int start, end;
|
||||
if (startIndex == null) {
|
||||
start = 0;
|
||||
} else if (startIndex is! int) {
|
||||
throw new ArgumentError("startIndex is not int");
|
||||
} else if (startIndex >= 0) {
|
||||
start = startIndex;
|
||||
} else {
|
||||
start = this.length + startIndex;
|
||||
}
|
||||
if (start < 0 || start > this.length) {
|
||||
throw new RangeError(
|
||||
"startIndex out of range: $startIndex (length: $length)");
|
||||
}
|
||||
if (endIndex == null) {
|
||||
end = this.length;
|
||||
} else if (endIndex is! int) {
|
||||
throw new ArgumentError("endIndex is not int");
|
||||
} else if (endIndex >= 0) {
|
||||
end = endIndex;
|
||||
} else {
|
||||
end = this.length + endIndex;
|
||||
}
|
||||
if (end < 0 || end > this.length) {
|
||||
throw new RangeError(
|
||||
"endIndex out of range: $endIndex (length: $length)");
|
||||
}
|
||||
if (end < start) {
|
||||
throw new ArgumentError(
|
||||
"End before start: $endIndex < $startIndex (length: $length)");
|
||||
}
|
||||
return _substringUnchecked(start, end);
|
||||
}
|
||||
|
||||
String _substringUnchecked(int startIndex, int endIndex) {
|
||||
assert(endIndex != null);
|
||||
assert((startIndex >= 0) && (startIndex <= this.length));
|
||||
@@ -204,7 +239,7 @@ class _StringBase {
|
||||
if (pattern is String) {
|
||||
return indexOf(pattern, startIndex) >= 0;
|
||||
}
|
||||
return pattern.allMatches(this.substring(startIndex)).iterator().hasNext;
|
||||
return pattern.allMatches(this.substring(startIndex)).iterator.moveNext();
|
||||
}
|
||||
|
||||
String replaceFirst(Pattern pattern, String replacement) {
|
||||
@@ -216,9 +251,9 @@ class _StringBase {
|
||||
}
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
int startIndex = 0;
|
||||
Iterator iterator = pattern.allMatches(this).iterator();
|
||||
if (iterator.hasNext) {
|
||||
Match match = iterator.next();
|
||||
Iterator iterator = pattern.allMatches(this).iterator;
|
||||
if (iterator.moveNext()) {
|
||||
Match match = iterator.current;
|
||||
buffer..add(this.substring(startIndex, match.start))
|
||||
..add(replacement);
|
||||
startIndex = match.end;
|
||||
@@ -231,7 +266,8 @@ class _StringBase {
|
||||
throw new ArgumentError("${pattern} is not a Pattern");
|
||||
}
|
||||
if (replacement is! String) {
|
||||
throw new ArgumentError("${replacement} is not a String");
|
||||
throw new ArgumentError(
|
||||
"${replacement} is not a String or Match->String function");
|
||||
}
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
int startIndex = 0;
|
||||
@@ -243,13 +279,75 @@ class _StringBase {
|
||||
return (buffer..add(this.substring(startIndex))).toString();
|
||||
}
|
||||
|
||||
String replaceAllMapped(Pattern pattern, String replace(Match match)) {
|
||||
return splitMapJoin(pattern, onMatch: replace);
|
||||
}
|
||||
|
||||
static String _matchString(Match match) => match[0];
|
||||
static String _stringIdentity(String string) => string;
|
||||
|
||||
String _splitMapJoinEmptyString(String onMatch(Match match),
|
||||
String onNonMatch(String nonMatch)) {
|
||||
// Pattern is the empty string.
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
int length = this.length;
|
||||
int i = 0;
|
||||
buffer.add(onNonMatch(""));
|
||||
while (i < length) {
|
||||
buffer.add(onMatch(new _StringMatch(i, this, "")));
|
||||
// Special case to avoid splitting a surrogate pair.
|
||||
int code = this.charCodeAt(i);
|
||||
if ((code & ~0x3FF) == 0xD800 && length > i + 1) {
|
||||
// Leading surrogate;
|
||||
code = this.charCodeAt(i + 1);
|
||||
if ((code & ~0x3FF) == 0xDC00) {
|
||||
// Matching trailing surrogate.
|
||||
buffer.add(onNonMatch(this.substring(i, i + 2)));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
buffer.add(onNonMatch(this[i]));
|
||||
i++;
|
||||
}
|
||||
buffer.add(onMatch(new _StringMatch(i, this, "")));
|
||||
buffer.add(onNonMatch(""));
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
String splitMapJoin(Pattern pattern,
|
||||
{String onMatch(Match match),
|
||||
String onNonMatch(String nonMatch)}) {
|
||||
if (pattern is! Pattern) {
|
||||
throw new ArgumentError("${pattern} is not a Pattern");
|
||||
}
|
||||
if (onMatch == null) onMatch = _matchString;
|
||||
if (onNonMatch == null) onNonMatch = _stringIdentity;
|
||||
if (pattern is String) {
|
||||
String stringPattern = pattern;
|
||||
if (stringPattern.isEmpty) {
|
||||
return _splitMapJoinEmptyString(onMatch, onNonMatch);
|
||||
}
|
||||
}
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
int startIndex = 0;
|
||||
for (Match match in pattern.allMatches(this)) {
|
||||
buffer.add(onNonMatch(this.substring(startIndex, match.start)));
|
||||
buffer.add(onMatch(match).toString());
|
||||
startIndex = match.end;
|
||||
}
|
||||
buffer.add(onNonMatch(this.substring(startIndex)));
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert all objects in [values] to strings and concat them
|
||||
* into a result string.
|
||||
*/
|
||||
static String _interpolate(List values) {
|
||||
int numValues = values.length;
|
||||
var stringList = new List(numValues);
|
||||
var stringList = new List.fixedLength(numValues);
|
||||
for (int i = 0; i < numValues; i++) {
|
||||
stringList[i] = values[i].toString();
|
||||
}
|
||||
@@ -284,8 +382,8 @@ class _StringBase {
|
||||
return splitChars();
|
||||
}
|
||||
int length = this.length;
|
||||
Iterator iterator = pattern.allMatches(this).iterator();
|
||||
if (length == 0 && iterator.hasNext) {
|
||||
Iterator iterator = pattern.allMatches(this).iterator;
|
||||
if (length == 0 && iterator.moveNext()) {
|
||||
// A matched empty string input returns the empty list.
|
||||
return <String>[];
|
||||
}
|
||||
@@ -293,11 +391,11 @@ class _StringBase {
|
||||
int startIndex = 0;
|
||||
int previousIndex = 0;
|
||||
while (true) {
|
||||
if (startIndex == length || !iterator.hasNext) {
|
||||
if (startIndex == length || !iterator.moveNext()) {
|
||||
result.add(this._substringUnchecked(previousIndex, length));
|
||||
break;
|
||||
}
|
||||
Match match = iterator.next();
|
||||
Match match = iterator.current;
|
||||
if (match.start == length) {
|
||||
result.add(this._substringUnchecked(previousIndex, length));
|
||||
break;
|
||||
@@ -315,7 +413,7 @@ class _StringBase {
|
||||
|
||||
List<String> splitChars() {
|
||||
int len = this.length;
|
||||
final result = new List<String>(len);
|
||||
final result = new List<String>.fixedLength(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
result[i] = this[i];
|
||||
}
|
||||
@@ -324,7 +422,7 @@ class _StringBase {
|
||||
|
||||
List<int> get charCodes {
|
||||
int len = this.length;
|
||||
final result = new List<int>(len);
|
||||
final result = new List<int>.fixedLength(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
result[i] = this.charCodeAt(i);
|
||||
}
|
||||
@@ -336,34 +434,38 @@ class _StringBase {
|
||||
String toLowerCase() native "String_toLowerCase";
|
||||
|
||||
// Implementations of Strings methods follow below.
|
||||
static String join(List<String> strings, String separator) {
|
||||
final int length = strings.length;
|
||||
if (length == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
List stringsList = strings;
|
||||
if (separator.length != 0) {
|
||||
stringsList = new List(2 * length - 1);
|
||||
stringsList[0] = strings[0];
|
||||
int j = 1;
|
||||
for (int i = 1; i < length; i++) {
|
||||
stringsList[j++] = separator;
|
||||
stringsList[j++] = strings[i];
|
||||
static String join(Iterable<String> strings, String separator) {
|
||||
bool first = true;
|
||||
List<String> stringsList = <String>[];
|
||||
for (String string in strings) {
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
stringsList.add(separator);
|
||||
}
|
||||
|
||||
if (string is! String) {
|
||||
throw new ArgumentError(Error.safeToString(string));
|
||||
}
|
||||
stringsList.add(string);
|
||||
}
|
||||
return concatAll(stringsList);
|
||||
}
|
||||
|
||||
static String concatAll(List<String> strings) {
|
||||
static String concatAll(Iterable<String> strings) {
|
||||
_ObjectArray stringsArray;
|
||||
if (strings is _ObjectArray) {
|
||||
stringsArray = strings;
|
||||
for (int i = 0; i < strings.length; i++) {
|
||||
if (strings[i] is! String) throw new ArgumentError(strings[i]);
|
||||
}
|
||||
} else {
|
||||
int len = strings.length;
|
||||
stringsArray = new _ObjectArray(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
stringsArray[i] = strings[i];
|
||||
int i = 0;
|
||||
for (String string in strings) {
|
||||
if (string is! String) throw new ArgumentError(string);
|
||||
stringsArray[i++] = string;
|
||||
}
|
||||
}
|
||||
return _concatAll(stringsArray);
|
||||
|
||||
@@ -9,7 +9,7 @@ patch class String {
|
||||
}
|
||||
|
||||
patch class Strings {
|
||||
/* patch */ static String join(List<String> strings, String separator) {
|
||||
/* patch */ static String join(Iterable<String> strings, String separator) {
|
||||
return _StringBase.join(strings, separator);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
|
||||
// for details. All rights reserved. Use of this source code is governed by a
|
||||
// BSD-style license that can be found in the LICENSE file.
|
||||
|
||||
patch class Timer {
|
||||
/* patch */ factory Timer(int milliseconds, void callback(Timer timer)) {
|
||||
if (_TimerFactory._factory == null) {
|
||||
throw new UnsupportedError("Timer interface not supported.");
|
||||
}
|
||||
return _TimerFactory._factory(milliseconds, callback, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new repeating timer. The [callback] is invoked every
|
||||
* [milliseconds] millisecond until cancelled.
|
||||
*/
|
||||
/* patch */ factory Timer.repeating(int milliseconds,
|
||||
void callback(Timer timer)) {
|
||||
if (_TimerFactory._factory == null) {
|
||||
throw new UnsupportedError("Timer interface not supported.");
|
||||
}
|
||||
return _TimerFactory._factory(milliseconds, callback, true);
|
||||
}
|
||||
}
|
||||
|
||||
typedef Timer _TimerFactoryClosure(int milliseconds,
|
||||
void callback(Timer timer),
|
||||
bool repeating);
|
||||
|
||||
class _TimerFactory {
|
||||
static _TimerFactoryClosure _factory;
|
||||
}
|
||||
|
||||
// TODO(ahe): Warning: this is NOT called by Dartium. Instead, it sets
|
||||
// [_TimerFactory._factory] directly.
|
||||
void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
|
||||
_TimerFactory._factory = closure;
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
library isolate_mirror_local_test;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:isolate';
|
||||
import 'dart:mirrors';
|
||||
|
||||
@@ -125,7 +126,7 @@ void testRootLibraryMirror(LibraryMirror lib_mirror) {
|
||||
});
|
||||
|
||||
// Check that the members map is complete.
|
||||
List keys = lib_mirror.members.keys;
|
||||
List keys = lib_mirror.members.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('['
|
||||
'FuncType, '
|
||||
@@ -162,7 +163,7 @@ void testRootLibraryMirror(LibraryMirror lib_mirror) {
|
||||
'$keys');
|
||||
|
||||
// Check that the classes map is complete.
|
||||
keys = lib_mirror.classes.keys;
|
||||
keys = lib_mirror.classes.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('['
|
||||
'FuncType, '
|
||||
@@ -174,7 +175,7 @@ void testRootLibraryMirror(LibraryMirror lib_mirror) {
|
||||
'$keys');
|
||||
|
||||
// Check that the functions map is complete.
|
||||
keys = lib_mirror.functions.keys;
|
||||
keys = lib_mirror.functions.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('['
|
||||
'_stringCompare, '
|
||||
@@ -200,17 +201,17 @@ void testRootLibraryMirror(LibraryMirror lib_mirror) {
|
||||
'$keys');
|
||||
|
||||
// Check that the getters map is complete.
|
||||
keys = lib_mirror.getters.keys;
|
||||
keys = lib_mirror.getters.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('[myVar]', '$keys');
|
||||
|
||||
// Check that the setters map is complete.
|
||||
keys = lib_mirror.setters.keys;
|
||||
keys = lib_mirror.setters.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('[myVar=]', '$keys');
|
||||
|
||||
// Check that the variables map is complete.
|
||||
keys = lib_mirror.variables.keys;
|
||||
keys = lib_mirror.variables.keys.toList();
|
||||
sort(keys);
|
||||
Expect.equals('['
|
||||
'exit_port, '
|
||||
@@ -458,59 +459,47 @@ void methodWithError() {
|
||||
void testMirrorErrors(MirrorSystem mirrors) {
|
||||
LibraryMirror lib_mirror = mirrors.isolate.rootLibrary;
|
||||
|
||||
Future<InstanceMirror> future =
|
||||
lib_mirror.invoke('methodWithException', []);
|
||||
future.handleException(
|
||||
(MirroredError exc) {
|
||||
Expect.isTrue(exc is MirroredUncaughtExceptionError);
|
||||
lib_mirror.invoke('methodWithException', [])
|
||||
.then((InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
})
|
||||
.catchError((exc) {
|
||||
Expect.isTrue(exc.error is MirroredUncaughtExceptionError);
|
||||
Expect.equals('MyException',
|
||||
exc.exception_mirror.type.simpleName);
|
||||
exc.error.exception_mirror.type.simpleName);
|
||||
Expect.equals('MyException: from methodWithException',
|
||||
exc.exception_string);
|
||||
Expect.isTrue(exc.stacktrace.toString().contains(
|
||||
exc.error.exception_string);
|
||||
Expect.isTrue(exc.error.stacktrace.toString().contains(
|
||||
'isolate_mirror_local_test.dart'));
|
||||
testDone('testMirrorErrors1');
|
||||
return true;
|
||||
});
|
||||
future.then(
|
||||
(InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
});
|
||||
|
||||
Future<InstanceMirror> future2 =
|
||||
lib_mirror.invoke('methodWithError', []);
|
||||
future2.handleException(
|
||||
(MirroredError exc) {
|
||||
Expect.isTrue(exc is MirroredCompilationError);
|
||||
Expect.isTrue(exc.message.contains('unexpected token'));
|
||||
testDone('testMirrorErrors2');
|
||||
return true;
|
||||
});
|
||||
future2.then(
|
||||
(InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
});
|
||||
lib_mirror.invoke('methodWithError', [])
|
||||
.then((InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
})
|
||||
.catchError((exc) {
|
||||
Expect.isTrue(exc.error is MirroredCompilationError);
|
||||
Expect.isTrue(exc.error.message.contains('unexpected token'));
|
||||
testDone('testMirrorErrors2');
|
||||
});
|
||||
|
||||
// TODO(turnidge): When we call a method that doesn't exist, we
|
||||
// should probably call noSuchMethod(). I'm adding this test to
|
||||
// document the current behavior in the meantime.
|
||||
Future<InstanceMirror> future3 =
|
||||
lib_mirror.invoke('methodNotFound', []);
|
||||
future3.handleException(
|
||||
(MirroredError exc) {
|
||||
Expect.isTrue(exc is MirroredCompilationError);
|
||||
Expect.isTrue(exc.message.contains(
|
||||
"did not find top-level function 'methodNotFound'"));
|
||||
testDone('testMirrorErrors3');
|
||||
return true;
|
||||
});
|
||||
future3.then(
|
||||
(InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
});
|
||||
lib_mirror.invoke('methodNotFound', [])
|
||||
.then((InstanceMirror retval) {
|
||||
// Should not reach here.
|
||||
Expect.isTrue(false);
|
||||
})
|
||||
.catchError((exc) {
|
||||
Expect.isTrue(exc.error is MirroredCompilationError);
|
||||
Expect.isTrue(exc.error.message.contains(
|
||||
"did not find top-level function 'methodNotFound'"));
|
||||
testDone('testMirrorErrors3');
|
||||
});
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
@@ -35,14 +35,15 @@ void main() {
|
||||
|
||||
// Send a message that will cause an ignorable exception to be thrown.
|
||||
Future f = isolate_port.call('throw exception');
|
||||
f.onComplete((future) {
|
||||
f.catchError((error) {
|
||||
// Exception wasn't ignored as it was supposed to be.
|
||||
Expect.equals(null, future.exception);
|
||||
Expect.fail("Error not expected");
|
||||
});
|
||||
|
||||
// Verify that isolate can still handle messages.
|
||||
isolate_port.call('hi').onComplete((future) {
|
||||
Expect.equals(null, future.exception);
|
||||
Expect.equals('hello', future.value);
|
||||
isolate_port.call('hi').then((value) {
|
||||
Expect.equals('hello', value);
|
||||
}, onError: (error) {
|
||||
Expect.fail("Error not expected");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,14 +18,15 @@ void main() {
|
||||
|
||||
// Send a message that will cause an ignorable exception to be thrown.
|
||||
Future f = isolate_port.call('throw exception');
|
||||
f.onComplete((future) {
|
||||
Expect.equals(null, future.exception);
|
||||
f.catchError((error) {
|
||||
Expect.fail("Error not expected");
|
||||
});
|
||||
|
||||
// Verify that isolate can still handle messages.
|
||||
isolate_port.call('hi').onComplete((future) {
|
||||
Expect.equals(null, future.exception);
|
||||
Expect.equals('hello', future.value);
|
||||
isolate_port.call('hi').then((value) {
|
||||
Expect.equals('hello', value);
|
||||
}, onError: (error) {
|
||||
Expect.fail("Error not expected");
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@@ -42,3 +42,9 @@ dart/*: Skip
|
||||
|
||||
[ $arch == simarm ]
|
||||
dart/*: Skip
|
||||
|
||||
# TODO(ajohnsen): Fix this as part of library changes.
|
||||
[ $compiler == none ]
|
||||
cc/CustomIsolates: Skip # Bug 6890
|
||||
cc/NewNativePort: Skip # Bug 6890
|
||||
cc/RunLoop_ExceptionParent: Skip # Bug 6890
|
||||
|
||||
@@ -26,6 +26,13 @@ RawScript* Bootstrap::LoadScript(const char* url,
|
||||
}
|
||||
|
||||
|
||||
RawScript* Bootstrap::LoadASyncScript(bool patch) {
|
||||
const char* url = patch ? "dart:async-patch" : "dart:async";
|
||||
const char* source = patch ? async_patch_ : async_source_;
|
||||
return LoadScript(url, source, patch);
|
||||
}
|
||||
|
||||
|
||||
RawScript* Bootstrap::LoadCoreScript(bool patch) {
|
||||
// TODO(iposva): Use proper library name.
|
||||
const char* url = patch ? "dart:core-patch" : "bootstrap";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user