// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:isolate';

import 'package:stack_trace/stack_trace.dart';

/// Capture any top-level errors (mostly lazy syntax errors, since other are
/// caught below) and report them to the parent isolate.
void catchIsolateErrors() {
  var errorPort = new ReceivePort();
  // Aet errors non-fatal because otherwise they'll be double-printed.
  Isolate.current.setErrorsFatal(false);
  Isolate.current.addErrorListener(errorPort.sendPort);
  errorPort.listen((message) {
    // Masquerade as an IsoalteSpawnException because that's what this would
    // be if the error had been detected statically.
    var error = new IsolateSpawnException(message[0]);
    var stackTrace =
        message[1] == null ? new Trace([]) : new Trace.parse(message[1]);
    Zone.current.handleUncaughtError(error, stackTrace);
  });
}

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:isolate';

import 'package:stack_trace/stack_trace.dart';

/// Capture any top-level errors (mostly lazy syntax errors, since other are
/// caught below) and report them to the parent isolate.
void catchIsolateErrors() {
  var errorPort = new ReceivePort();
  // Treat errors non-fatal because otherwise they'll be double-printed.
  Isolate.current.setErrorsFatal(false);
  Isolate.current.addErrorListener(errorPort.sendPort);
  errorPort.listen((message) {
    // Masquerade as an IsolateSpawnException because that's what this would
    // be if the error had been detected statically.
    var error = new IsolateSpawnException(message[0]);
    var stackTrace =
        message[1] == null ? new Trace([]) : new Trace.parse(message[1]);
    Zone.current.handleUncaughtError(error, stackTrace);
  });
}

Fix some typos in comments

Fix some typos in comments


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "package:expect/expect.dart";

// Tests that inference can solve for T? ~ dynamic or void.

class C<T extends Object> {
  final T? value;
  const C(this.value);
  C.list(List<T?> list) : value = list.first;
  void set nonNullValue(T value) {}
}

List<T> foo<T extends Object>(T? value) => [value!];

List<T> bar<T extends Object>(List<T?> value) => [
      for (var element in value)
        if (element != null) element
    ];

extension Ext<T extends Object> on List<T?> {
  List<T> whereNotNull() => [
        for (var element in this)
          if (element != null) element
      ];
}

main() {
  {
    // Testing for dynamic.
    const dynamic o = 42;

    var c = const C(o);
    var f = foo(o);
    var l = [o].whereNotNull();

    c.expectStaticType<Exactly<C<Object>>>();
    Expect.type<C<Object>>(c); // Run-time type is subtype of C<Object>.
    c.nonNullValue = Object(); // And supertype.

    f.expectStaticType<Exactly<List<Object>>>();
    Expect.type<List<Object>>(f); // Run-time type is subtype of List<Object>.
    f[0] = Object(); // And supertype.

    l.expectStaticType<Exactly<List<Object>>>();
    Expect.type<List<Object>>(l); // Run-time type is subtype of List<Object>.
    l[0] = Object(); // And supertype.
  }

  {
    // Testing for void
    List<void> o = <void>[42];

    var c = C.list(o);
    var f = bar(o);
    var l = o.whereNotNull;

    c.expectStaticType<Exactly<C<Object>>>();
    Expect.type<C<Object>>(c); // Run-time type is subtype of C<Object>.
    c.nonNullValue = Object(); // And supertype.

    f.expectStaticType<Exactly<List<Object>>>();
    Expect.type<List<Object>>(f); // Run-time type is subtype of List<Object>.
    f[0] = Object(); // And supertype.

    l.expectStaticType<Exactly<List<Object>>>();
    Expect.type<List<Object>>(l); // Run-time type is subtype of List<Object>.
    l[0] = Object(); // And supertype.
  }
}

// Captures and checks static type of expression.
extension TypeCheck<T> on T {
  T expectStaticType<R extends Exactly<T>>() {
    return this;
  }
}

typedef Exactly<T> = T Function(T);

Add test for inference solving T? = dynamic.

See https://github.com/dart-lang/language/issues/1035

Change-Id: Ieb258a020d8212f5488cc3d73978b8132223353d
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/151760
Commit-Queue: Lasse R.H. Nielsen <80295e4ef244a07779f93eaa95d582bad8e316a5@google.com>
Reviewed-by: Leaf Petersen <9bef692239b5f624cec8e2cd5249ab1939a377aa@google.com>


// 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.

#library('TypedArraysRangeCheckTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('outOfRangeAccess_dynamic', () {
      var a = new Uint8Array(1024);

      expect(a[a.length]).isNull();
      expect(a[a.length + 1]).isNull();
      expect(a[a.length + 1024]).isNull();

      expect(a[-1]).isNull();
      expect(a[-2]).isNull();
      expect(a[-1024]).isNull();

      // It's harder to test out of range setters, but let's do some minimum.
      a[a.length] = 0xdeadbeaf;
      a[a.length + 1] = 0xdeadbeaf;
      a[a.length + 1024] = 0xdeadbeaf;

      a[-1] = 0xdeadbeaf;
      a[-2] = 0xdeadbeaf;
      a[-1024] = 0xdeadbeaf;
  });

  test('outOfRange_typed', () {
      Uint8Array a = new Uint8Array(1024);

      expect(a[a.length]).isNull();
      expect(a[a.length + 1]).isNull();
      expect(a[a.length + 1024]).isNull();

      expect(a[-1]).isNull();
      expect(a[-2]).isNull();
      expect(a[-1024]).isNull();

      // It's harder to test out of range setters, but let's do some minimum.
      a[a.length] = 0xdeadbeaf;
      a[a.length + 1] = 0xdeadbeaf;
      a[a.length + 1024] = 0xdeadbeaf;

      a[-1] = 0xdeadbeaf;
      a[-2] = 0xdeadbeaf;
      a[-1024] = 0xdeadbeaf;
  });
}

Add a test for out of range access of typed arrays.

R=podivilov@chromium.org,sra@google.com

Review URL: https://chromiumcodereview.appspot.com//10391087

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@7578 260f80e4-7a28-3924-810f-c04153c831b5


import "package:dartredisclient/redis_client.dart";

main() {
  print("main():");

  RedisClient client = new RedisClient();
  client.flushall();
  client.info.then((info) {
    client.close();
  });
}

Add small test case to repro weird behavior


import 'package:test/test.dart';
import 'package:minic/memory.dart';

void main() {
  group('[MemoryBlock]:', () {
    test('setValue converts values before insertion', () {
      var memory = new MemoryBlock(8);

      memory.setValue(0, NumberType.uint8, 1.0);
      expect(memory.getValue(0, NumberType.uint8), equals(1));

      memory.setValue(0, NumberType.fp32, 1);
      expect(memory.getValue(0, NumberType.fp32), equals(1.0));
    });

    test('handles range overflow by cropping most significant bits', () {
      var memory = new MemoryBlock(8);

      memory.setValue(0, NumberType.uint8, 257);
      expect(memory.getValue(0, NumberType.uint8), equals(1));
    });
  });
}

import 'package:test/test.dart';
import 'package:minic/memory.dart';

void main() {
  group('[MemoryBlock]:', () {
    test('setValue converts values before insertion', () {
      var memory = new MemoryBlock(8);

      memory.setValue(0, NumberType.uint8, 1.0);
      expect(memory.getValue(0, NumberType.uint8), equals(1));

      memory.setValue(0, NumberType.fp32, 1);
      expect(memory.getValue(0, NumberType.fp32), equals(1.0));
    });

    test('handles range overflow by cropping most significant bits', () {
      var memory = new MemoryBlock(8);

      memory.setValue(0, NumberType.uint8, 257);
      expect(memory.getValue(0, NumberType.uint8), equals(1));
    });

    test('arranges bytes in big endian order', () {
      var memory = new MemoryBlock(8);

      memory.setValue(0, NumberType.uint16, 258);
      expect(memory.getValue(0, NumberType.uint8), equals(1));
      expect(memory.getValue(1, NumberType.uint8), equals(2));
    });
  });
}

Add MemoryBlock test using big endian ordering


// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

export 'package:analyzer/src/summary/idl.dart' show PackageBundle;

Prepare for replacing PackageBundle with PackageBundleReader.

There are clients in google3 that import package:analyzer/src/summary/idl.dart
to use PackageBundle. We cannot make changes to idl.dart, so this
CL introduces a new file that we can change, and in the binary format CL
we will replace the exported PackageBundle class with a new class for
the binary format.

Change-Id: Iee89c784a2812bcdeefaef1c122ac8d8533665fe
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/174080
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


import 'package:ds/Task.dart';
import 'package:test/test.dart';

void main() {
  test('Task gets initialized correctly', () {
    var t1 = new Task('task1');
    expect(t1.summary, 'task1');
    expect(t1.contents.length, 0);
    expect(t1.scheduled, null);
    expect(t1.categories.length, 0);
  });
}

Check Tasks get initialized correctly.

Check Tasks get initialized correctly.


import 'dart:io';

void main() {
  double a = double.parse(stdin.readLineSync() ?? '');
  double b = double.parse(stdin.readLineSync() ?? '');
  double c = double.parse(stdin.readLineSync() ?? '');

  double media = (a * 2.0 + b * 3.0 + c * 5.0) / 10.0;

  print("MEDIA = ${media.toStringAsFixed(1)}");
}

Solve Average 2 in dart

Solve Average 2 in dart


import 'dart:async';

class A {
  FutureOr<int> x;
}

Future<int> foo() async => 42;

main() {
  var a = new A();
  a.x = 33;
  a.x = null;
  a.x = foo();
}

[VM] Add missing regression test for dartbug.com/34238

Issue https://github.com/dart-lang/sdk/issues/34238

Change-Id: If4ee2e09cd6764dd3dd7f88dfc3d007989f68eb5
Reviewed-on: https://dart-review.googlesource.com/71245
Reviewed-by: Martin Kustermann <a35dd5b79fac84b2bb3b026a16b8becc55af5961@google.com>
Commit-Queue: Martin Kustermann <a35dd5b79fac84b2bb3b026a16b8becc55af5961@google.com>


library benchmark;

import "dart:io";
import "package:badger/parser.dart";

int benchmark(Function function, [int warmup = 5, int milliseconds = 1000]) {
  var count = 0;
  var elapsed = 0;
  var watch = new Stopwatch();
  while (warmup-- > 0) {
    function();
  }
  watch.start();
  while (elapsed < milliseconds) {
    function();
    elapsed = watch.elapsedMilliseconds;
    count++;
  }
  return (elapsed / count).round();
}

void main() {
  var parser = new BadgerParser();
  Directory.current
      .list(recursive: true)
      .where((file) => file is File)
      .where((file) => file.path.endsWith('.badger'))
      .forEach((file) {
    var source = file.readAsStringSync();
    var result = parser.parse(source);
    if (result.isSuccess) {
      var time = benchmark(() => parser.parse(source));
      print('${file.path}: ${time.round()}ms');
    } else {
      print('${file.path}: FAILURE');
    }
  });
}

Add code to identify the slowest parses.


part of github.server;

class HookMiddleware {
  final StreamController<HookEvent> _eventController = new StreamController<HookEvent>();
  Stream<HookEvent> get onEvent => _eventController.stream;

  void handleHookRequest(HttpRequest request) {

    if (request.method != "POST") {
      request.response.write("Only POST is Supported");
      request.response.close();
      return;
    }

    if (request.headers['x-github-event'] == null) {
      request.response.write("X-GitHub-Event must be specified.");
      request.response.close();
      return;
    }

    request.transform(new Utf8Decoder()).join().then((content) {
      _eventController.add(new HookEvent(request.headers['x-github-event'].first, JSON.decode(content)));
      request.response.write(JSON.encode({
        "handled": true
      }));
      request.response.close();
    });
  }
}

class HookServer extends HookMiddleware {
  final String host;
  final int port;

  HttpServer _server;

  HookServer(this.port, [this.host = "0.0.0.0"]);

  void start() {
    HttpServer.bind(host, port).then((HttpServer server) {
      _server = server;
      server.listen(handleHookRequest);
    });
  }

  Future stop() => _server.close();
}

class HookEvent {
  final String event;
  final Map<String, Object> data;

  HookEvent(this.event, this.data);
}

part of github.server;

class HookMiddleware {
  final StreamController<HookEvent> _eventController = new StreamController<HookEvent>();
  Stream<HookEvent> get onEvent => _eventController.stream;

  void handleHookRequest(HttpRequest request) {

    if (request.method != "POST") {
      request.response.write("Only POST is Supported");
      request.response.close();
      return;
    }

    if (request.headers['x-github-event'] == null) {
      request.response.write("X-GitHub-Event must be specified.");
      request.response.close();
      return;
    }

    request.transform(new Utf8Decoder()).join().then((content) {
      _eventController.add(new HookEvent(request.headers['x-github-event'].first, JSON.decode(content)));
      request.response.write(JSON.encode({
        "handled": true
      }));
      request.response.close();
    });
  }
}

class HookServer extends HookMiddleware {
  final String host;
  final int port;

  HttpServer _server;

  HookServer(this.port, [this.host = "0.0.0.0"]);

  void start() {
    HttpServer.bind(host, port).then((HttpServer server) {
      _server = server;
      server.listen((request) {
        if (request.uri.path == "/hook") {
          handleHookRequest(request);
        } else {
          request.response.statusCode = 404;
          request.response.write("404 - Not Found");
          request.response.close();
        }
      });
    });
  }

  Future stop() => _server.close();
}

class HookEvent {
  final String event;
  final Map<String, Object> data;

  HookEvent(this.event, this.data);
}

Change HookServer to only hook on with /hook


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// VMOptions=--deterministic --optimization-counter-threshold=102 --enable-inlining-annotations --optimization-filter=Box_

import 'package:expect/expect.dart';

const String NeverInline = 'NeverInline';
const String AlwaysInline = 'AlwaysInline';
const int kLimit = 100;

main() {
  // Get all 3 functions optimized with _Smi's.
  optimizeMilliseconds(1);
  optimizeMicroseconds(1);
  optimizeConstructor(1);

  // Now we trigger a store of a _Mint into the Box._value
  testMints(2048);
}

@NeverInline
optimizeConstructor(int value) {
  for (int i = 0; i < kLimit; ++i) {
    new Box(milliseconds: value);
  }
}

@NeverInline
optimizeMicroseconds(int value) {
  final d = new Box(milliseconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000, d.inMicroseconds);
  }
}

@NeverInline
optimizeMilliseconds(int value) {
  final d = new Box(seconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000, d.inMilliseconds);
  }
}

@NeverInline
testMints(int value) {
  final d = new Box(seconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000 * 1000, d.inMicroseconds);
    Expect.equals(value * 1000, d.inMilliseconds);
  }
}

int c = 0;

class Box {
  final int _value;

  @NeverInline
  Box(
      {int days: 0,
      int hours: 0,
      int minutes: 0,
      int seconds: 0,
      int milliseconds: 0,
      int microseconds: 0})
      : this._microseconds(1000 * 1000 * 60 * 60 * 24 * days +
            1000 * 1000 * 60 * 60 * hours +
            1000 * 1000 * 60 * minutes +
            1000 * 1000 * seconds +
            1000 * milliseconds +
            microseconds);

  Box._microseconds(this._value);

  @NeverInline
  int get inMilliseconds => _value ~/ 1000;

  @NeverInline
  int get inMicroseconds => _value;
}

[VM] Add regression test for buildbot flakiness due to smi-widening optimization in VM

The added test in this CL causes code to be optimized with _Smi's and
eliminated field guards.  Field guards were eliminated due to usage of Smi ops,
which get removed due to the WidenSmiToInt32 optimization.
A use of the code with _Mint's will then trigger a test failure.

The WidenSmiToInt32 optimization has been disabled for the time being.

Change-Id: I6f7dd003a875b0abd708b3b948cda44378c42198
Reviewed-on: https://dart-review.googlesource.com/c/79540
Reviewed-by: Vyacheslav Egorov <72c81f38df725d8f1832acb9b5bb99563fc2f1b9@google.com>
Commit-Queue: Martin Kustermann <a35dd5b79fac84b2bb3b026a16b8becc55af5961@google.com>


library twitter.client;

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:oauth/oauth.dart' as oauth;

class Client extends oauth.Client {

	Client(oauth.Tokens tokens)
		: super(tokens);

	@override
	Future<http.Response> get(url, {Map<String,String> headers, body, Encoding encoding}){
		if (url is String) url = Uri.parse(url);
		var request = new http.Request("GET",url);

		if (headers != null) request.headers.addAll(headers);
		if (encoding != null) request.encoding = encoding;
		if (body != null){
			if (body is String){
				request.body = body;
			} else if (body is List){
				request.bodyBytes = body;
			} else if (body is Map){
				request.bodyFields = body;
			} else {
				throw new ArgumentError('Invalid request body "$body".');
			}
		}
		return super.send(request).then(http.Response.fromStream);
	}
}

Create Client class which extends oauth.Client


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for 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 tool cleans task objects from the project's datastore

import 'dart:io';
import 'dart:async';

import 'package:sintr_live_common/configuration.dart' as config;
import 'package:sintr_live_common/logging_utils.dart' as log;
import 'package:sintr_live_common/auth.dart' as auth;
import 'package:sintr_live_common/tasks.dart' as tasks;
import 'package:gcloud/src/datastore_impl.dart' as datastore_impl;
import 'package:gcloud/db.dart' as db;
import 'package:gcloud/service_scope.dart' as ss;

main(List<String> args) async {
  if (args.length < 1) {
    print("Usage: dart gc_tasks cloud_project_id");
    exit(1);
  }

  log.setupLogging();

  String projectId = args[0];

  config.configuration = new config.Configuration(projectId,
      cryptoTokensLocation:
          "${config.userHomePath}/Communications/CryptoTokens");

  var client = await auth.getAuthedClient();

  tasks.TaskController taskController =
      new tasks.TaskController("example_task");

  var datastore = new datastore_impl.DatastoreImpl(client, 's~$projectId');
  var datastoreDB = new db.DatastoreDB(datastore);

  log.info("Setup done");

  await ss.fork(() async {
    db.registerDbService(datastoreDB);

    await taskController.deleteAllTasks();
  });
  log.info("Tasks deleted");
}

Add tool to cleanup tasks

Add tool to cleanup tasks


library annotation_src_spec;

import 'package:angular/core/annotation_src.dart';
import 'dart:mirrors';
import '../_specs.dart';

var _SYMBOL_NAME = new RegExp('"([^@]*).*"');
_getName(VariableMirror v) => _SYMBOL_NAME.firstMatch(v.simpleName.toString()).group(1);

Map<String, dynamic> variables(x) {
  Map variables = {};
  InstanceMirror mirror = reflect(x) as InstanceMirror;
  ClassMirror type = mirror.type;
  do {
    type.declarations.forEach((k,v) {
      if (v is VariableMirror && !v.isStatic) {
        variables[_getName(v)] = mirror.getField(v.simpleName).reflectee;
      }
    });
  } while ((type = type.superclass) != null);

  return variables;
}

List<String> nullFields(x) {
  var ret = [];
  variables(x).forEach((k, v) {
    if (v == null) ret.add(k);
  });
  return ret;
}

void main() => describe('annotations', () {
  describe('component', () {
    it('should set all fields on clone when all the fields are set', () {
      var component = new Component(
        template: '',
        templateUrl: '',
        cssUrl: [''],
        applyAuthorStyles: true,
        resetStyleInheritance: true,
        publishAs: '',
        module: (){},
        map: {},
        selector: '',
        visibility: Directive.LOCAL_VISIBILITY,
        exportExpressions: [],
        exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(component)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(component, {}))).toEqual(variables(component));
    });
  });

  describe('decorator', () {
    it('should set all fields on clone when all the fields are set', () {
      var decorator = new Decorator(
          children: 'xxx',
          map: {},
          selector: '',
          module: (){},
          visibility: Directive.LOCAL_VISIBILITY,
          exportExpressions: [],
          exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(decorator)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(decorator, {}))).toEqual(variables(decorator));
    });
  });

  describe('controller', () {
    it('should set all fields on clone when all the fields are set', () {
      var controller = new Controller(
          publishAs: '',
          children: 'xxx',
          map: {},
          selector: '',
          module: (){},
          visibility: Directive.LOCAL_VISIBILITY,
          exportExpressions: [],
          exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(controller)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(controller, {}))).toEqual(variables(controller));
    });
  });
});

Verify clone does the right thing

test(annotation_src): Verify clone does the right thing


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Tests for parsing closures with complex parameter types.

main() {
  test1();
  test2();
  test3();
}

class Pair<A, B> {
  final A fst;
  final B snd;
  Pair(A this.fst, B this.snd);
}

test1() {
  // Closures with nested parameterized types.
  var cdar1 = (Pair<int, Pair<int, int>> pr) => pr.snd.fst;
  var cdar2 = (Pair<int, Pair<int, int> > pr) => pr.snd.fst;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(200, cdar1(e));
  Expect.equals(200, cdar2(e));
}

test2() {
  // Closures with nested parameterized types in optional position
  var cdar1 = ([Pair<int, Pair<int, int>> pr = null]) => pr.snd.fst;
  var cdar2 = ([Pair<int, Pair<int, int> > pr = null]) => pr.snd.fst;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(200, cdar1(e));
  Expect.equals(200, cdar2(e));
}

test3() {
  // Closures with nested parameterized types.
  var f1 = (Pair<int, Pair<int, int>> pr) => pr.snd.fst + 1;
  var f2 = (Pair<int, Pair<int, int> > pr) => pr.snd.fst + 2;

  // Closures with function type with nested parameterized types.
  var ap1 = (f(Pair<int, Pair<int, int>> pr), Pair<int, Pair<int, int>> pr)
                 => f(pr) * 10;
  var ap2 = (f(Pair<int, Pair<int, int> > pr), Pair<int, Pair<int, int> > pr)
                 => f(pr) * 100;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(2010, ap1(f1, e));
  Expect.equals(2020, ap1(f2, e));
  Expect.equals(20100, ap2(f1, e));
  Expect.equals(20200, ap2(f2, e));
}

Test with difficult to parse formal parameters.

BUG=
TEST=

Review URL: http://codereview.chromium.org//8343049

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@866 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';

abstract class DeviceInfo {
  /// The end-user-visible name for the device.
  Future<String?> get model;

  /// Returns `'ios'` if platform is iOS, otherwise returns `'android'`
  Future<String> get platform;

  /// A unique identifier for the device.
  Future<String?> get uniqueId;
}

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

  @override
  Future<String?> get model async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.model;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.name;
    }
  }

  @override
  Future<String?> get uniqueId async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.androidId;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.identifierForVendor;
    }
  }

  @override
  Future<String> get platform async {
    final isIos = Platform.isIOS;
    if (isIos) {
      return 'ios';
    }
    return 'android';
  }
}

Add DeviceInfo class to get model, platform, etc.


// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for 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 tool takes a time_to_fix file and emits summary information in a format
// that is easier to render

import 'dart:io';
import 'dart:convert';

main(List<String> args) async {
  String inputPath;
  if (args.length != 1) {
    print("usage: to_denorm_format.dart path");
    exit(1);
  }

  inputPath = args[0];

  // E.g. Resolved: {"severity":"ERROR","type":"SYNTACTIC_ERROR","message":"Expected an identifier","code":"missing_identifier","hasFix":false}, 1473891312265, 1473891313360, 1095

  await new File(inputPath).openRead().transform(UTF8.decoder).transform(new LineSplitter()).forEach((ln) {
    if (!ln.startsWith("Resolved:")) return;
    ln = ln.substring("Resolved:".length);

    int endOfJson = ln.lastIndexOf("}") + 1;
    int timeToFix = int.parse(ln.split(",").last);

    Map data = JSON.decode(ln.substring(0, endOfJson));

    print ("${data['code']}, ${data['hasFix']}, $timeToFix");

  });
}

Add tool to export timings

Add tool to export timings


import 'dart:sky';

import 'package:test/test.dart';

void main() {
  test("rect accessors", () {
    Rect r = new Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
    expect(r.left, equals(1.0));
    expect(r.top, equals(3.0));
    expect(r.right, equals(5.0));
    expect(r.bottom, equals(7.0));
  });

  test("rect created by width and height", () {
    Rect r = new Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
    expect(r.left, equals(1.0));
    expect(r.top, equals(3.0));
    expect(r.right, equals(6.0));
    expect(r.bottom, equals(10.0));
  });

  test("rect intersection", () {
    Rect r1 = new Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
    Rect r2 = new Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
    Rect r3 = r1.intersect(r2);
    expect(r3.left, equals(50.0));
    expect(r3.top, equals(50.0));
    expect(r3.right, equals(100.0));
    expect(r3.bottom, equals(100.0));
    Rect r4 = r2.intersect(r1);
    expect(r4, equals(r3));
  });
}

Fix Rect intersection; add test

Fix Rect intersection; add test


// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// None of these methods have any side effects, but using [Selector] count to
// order side-effects computation will make [_callNoSideEffectsManyTimes] be
// computed last and thus make [callCallNoSideEffectsManyTimes] and with it
// [main] assume all side-effects from the call to
// [_callNoSideEffectsManyTimes].
//
// The methods are deliberately put in order of increasing [Selector] count to
// make the [InferrerEngineImpl.useSorterForTesting] flag mimmick the order in
// the old inference.

/*element: _noSideEffects:Depends on nothing, Changes nothing.*/
_noSideEffects() {}

/*element: callCallNoSideEffectsManyTimes:Depends on [] field store static store, Changes [] field static.*/
callCallNoSideEffectsManyTimes() {
  _callNoSideEffectsManyTimes();
}

/*element: main:Depends on [] field store static store, Changes [] field static.*/
main() {
  callCallNoSideEffectsManyTimes();
  callCallNoSideEffectsManyTimes();
}

/*element: _callNoSideEffectsManyTimes:Depends on nothing, Changes nothing.*/
_callNoSideEffectsManyTimes() {
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
}

Add test for inadequate side-effects computation

Change-Id: Ia4b192490f6b21a6f5201751ba05b50dd493efaf
Reviewed-on: https://dart-review.googlesource.com/21720
Reviewed-by: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>


@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:test/test.dart';

import '1358_rebind_injector_test.template.dart' as ng;

void main() {
  ng.initReflector();

  ReflectiveInjector parentInjector;

  setUp(() {
    parentInjector = ReflectiveInjector.resolveAndCreate([
      new ClassProvider(Model),
      new ValueProvider(Place, new Place('Parent')),
    ]);
  });

  test('should have the expected bindings at the parent level', () {
    expect((parentInjector.get(Model) as Model).place.name, 'Parent');
  });

  test('should have the expected bindings at the child level', () {
    final childInjector = parentInjector.resolveAndCreateChild([
      new ValueProvider(Place, new Place('Child')),
    ]);
    expect(
      (childInjector.resolveAndInstantiate(Model) as Model).place.name,
      'Child',
    );
  });
}

class Place {
  final String name;

  Place(this.name);

  @override
  String toString() => '$Place {name=$name}';
}

@Injectable()
class Model {
  final Place place;

  Model(this.place);

  @override
  String toString() => '$Model {place=$place}';
}

Add a test for a customer use-case.

test(Core): Add a test for a customer use-case.

Closes #1361

PiperOrigin-RevId: 198746556


f(s) {
  return new Future(() => print(s));
}

g(x, y, z) {}

test1() async {
  g(print('a'),
      print('b'),
      g(print('1'), await f('2'), print('3')));
}

test2() async {
  g(print('a'),
      g(print('1'), await f('2'), print('3')),
      print('b'));
}

test3() async {
  g(print('a'),
      g(print('1'), await f('2'), print('3')),
      g(print('4'), await f('5'), print('6')));
}

test4() async {
  g(g(print('1'), await f('2'), print('3')),
      print('a'),
      print('b'));
}

Add a test for nested await argument subexpressions.


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Directory listing test.

class DirectoryTest {
  static void testListing() {
    bool listedSomething = false;
    Directory directory = new Directory.open(".");

    directory.setDirHandler((dir) {
      listedSomething = true;
    });

    directory.setFileHandler((f) {
      listedSomething = true;
    });

    directory.setDoneHandler((completed) {
      Expect.isTrue(completed, "directory listing did not complete");
      Expect.isTrue(listedSomething, "empty directory");
      directory.close();
    });

    directory.setDirErrorHandler((dir) {
      Expect.fail("error listing directory");
    });

    directory.list();
  }

  static void testMain() {
    testListing();
  }
}

main() {
  DirectoryTest.testMain();
}

Add simple directory listing test.

Add simple directory listing test.

For now, just test that we list something and that no errors occur.

R=sgjesse@google.com
BUG=
TEST=

Review URL: http://codereview.chromium.org//8222006

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@299 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;

final String PATH_TO_WEB_CONTENT = "web";

void main() {
  HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 3031).then((HttpServer server) {
    print("Serving at ${server.address}:${server.port}");
    final root = Platform.script.resolve(PATH_TO_WEB_CONTENT).toFilePath();
    final virDir = new VirtualDirectory(root)
        // The following are needed in dev mode to be able to access
        // Dart packages in the cache.
        ..followLinks = true
        ..jailRoot = false;
    server.listen((HttpRequest req) {
      print("${req.method} ${req.uri};\tcached ${req.headers.ifModifiedSince}");
      (req.method == "PUT" ? processPut : virDir.serveRequest)(req);
    });
  });
}

void processPut(HttpRequest request) {
  String filePath = request.uri.toFilePath();
  final file = new File(PATH_TO_WEB_CONTENT + filePath);
  request.pipe(file.openWrite()).then((_) {
    request.response
        ..statusCode = HttpStatus.NO_CONTENT
        ..close();
    print("Wrote to file '${file.path}'");
  });
}

Add simple HTTP server implementation in support of Chap. 6 exercises


library prop_map;

import 'dart:collection';

class PropMap extends MapBase<String, Object> {
  final _src = {};

  Object operator [](String key) => _src[key];
  operator []=(String key, Object value) => _src[key] = value;
  Iterable<String> get keys => _src.keys;
  Object remove(String key) => _src.remove(key);
  void clear() => _src.clear();
}

Create class that mimic a map to handle properties


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'layout2.dart';
import 'dart:sky' as sky;

class AppView {
  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }
}

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'layout2.dart';
import 'dart:sky' as sky;

class AppView {

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }

  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

}

Rearrange AppView so that the constructor is first.

R=abarth@chromium.org

Review URL: https://codereview.chromium.org/1154403002


// 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.

import 'package:matcher/matcher.dart';
import 'package:test/test.dart' show test, group;

import 'test_utils.dart';

void main() {
  _test('Map', isMap, {});
  _test('List', isList, []);
  _test('ArgumentError', isArgumentError, new ArgumentError());
  _test('Exception', isException, const FormatException());
  _test('FormatException', isFormatException, const FormatException());
  _test('StateError', isStateError, new StateError('oops'));
  _test('RangeError', isRangeError, new RangeError('oops'));
  _test('UnimplementedError', isUnimplementedError,
      new UnimplementedError('oops'));
  _test('UnsupportedError', isUnsupportedError, new UnsupportedError('oops'));
  _test('ConcurrentModificationError', isConcurrentModificationError,
      new ConcurrentModificationError());
  _test('CyclicInitializationError', isCyclicInitializationError,
      new CyclicInitializationError());
  _test('NoSuchMethodError', isNoSuchMethodError, null);
  _test('NullThrownError', isNullThrownError, new NullThrownError());

  group('custom `TypeMatcher`', () {
    _test('String', const isInstanceOf<String>(), 'hello');
    _test('String', const _StringMatcher(), 'hello');
  });
}

// TODO: drop `name` and use a type argument – once Dart2 semantics are enabled
void _test(String name, Matcher typeMatcher, Object matchingType) {
  group('for `$name`', () {
    if (matchingType != null) {
      test('succeeds', () {
        shouldPass(matchingType, typeMatcher);
      });
    }

    test('fails', () {
      shouldFail(
          const _TestType(),
          typeMatcher,
          anyOf(
              // Handles the TypeMatcher case
              equalsIgnoringWhitespace('Expected: $name Actual: ?:<TestType>'),
              // Handles the `isInstanceOf` case
              equalsIgnoringWhitespace(
                  'Expected: an instance of $name Actual: ?:<TestType>')));
    });
  });
}

class _StringMatcher extends TypeMatcher {
  const _StringMatcher() : super('String');

  bool matches(item, Map matchState) => item is String;
}

class _TestType {
  const _TestType();

  String toString() => 'TestType';
}

Add tests for all isXYZ matchers

test: Add tests for all isXYZ matchers


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Check that const objects (including literals) are immutable.

// should be 'const {}'
invalid([var p = {}]) {
}

main() {
  invalid();
}

Check constness of default args

Check constness of default args

BUG= http://code.google.com/p/dart/issues/detail?id=635

Review URL: http://codereview.chromium.org//8772070

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@2051 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Verifies that VM is able to handle certain cases of unreachable code.

// VMOptions=--no_background_compilation --optimization_counter_threshold=10

import "package:expect/expect.dart";

class A {
  dynamic next;
}

test1(A arg1, bool arg2, bool arg3) {
  assert(arg1.next == (arg2 ?? arg3));
}

test2(A arg1, bool arg2, bool arg3) {
  print(((throw 'Error') as dynamic).next == (arg2 ?? arg3));
}

void doTests() {
  test1(new A(), null, null);
  Expect.throws(() {
    test2(new A(), null, null);
  });
}

void main() {
  for (int i = 0; i < 20; i++) {
    doTests();
  }
}

[vm] Add test for certain cases of unreachable code

This is the follow-up for https://github.com/dart-lang/sdk/commit/1d10e037ef9e69424f4fce998b4857648a96e740.

Change-Id: Ifd35acb08904d34010ede0fe609076424d146374
Reviewed-on: https://dart-review.googlesource.com/c/81331
Commit-Queue: Alexander Markov <239e774fd29abc1267878f57afe1a8a03e0ca887@google.com>
Commit-Queue: Régis Crelier <c2bf536a10d9f2530c38e4e8da517718be8c39ce@google.com>
Auto-Submit: Alexander Markov <239e774fd29abc1267878f57afe1a8a03e0ca887@google.com>
Reviewed-by: Régis Crelier <c2bf536a10d9f2530c38e4e8da517718be8c39ce@google.com>


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:isolate';

Future<int> runServer(int port, int connections, bool clean) {
  var completer = new Completer();
  HttpServer.bind("127.0.0.1", port).then((server) {
    int i = 0;
    server.listen((request) {
      request.pipe(request.response);
      i++;
      if (!clean && i == 10) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });

    Future.wait(new List.generate(connections, (_) {
      var client = new HttpClient();
      return client.get("127.0.0.1", server.port, "/")
          .then((request) => request.close())
          .then((response) => response.drain())
          .catchError((e) { if (clean) throw e; });
    })).then((_) {
      if (clean) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });
  });
  return completer.future;
}

void testReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, true).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, true);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void testUncleanReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, false).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, false);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void main() {
  testReusePort();
  testUncleanReusePort();
}

Add test for reusing the port of a server socket, after the server's close future is completed.

BUG=
R=kustermann@google.com

Review URL: https://codereview.chromium.org//19653004

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@25257 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library solver.msrand;

import "dart:math";

class MSRandom implements Random {
  int _seed;

  MSRandom(this._seed);

  int _rand() {
    _seed = (_seed * 214013 + 2531011) & 0x7FFFFFFF;
    return ((_seed >> 16) & 0x7fff);
  }

  int nextInt(max) {
    return _rand() % max;
  }

  double nextDouble() {
    return _rand() % 101 / 100.0;
  }

  bool nextBool() {
    return nextDouble() > 0.5;
  }
}

Add the MS random number generator.

Add the MS random number generator.


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/analyzer.dart';
import 'package:analyzer/plugin/options.dart';
import 'package:analyzer/src/lint/registry.dart';
import 'package:yaml/yaml.dart';

/**
 * An error code indicating an undefined lint rule.
 *
 * Parameters:
 * 0: the rule name
 */
const AnalysisOptionsWarningCode UNDEFINED_LINT_WARNING =
    const AnalysisOptionsWarningCode(
        'UNDEFINED_LINT_WARNING', "'{0}' is not a recognized lint rule");

/**
 * Validates `linter` rule configurations.
 */
class LinterRuleOptionsValidator extends OptionsValidator {
  static const linter = 'linter';
  static const rulesKey = 'rules';
  @override
  List<AnalysisError> validate(
      ErrorReporter reporter, Map<String, YamlNode> options) {
    List<AnalysisError> errors = <AnalysisError>[];
    var node = options[linter];
    if (node is YamlMap) {
      var rules = node.nodes[rulesKey];
      validateRules(rules, reporter);
    }
    return errors;
  }

  validateRules(dynamic rules, ErrorReporter reporter) {
    if (rules is YamlList) {
      Iterable<String> registeredLints =
          Registry.ruleRegistry.map((r) => r.name);
      rules.nodes.forEach((YamlNode ruleNode) {
        Object value = ruleNode.value;
        if (value != null && !registeredLints.contains(value)) {
          reporter.reportErrorForSpan(
              UNDEFINED_LINT_WARNING, ruleNode.span, [value]);
        }
      });
    }
  }
}

Add file missed in last commit (TBR)

Add file missed in last commit (TBR)

Review-Url: https://codereview.chromium.org/2562223002 .


part of ThreeD;

class EventEmitterEvent {
  String type;
  String message;
  var content;
  EventEmitterEvent({this.type, this.message, this.content});
}

class EventEmitter {

	var listeners;

	EventEmitter() : listeners = {};

	addEventListener( type, listener ) {

		if ( listeners[ type ] == null ) {
			listeners[ type ] = [];
		}

		if ( listeners[ type ].indexOf( listener ) == - 1 ) {
			listeners[ type ].add( listener );
		}

	}

	dispatchEvent( event ) {
		if ( listeners[ event.type ] != null ) {
			listeners[ event.type ].forEach((listener) => listener( event ));
                }
	}

	removeEventListener ( type, listener ) {

		var index = listeners[ type ].indexOf( listener );

		if ( index != - 1 ) {
			listeners[ type ].removeRange( index, 1 );
		}

	}

}

Fix tabs on closing brace.

Fix tabs on closing brace.


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";

// SharedOptions=--enable-experiment=non-nullable
void main() {
}

/// These tests will all pass only if run with the NNBD migrated SDK.
/// In not migrated SDK all types are unprefixed, so look non-nullable.
void f(List<int> list, Map<int, String> map, int a, int? b) {
  // List: E operator [](int index);
  list[a]; //# 00: ok
  list[b]; //# 01: compile-time error

  // Map: V? operator [](Object? key);
  map[a]; //# 02: ok
  map[b]; //# 03: ok

  // Map: void operator []=(K key, V value);
  map[a].length; //# 04: compile-time error
  map[a]?.length; //# 05: ok

  map[b] = ''; //# 06: compile-time error
  map[a] = b; //# 07: compile-time error
}

Add a NNBD test that needs NNBD migrated SDK.

I tested it locally by updating `SharedOptions` to include not only
`--enable-experiment=non-nullable`, but also the forced path to NNBD
SDK: `--dart-sdk=/Users/scheglov/Applications/dart-sdk-NNBD`.

This will fail for now, I will accept current bot failures.

Change-Id: I72c9b46049de6cd25eddebd43d5c73c2fc9d7825
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/124168
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Reviewed-by: Paul Berry <72d414e3a99fb120308437779d51667bcc0984eb@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.md file.

import "package:testing/src/run_tests.dart" as run_tests;

main(List<String> arguments) => run_tests.main(arguments);

Add entrypoint to make benefit pub run.

Add entrypoint to make benefit pub run.

R=karlklose@google.com

Review URL: https://codereview.chromium.org/2428903002 .


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_js_helper";
import "package:expect/expect.dart";

// Test that compiler is cautious with optimizations on native fields.  The
// motivation is that DOM properties are getters and setters with arbitrary
// effects.  Setting CSSStyleDeclaration.borderLeft can canonicalize the value
// and changes the value of CSSStyleDeclaration.border.

@Native("Foo")
class Foo {
  var a;
  var b;
  var ab;
}

Foo makeFoo() native;

void setup() native """
function Foo() { this.i = 0; }

Object.defineProperty(Foo.prototype, 'a', {
  get: function () { return (this._a || '') + ++this.i; },
  set: function (v) { this._a = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'b', {
  get: function () { return this._b || ''; },
  set: function (v) { this._b = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'ab', {
  get: function () { return this.a + ' ' + this.b; },
  set: function (v) {
    var s = v.split(' ');
    this.a = s[0];
    this.b = s[1];
  }
});

makeFoo = function() { return new Foo() }
""";

test1() {
  var f = makeFoo();
  f.a = 'Hi';
  f.b = 'There';
  Expect.equals('hi1 there', f.ab);
}

test2() {
  // Test for CSE. dart2js currently does CSE loads. Is this the right choice?
  var f = makeFoo();
  var a1 = f.a;
  var b1 = f.b;
  var a2 = f.a;
  Expect.equals('1', a1);
  if (a2 == a1) {
    // We did CSE.
  } else {
    Expect.equals('2', a2);
  }
}

test3() {
  // Must not CSE over a native field store.
  var f = makeFoo();
  var a1 = f.a;
  f.ab = 'X Y';
  var a2 = f.a;
  Expect.equals('1', a1);
  Expect.equals('x2', a2);
}

test4() {
  // Must not store-forward.
  var f = makeFoo();
  f.a = 'A';
  var a2 = f.a;
  Expect.equals('a1', a2);
}

main() {
  setup();
  (test1)();
  (test2)();
  (test3)();
  (test4)();
}

Test for limited optimizations on native fields

This captures some of the current status on how optimizations interact with native fields.

R=herhut@google.com

Review URL: https://codereview.chromium.org//1031073002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@44783 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';

main() {
  initConfig();

  integration("includes .dart files from dependencies in debug mode", () {
    // Dart2js can take a long time to compile dart code, so we increase the
    // timeout to cope with that.
    currentSchedule.timeout *= 3;

    d.dir("foo", [
      d.libPubspec("foo", "0.0.1"),
      d.dir("lib", [
        d.file('foo.dart', 'foo() => print("hello");'),
        d.dir("sub", [
          d.file('bar.dart', 'bar() => print("hello");'),
        ])
      ])
    ]).create();

    d.dir(appPath, [
      d.appPubspec({
        "foo": {"path": "../foo"}
      }),
      d.dir("example", [
        d.file("main.dart", 'myapp() => print("not entrypoint");'),
        d.dir("sub", [
          d.file("main.dart", 'myapp() => print("not entrypoint");')
        ])
      ])
    ]).create();

    schedulePub(args: ["build", "--mode", "debug", "example"],
        output: new RegExp(r"Built 4 files!"));

    d.dir(appPath, [
      d.dir('build', [
        d.dir('example', [
          d.file("main.dart", 'myapp() => print("not entrypoint");'),
          d.dir('packages', [
            d.dir('foo', [
              d.file('foo.dart', 'foo() => print("hello");'),
              d.dir("sub", [
                d.file('bar.dart', 'bar() => print("hello");'),
              ])
            ])
          ]),
          d.dir("sub", [
            d.file("main.dart", 'myapp() => print("not entrypoint");'),
            // Does *not* copy packages into subdirectories.
            d.nothing("packages")
          ])
        ])
      ])
    ]).validate();
  });
}

Test that .dart files are copied to packages/ in debug mode.

BUG=https://code.google.com/p/dart/issues/detail?id=16567
R=nweiz@google.com

Review URL: https://codereview.chromium.org//149213009

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@32566 260f80e4-7a28-3924-810f-c04153c831b5


/// This regression test demonstrates why `View.injectorGet()` must null-check
/// the `nodeIndex` argument, a rare and complex case that requires a number of
/// conditions to be met.
///
///   (1) Create a component whose template contains a top-level view container;
///   this ensures the view container has a null parent index.
///
///   (2) Add directive(s) with multiple providers to any node in the
///   component's template with at least one child node; this ensures that a
///   range check on `nodeIndex` is generated in `injectorGetInternal` and not
///   skipped due to short-circuit evaluation when a node only has one provider
///   and the token doesn't match. This range check is what will throw if
///   `nodeIndex` is null.
///
///   (3) Inject a dependency via the top-level view container's
///   `parentInjector`. This causes the null parent index to pass from
///   `ElementInjector.provideUntyped()` to `View.injectorGet()`.
@TestOn('browser')
import 'package:test/test.dart';
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';

import 'b_133253211_null_node_index_test.template.dart' as ng;

void main() {
  tearDown(disposeAnyRunningTest);

  test('View.injectorGet() should handle a null nodeIndex argument', () async {
    final testValue = 'Hello world!';
    final testBed = NgTestBed.forComponent(
      ng.TestComponentNgFactory,
      rootInjector: ([parent]) => Injector.map({testToken: testValue}, parent),
    );
    final testFixture = await testBed.create();
    final testComponent = testFixture.assertOnlyInstance;
    expect(
      // This parent injector, an `ElementInjector`, passes a null nodeIndex
      // parameter to `View.injectorGet()`. Note that while this looks like a
      // bizarre use case that might not seem worth supporting, this is the
      // simplest reproduction of this pattern that can be achieved far more
      // indirectly via declarative means. Clients do depend on this behavior.
      testComponent.viewContainerRef.parentInjector.provideToken(testToken),
      testValue,
    );
  });
}

@Component(
  selector: 'test',
  directives: [ProvidersDirective],
  template: '''

      Some content to create a range check on nodeIndex

  ''',
)
class TestComponent {
  @ViewChild('container', read: ViewContainerRef)
  ViewContainerRef viewContainerRef;
}

const testToken = OpaqueToken<String>('test');
const tokenA = OpaqueToken<String>('a');
const tokenB = OpaqueToken<String>('b');

@Directive(
  selector: '[providers]',
  // Multiple providers to ensure the range check isn't skipped due to short
  // circuit evaluation of mismatched token query.
  providers: [
    ValueProvider.forToken(tokenA, 'a'),
    ValueProvider.forToken(tokenB, 'b'),
  ],
)
class ProvidersDirective {}

Add regression test for null `nodeIndex` argument passed to `View.injectorGet()`

This demonstrates why `View.injectorGet()` must null-check the `nodeIndex`
argument, a rare and complex case that requires a number of conditions to be
met.

  (1) Create a component whose template contains a top-level view container;
  this ensures the view container has a null parent index.

  (2) Add directive(s) with multiple providers to any node in the component's
  template with at least one child node; this ensures that a range check on
  `nodeIndex` is generated in `injectorGetInternal` and not skipped due to
  short-circuit evaluation when a node only has one provider and the token
  doesn't match. This range check is what will throw if `nodeIndex` is null.

  (3) Inject a dependency via the top-level view container's `parentInjector`.
  This causes the null parent index to pass from
  `ElementInjector.provideUntyped()` to `View.injectorGet()`.

PiperOrigin-RevId: 249476365


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library sintr_common.pubsub_utils;

import 'dart:async';

import 'package:gcloud/pubsub.dart';
import "package:logging/logging.dart" as logging;

final _log = new logging.Logger("PubSub_support");

/// Gets a topic, if it doesn't already exist, create it.
Future<Topic> getTopic(String name, PubSub ps) async {

  // Try and find the topic.
  _log.finer("PRE: Getting topic for $name");

  Topic topic;

  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Existing topic found: $name");
    return topic;
  }

  // Try and create the topic.
  try {
    topic = await ps.createTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic creation failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.fine("OK: Topic created: $name");
    return topic;
  }

  // The creation make have failed because of a race between the lookup and
  // the creation.
  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Topic found after race: $name");
    return topic;
  }

  _log.shout("FAIL: Topic not $name");
  throw "Topic not found: $name";
}

Add library to get a topic creating it if necessary


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Regression test for CL 194523002.

library js_custom_test;

import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';
import 'dart:html';
import '../utils.dart';

class A extends HtmlElement {
  static final tag = 'x-a';
  factory A() => new Element.tag(tag);
  A.created() : super.created();
}

main() {
  useHtmlConfiguration();

  // Adapted from Blink's
  // fast/dom/custom/constructor-calls-created-synchronously test.

  var registered = false;
  setUp(() {
    return customElementsReady.then((_) {
      if (!registered) {
        registered = true;
        document.register(A.tag, A);
      }
    });
  });
}

Add regression test for CL 194523002

Add regression test for CL 194523002

BUG=
R=floitsch@google.com

Review URL: https://codereview.chromium.org//214443002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@34470 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

void _expectSpan(SourceSpan source, String expected) {
  final result = source.message('message');
  printOnFailure("r'''\n$result'''");

  expect(result, expected);
}

void main() {
  YamlMap yaml;

  setUpAll(() {
    yaml = loadYaml(const JsonEncoder.withIndent(' ').convert({
      'num': 42,
      'nested': {
        'null': null,
        'num': 42,
      },
      'null': null,
    })) as YamlMap;
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['num'].span,
      r'''
line 2, column 9: message
  ╷
2 │  "num": 42,
  │         ^^
  ╵''',
    );
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['null'].span,
      r'''
line 7, column 10: message
  ╷
7 │  "null": null
  │          ^^^^
  ╵''',
    );
  });

  group('nested', () {
    YamlMap nestedMap;

    setUpAll(() {
      nestedMap = yaml.nodes['nested'] as YamlMap;
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['null'].span,
        r'''
line 4, column 11: message
  ╷
4 │   "null": null,
  │           ^^^^
  ╵''',
      );
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['num'].span,
        r'''
line 5, column 10: message
  ╷
5 │     "num": 42
  │ ┌──────────^
6 │ │  },
  │ └─^
  ╵''',
      );
    });
  });
}

Add test to validate SourceSpan values for nodes

Preparing for https://github.com/dart-lang/yaml/issues/51


// Copyright (c) 2014, the Liquid project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library liquid.utils;

class AssertionFailure {
  final String message;

  const AssertionFailure(this.message);

  String toString() => message;
}

bool invariant(condition, [message]) {
  if (condition is Function){
    condition = condition();
  }
  if (!condition) {
    if (message is Function) {
      message = message();
    }
    throw new AssertionFailure(message);
  }
  return true;
}

Add functions for runtime checking

Add functions for runtime checking


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Example of retrieving a sensor using the Sensor API.

// C++ implementation can be found here:
// https://docs.microsoft.com/en-us/windows/win32/sensorsapi/retrieving-a-sensor

import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

void main() {
  CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

  final sensorManager = SensorManager.createInstance();

  // Replace this with the sensor category you're looking for.
  final sampleDateTimeSensorCategory =
      GUIDFromString('{062A5C3B-44C1-4ad1-8EFC-0F65B2E4AD48}');
  final pSensorsColl = calloc<Pointer<COMObject>>();
  var hr = sensorManager.GetSensorsByCategory(
      sampleDateTimeSensorCategory, pSensorsColl);
  if (FAILED(hr)) throw WindowsException(hr);

  final coll = ISensorCollection(pSensorsColl.cast());
  final pCount = calloc<Uint32>();
  if (coll.GetCount(pCount) > 1) {
    print('Found items');
  }

  free(pCount);
  free(pSensorsColl);
  free(sampleDateTimeSensorCategory);

  CoUninitialize();
}

Add trivial example of usage

Add trivial example of usage


import 'package:moor/moor.dart';
import 'package:moor_ffi/moor_ffi.dart';
@TestOn('vm')
import 'package:test/test.dart';

import '../data/tables/todos.dart';

void main() {
  TodoDb db;

  setUp(() {
    db = TodoDb(VmDatabase.memory());
  });

  test('insertOnConflictUpdate', () async {
    await db.into(db.categories).insert(
        CategoriesCompanion.insert(description: 'original description'));

    var row = await db.select(db.categories).getSingle();

    await db.into(db.categories).insertOnConflictUpdate(CategoriesCompanion(
        id: Value(row.id), description: const Value('changed description')));

    row = await db.select(db.categories).getSingle();
    expect(row.description, 'changed description');
  });
}

Add small integration test for generated upserts


import 'dart:convert' show UTF8;
import 'dart:typed_data' show Uint8List;

final _padding = [
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
];

Uint8List stringToUint8List(String value) =>
  new Uint8List.fromList(
    (UTF8.encode(value).toList()
      ..addAll(_padding)
    ).sublist(0, 32),
  );

Add the stringtoUint8List utility function


// 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.

// Test that a Dart implementation doesn't turn dynamic errors into
// compilation errors.

f(x) {}

class MyClass {
  MyClass(x, y);

  foo() {
    var z;
    // Neither y nor x are defined. So they are simply dynamic
    // (getter) sends to this, not compile-time errors.
    if (false) f(new MyClass(z, y[x.y.z]));
    if (false) print(y[x.y.z]);
  }
}

main() {
  var x;
  // We know the concrete type of f (a function closure) does not
  // support the index operator. However, this is a dynamic error, so
  // this program should compile.
  if (false) print(f[x.y.z]);
  new MyClass(0, 0).foo();
}

Test that expose a few quirks in the Dart VM parser.

Review URL: https://chromiumcodereview.appspot.com//9205003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6783 260f80e4-7a28-3924-810f-c04153c831b5


// 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.

#library('HTMLOptionsCollectionTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('indexedAccessTest', () {
    // FIXME: we need some massaging to dart:html to enable HTMLOptionsCollection.add
    // and hence programatic building of collection.
    final selectElement = new Element.html('''
      <select>
        <option value="0">Option0</option>
        <option value="1">Option1</option>
        <option value="2">Option2</option>
      ''');
    final optionsCollection = selectElement.options;

    expect(optionsCollection[0].value, equals('0'));
    expect(optionsCollection[1].value, equals('1'));
    expect(optionsCollection[2].value, equals('2'));

    expect(optionsCollection[0].text, equals('Option0'));
    expect(optionsCollection[1].text, equals('Option1'));
    expect(optionsCollection[2].text, equals('Option2'));

    expect(() { optionsCollection[0] = 1; }, throws);

    optionsCollection[0] = new OptionElement(value: '42', data: 'Option42');
    expect(optionsCollection[0].value, equals('42'));
    expect(optionsCollection[0].text, equals('Option42'));
  });
}

Add a simple test for HTMLOptionsCollection.

R=podivilov@chromium.org

Review URL: https://chromiumcodereview.appspot.com//10636002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@8978 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that it is an error for a class with no generative constructors to
// have a final instance variable without an initializing expression, except
// if it is `abstract` or `external`. The latter also holds in a class with
// generative constructors.

// Has factory, hence no default, hence no generative constructors.
abstract class A {
  final dynamic n;
  //            ^
  // [analyzer] COMPILE_TIME_ERROR.FINAL_NOT_INITIALIZED
  // [cfe] unspecified

  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;

  factory A() = B;
}

class B implements A {
  dynamic get n => 1;
  int get x1 => 1;
  int? get x2 => null;
  String get x3 => "";
  String? get x4 => null;
}

class C = Object with A;

// Has a generative constructor: default.
abstract class D {
  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;
}

void main() {
  A();
  C();
  var _ = D;
}

Add test for missing initializer on final instance variable

Add a test where a class that has no generative constructors
declares an instance variable which is final and has no initializing
expression. With https://github.com/dart-lang/language/pull/1130 this
is an error, and that error is expected by the test. Also test that
it is not an error to have an uninitialized final variable which is
abstract or external.

Change-Id: I6c4a46393f46587448612bd91fb99fa65f89704c
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/157490
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Reviewed-by: Bob Nystrom <afede3a9ebedb865bee78398feff6fbe97068f17@google.com>


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'package:expect/expect.dart';

class A implements Future<Future<A>> {
  @override
  noSuchMethod(Invocation _) {}
}

void main() {
  Expect.notSubtype<A, Future<A>>();
  Expect.subtype<FutureOr<A>, FutureOr<Future<A>>>();
}

Add test demonstrating that FutureOr<A> <: FutureOr<B> =/=> A <: B.

Change-Id: Iedc60b57f80e77784e54b8d5ed9076c5016edd2f
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/121653
Commit-Queue: Mayank Patke <e0355b78204b67a55a952941c68c8f1b40235938@google.com>
Reviewed-by: Leaf Petersen <9bef692239b5f624cec8e2cd5249ab1939a377aa@google.com>


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'dart:async';
import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import 'utils.dart';

main() {
  // This is a regression test for http://dartbug.com/21402.
  initConfig();
  withBarbackVersions("any", () {
    integration("picks up files replaced after serving started when using the "
        "native watcher", () {
      d.dir(appPath, [
        d.pubspec({
          "name": "myapp",
          "transformers": ["myapp/src/transformer"]
        }),
        d.dir("lib", [d.dir("src", [
          d.file("transformer.dart", REWRITE_TRANSFORMER)
        ])]),
        d.dir("web", [
          d.file("file.txt", "before"),
        ]),
        d.file("other", "after")
      ]).create();

      createLockFile("myapp", pkg: ["barback"]);

      pubServe(args: ["--no-force-poll"]);
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "before.out");

      schedule(() {
        // Replace file.txt by renaming other on top of it.
        return new File(p.join(sandboxDir, appPath, "other"))
            .rename(p.join(sandboxDir, appPath, "web", "file.txt"));
      });

      // Read the transformed file to ensure the change is actually noticed by
      // pub and not that we just get the new file contents piped through
      // without pub realizing they've changed.
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "after.out");

      endPubServe();
    });
  });
}

Test that safe saves are picked up by pub serve.

BUG=https://code.google.com/p/dart/issues/detail?id=21402
R=nweiz@google.com

Review URL: https://codereview.chromium.org//870703003

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@43082 260f80e4-7a28-3924-810f-c04153c831b5


/// Selection Sort the input list
void selectionSort(List<int> items) {
  // Iterate through the array, knowing left-of-i is sorted and looking
  // for the lowest to-the-right element to place at the end of left
  for (int i = 0; i < items.length - 1; i++) {
    int lowestIndex = i;
    for (int j = i + 1; j < items.length; j++) {
      if (items[j] < items[lowestIndex]) {
        lowestIndex = j;
      }
    }

    // Swap the lowest item with this position (i)
    final int lowestNumber = items[lowestIndex];
    items[lowestIndex] = items[i];
    items[i] = lowestNumber;
  }
}
 // ----- Test -----
void main() {
  // 1. Arrange
  final List<int> testedList = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
  final List<int> expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   // 2. Act
  selectionSort(testedList);
  print(testedList);
   // 3. Assert
  // No simple list equality in dart yet so using 'fold' to recursively check
  // each sorted element compared to the expected output at each index.
  int i = 0;
  final bool isEqual = testedList.fold(
    true,
    (result, item) => result && item == expectedOutput[i++],
  );
  print(isEqual);
}

Add Dart implementation of Selection Sort


// 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.
// Dart test program for default constructors.

String message;

foo() {
  message += 'foo';
  return 1;
}

bar() {
  message += 'bar';
  return 2;
}

class X {
  var i;
  var j;
  X([a = 'defa', b = 'defb']) : this.i = a, this.j = b;
  X.foo() : this(b: 1, a: 2);
  X.bar() : this(
                     1,  /// 01: compile-time error
                     a: 2);
  X.baz() : this(a: 1, b: 2);
  X.qux() : this(1, 2);
  X.hest() : this();
  X.fisk() : this(b: bar(), a: foo());
  X.naebdyr() : this(a: foo(), b: bar());
}

test(x, a, b) {
  Expect.equals(x.i, a);
  Expect.equals(x.j, b);
}

main() {
  test(new X.foo(), 2, 1);
  test(new X.bar(), 2, 'defb');
  test(new X.baz(), 1, 2);
  test(new X.qux(), 1, 2);
  test(new X.hest(), 'defa', 'defb');

  message = '';
  new X.fisk();
  Expect.equals('barfoo', message);

  message = '';
  new X.naebdyr();
  Expect.equals('foobar', message);
}

Support named parameters for super initializers and redirections.

Review URL: https://chromiumcodereview.appspot.com//9454014

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@4606 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Check function subtyping of type arguments. These cases use typedefs as type
// arguments, and the typedefs have type parameters that are used more than
// once.

import 'package:expect/expect.dart';

typedef A F<A>(A arg1, A arg2);
typedef B G<A,B>(B arg1, B arg2);

typedef Set<A> FS<A>(Set<A> arg1, Set<A> arg2);

@NoInline() @AssumeDynamic() dyn(x) => x;

class CheckEnv<X, Y> {
  test(bool intX) {
    Expect.isTrue(<F<X>>[] is List<F>);
    Expect.isTrue(<F<X>>[] is List<F<X>>);
    Expect.isTrue(<F<X>>[] is List<G<Y,X>>);

    Expect.isTrue(dyn(<F<X>>[]) is List<F>);
    Expect.isTrue(dyn(<F<X>>[]) is List<F<X>>);
    Expect.isTrue(dyn(<F<X>>[]) is List<G<Y,X>>);

    Expect.isTrue(<F<X>>[] is! List<F<Y>>);
    Expect.isTrue(<F<X>>[] is! List<G<X,Y>>);

    Expect.isTrue(dyn(<F<X>>[]) is! List<F<Y>>);
    Expect.isTrue(dyn(<F<X>>[]) is! List<G<X,Y>>);

    Expect.isTrue(dyn(<FS<X>>[]) is List<FS>);
    Expect.isTrue(dyn(<FS<X>>[]) is List<FS<X>>);
    if (intX) {
      Expect.isTrue(dyn(<FS<X>>[]) is List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is List<FS<X>>);
      Expect.isTrue(dyn(<FS<Y>>[]) is! List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is! List<FS<Y>>);
    }
  }
}

main() {
  Expect.isTrue(<F<int>>[] is List<F<int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<F<int>>);
  Expect.isTrue(<F<int>>[] is List<G<bool,int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<G<bool,int>>);

  new CheckEnv<int,String>().test(true);
  new CheckEnv<String,int>().test(false);
}

Add language test with nested function typedef with two references to argument

R=sigmund@google.com

Review URL: https://codereview.chromium.org/2297783002 .


import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:test/test.dart';
import 'package:win32/win32.dart';

// This test prevents CI from failing on other platforms (GitHub Actions fails
// unless at least one test is run successfully.)
void main() {
  test('Neutral test to give non-Windows platforms something to chew on', () {
    final point = calloc<POINT>()
      ..ref.x = 0x10
      ..ref.y = 0x7F;
    expect(point.ref.x + point.ref.y, equals(0x8F));
    free(point);
  });
}

Add platform-independent test to fix Ubuntu flake


import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

import 'expect_no_changes_dev_mode_test.template.dart' as ng_generated;

void main() {
  ng_generated.initReflector();

  test('should throw during change detection', () async {
    final testBed = new NgTestBed<IllegalChangeDetectionComponent>();
    expect(
      testBed.create(),
      throwsA(predicate(
        (e) => '$e'.contains('Expression has changed after it was checked'),
      )),
    );
  });
}

@Component(
  selector: 'illegal-change-detection',
  template: r'''
    <div>{{counter}}</div>
  ''',
)
class IllegalChangeDetectionComponent {
  var _counter = 0;
  int get counter => _counter++;
}

test(Core): Add a test that shows that "expression has changed" works.

PiperOrigin-RevId: 183892699


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test program checking that optimizations are not too aggresive and
// incorrect:
// - (a * (1.0 / b))
//
// VMOptions=--optimization-counter-threshold=8 --no-use-osr

import "package:expect/expect.dart";

var xx = 23.0;

main() {
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
  for (int i = 0; i < 10; i++) {
    xx = 24.0;
    scaleIt(6.0);
    Expect.equals(4.0, xx);
  }
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
}

scaleIt(double b) {
  scale(1.0 / b);
}

scale(a) {
  xx *= a;
}

Add check that no aggressive & incorrect optimizations is done.

R=sra@google.com

Review URL: https://codereview.chromium.org//1033873003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@44746 260f80e4-7a28-3924-810f-c04153c831b5


/// Computes what the probability should be set for each wheel if
/// there are five of them and success is 3+ successful wheels.
library compute_floating_setup;

import 'dart:math';

void main() {
  for (int i = 0; i <= 100; i++) {
    final p = i / 100;
    print('$p, ${computeTotalProbability(p)}');
  }
}

double computeTotalProbability(double wheelProbability, [int wheelCount = 5]) {
  final possibleResults = getPossibleResults(wheelCount);

  // print("count: ${possibleResults.length}");

  // print(possibleResults);
  // print(possibleResults.where((result) => result.isWinning).length);

  var total = 0.0;
  var winningTotal = 0.0;
  for (final result in possibleResults) {
    final partial = result.probability(wheelProbability);
    // print("$result (${result.isWinning ? 'win' : 'lose'}) = $partial");
    total += partial;
    winningTotal += result.isWinning ? partial : 0;
  }

  // print(total);
  return winningTotal;
}

List<Result> getPossibleResults(int wheelCount) {
  final pools =
      List<List<bool>>.filled(wheelCount, const [true, false], growable: false);
  final set = product(pools);
  assert(
      set.length == pow(2, wheelCount), "The resulting set should be n ** r.");
  return set.map((result) => Result(result)).toList(growable: false);
}

/// Returns Cartesian product of a list of [pools].
/// https://en.wikipedia.org/wiki/Cartesian_product
Iterable<List<T>> product<T>(List<List<T>> pools) sync* {
  if (pools.length < 2) throw ArgumentError(pools);
  if (pools.length == 2) {
    for (final x in pools.first) {
      for (final y in pools.last) {
        yield [x, y];
      }
    }
    return;
  }

  for (final x in pools.first) {
    for (final y in product(pools.sublist(1))) {
      yield [x] + y;
    }
  }
}

class Result {
  final List<bool> wheelResults;

  const Result(this.wheelResults);

  bool get isWinning =>
      wheelResults.where((result) => result).length > wheelResults.length / 2;

  /// Probability that this exact result will be shown, given probability
  /// setting of each wheel.
  double probability(double wheelProbability) {
    double result = 1.0;
    for (final wheelResult in wheelResults) {
      if (wheelResult) {
        result *= wheelProbability;
      } else {
        result *= (1 - wheelProbability);
      }
    }
    return result;
  }

  @override
  String toString() => wheelResults.toString();
}

Add computation for a floating point wheel

Instead of slot reels (with a finite amount of Xs and Os), we are now using “wheels of fortune”. These can have any probability of success. We use them in a row of five, and we want to know what the probability is of them landing on a success with at least a 3:2 advantage.


@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    FORM_DIRECTIVES,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}

@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    formDirectives,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}

Replace FORM_DIRECTIVES with formDirectives in one of the tests, this seems to
work.

PiperOrigin-RevId: 163141550


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that dump-info has no effect on the compiler output.

import 'dart:io';

import 'package:path/path.dart' as path;
import 'package:expect/expect.dart';

import 'launch_helper.dart' show dart2JsCommand;

copyDirectory(Directory sourceDir, Directory destinationDir) {
  for (var element in sourceDir.listSync()) {
    if (element.path.endsWith('.git')) continue;
    String newPath =
        path.join(destinationDir.path, path.basename(element.path));
    if (element is File) {
      element.copySync(newPath);
    } else if (element is Directory) {
      Directory newDestinationDir = new Directory(newPath);
      newDestinationDir.createSync();
      copyDirectory(element, newDestinationDir);
    }
  }
}

void main() {
  Directory tmpDir = Directory.systemTemp.createTempSync('dump_info_test_');
  Directory out1 = new Directory.fromUri(tmpDir.uri.resolve('without'));
  out1.createSync();
  Directory out2 = new Directory.fromUri(tmpDir.uri.resolve('with'));
  out2.createSync();
  Directory sunflowerDir =
      new Directory.fromUri(Uri.base.resolve('third_party/sunflower'));

  print("Copying '${sunflowerDir.path}' to '${tmpDir.path}'.");
  copyDirectory(sunflowerDir, tmpDir);
  try {
    var command =
        dart2JsCommand(['--out=without/out.js', 'web/sunflower.dart']);
    print('Run $command');
    var result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output1 = new File.fromUri(tmpDir.uri.resolve('without/out.js'))
        .readAsStringSync();

    command = dart2JsCommand(
        ['--out=with/out.js', 'web/sunflower.dart', '--dump-info']);
    print('Run $command');
    result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output2 =
        new File.fromUri(tmpDir.uri.resolve('with/out.js')).readAsStringSync();

    print('Compare outputs...');
    Expect.equals(output1, output2);
    print('Done');
  } finally {
    print("Deleting '${tmpDir.path}'.");
    tmpDir.deleteSync(recursive: true);
  }
}

Add dump-info end to end test

Add dump-info end to end test

This test gives the same coverage we are getting from the mist-dump-info bots
today.

Change-Id: Ie6f7f8eba9b5de5c3983d9066aa29709ae4200a4
Reviewed-on: https://dart-review.googlesource.com/63541
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

class A implements B {
  var x;
  A(Object this.x);
}

class B {
  factory B(String s) = A;
}

main() {
  B(42 as dynamic); //# 01: runtime error
}

Test of dynamic argument type check for redirecting factories.

Verify that dynamic type checks are inserted to check arguments to
redirecting factories against the redirector, even when they would
be valid arguments to the redirectee.

Closes https://github.com/dart-lang/sdk/issues/31590

Change-Id: Ic439fd1e125ae8ae156e611402782413600de98e
Reviewed-on: https://dart-review.googlesource.com/71860
Reviewed-by: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Commit-Queue: Aske Simon Christensen <589eb3fd9a84f06d0ac46d3aa71dddcfb0814ccd@google.com>


/*
 * Package : dartivity_database
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 05/011/2015
 * Copyright :  S.Hamblett 2015
 */

part of dartivity_database;

class DartivityCache {
  /// The cache
  Map<String, dynamic> _cache;

  DartivityCache() {
    _cache = new Map<String, dynamic>();
  }

  /// get
  dynamic get(String key) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    } else {
      return null;
    }
  }

  /// put
  put(String key, dynamic resource) {
    _cache[key] = resource;
  }

  /// clear
  void clear() {
    _cache.clear();
  }
}

Add the general purpose cache

Add the general purpose cache


/// More Dart — Literally.
export 'package:more/async.dart';
export 'package:more/cache.dart';
export 'package:more/char_matcher.dart';
export 'package:more/collection.dart';
export 'package:more/hash.dart';
export 'package:more/iterable.dart';
export 'package:more/math.dart';
export 'package:more/number.dart';
export 'package:more/ordering.dart';
export 'package:more/printer.dart';
export 'package:more/tuple.dart';

Create a parent package that imports all extensions at once.


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test for type literals as compile-time constants.

class C<T> {
  void m() {
    const List lst = const [
                            T /// 01: compile-time error
                             ];
  }
}

main() {
  new C().m();
}

Add const type literal test.

Add const type literal test.

BUG=
R=karlklose@google.com

Review URL: https://codereview.chromium.org//25535009

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@28794 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for 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 is responsible for accepting the results of a map oepration
// and structuring it ready to be passed to the reducer

// This version performs the shuffling in memory and so is a potential scaling
// bottleneck
Map shuffle(List<Map> data) {
  Map results = {};
  for (Map kv in data) {
    assert(kv.length == 1);
    var key = kv.keys.first;
    var value = kv.values.first;

    results.putIfAbsent(key, () => []);
    results[key].add(value);
  }
  return results;
}

_main() {
  print (shuffle([{"a" : 1}, {"b" : 2}, {"a" : 2}]));
}

Add an in memory shuffler

Add an in memory shuffler


import 'dart:async';

import 'package:angular/angular.dart';
import 'package:http/http.dart';

import '../data_model/create_user_request.pb.dart';
import '../data_model/rule.pb.dart';

/// A class to interact with the Rules Builder server.
@Injectable()
class RuleService {
  /// The base URL of the Rules Builder server.
  static const serverUrl =
      'https://rules-server-dot-spreadsheet-dv360-plugin.uc.r.appspot.com';

  /// The endpoint for operations on users.
  static const usersEndpoint = '$serverUrl/users';

  /// The endpoint for operations on rules.
  static const rulesEndpoint = '$serverUrl/rules';

  /// Creates a user using the user's ID token and refresh token.
  Future<void> createUser(String idToken, String refreshToken) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    final createUserRequest = CreateUserRequest()..refreshToken = refreshToken;
    await post(usersEndpoint,
        body: createUserRequest.writeToBuffer(), headers: headers);
  }

  /// Creates a rule using the user's ID token and rule proto.
  Future<void> createRule(String idToken, Rule rule) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    await post(rulesEndpoint, body: rule.writeToBuffer(), headers: headers);
  }
}

Add rule service in client to interact with rule server


// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
library scissors.test.path_resolver_test;

import 'dart:async';
import 'dart:io';

import 'package:test/test.dart';
import 'package:scissors/src/utils/path_resolver.dart' show pathResolver;
import 'package:scissors/testing/transformer_test_utils.dart';

main() {
  if (Platform.environment['TRAVIS'] == 'true') {
    print("WARNING: Skipping path resolver tests on Travis.");
    return;
  }

  group('pathResolver', () {

    var executables = {
      'sassc': pathResolver.defaultSassCPath,
      'pngcrush': pathResolver.defaultPngCrushPath,
      'cssjanus': pathResolver.defaultCssJanusPath,
      'java': pathResolver.defaultJavaPath,
    };
    var files = {
      'jruby': pathResolver.defaultJRubyPath,
      'ruby sass': pathResolver.defaultRubySassPath,
      'closure': pathResolver.defaultClosureCompilerJarPath
    };
    var dirs = {
      'compass stylesheets': pathResolver.defaultCompassStylesheetsPath,
    };

    check(String kind, String name, String path, Future action(String resolved)) {
      if (path == null) {
        print("WARNING: No path set for $name.");
      } else {
        test('finds $kind $name ($path)', () async {
          var resolved = await pathResolver.resolvePath(path);
          await action(resolved);
        });
      }
    }

    executables.forEach((name, path) {
      check('executable', name, path, (resolved) async {
        expect(hasExecutable(resolved), true);
      });
    });
    files.forEach((name, path) {
      check('file', name, path, (resolved) async {
        expect(await new File(resolved).exists(), true);
      });
    });
    dirs.forEach((name, path) {
      check('directory', name, path, (resolved) async {
        expect(await new Directory(resolved).exists(), true);
      });
    });
  });
}

Add test for path resolution

Add test for path resolution


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';
import 'package:args/args.dart';
import 'package:http/http.dart' as http;
import 'package:source_maps/source_maps.dart';

ArgParser parser = new ArgParser()
  ..addFlag('inline',
      abbr: 'i',
      negatable: true,
      help: 'Inline untranslatable parts..',
      defaultsTo: false);

main(List<String> arguments) async {
  ArgResults options = parser.parse(arguments);

  if (options.rest.length != 1) {
    print('Usage: <script.dart> [<options>] <file or url for source map file>\n'
        'Options:\n'
        '${parser.usage}');
    exit(2);
  }

  String url = options.rest[0];
  String data;
  if (url.startsWith("http://") || url.startsWith("https://")) {
    data = (await http.get(url)).body;
  } else {
    data = new File(url).readAsStringSync();
  }

  SingleMapping sourceMap = parse(data);

  print("Now paste the stacktrace here. Finish with at least 3 empty lines...");

  int emptyInARow = 0;
  List<String> lines = [];
  while (true) {
    String line = stdin.readLineSync();
    if (line == null) break;
    if (line == "") {
      ++emptyInARow;
    } else {
      lines.add(line);
      emptyInARow = 0;
    }

    if (emptyInARow >= 3) break;
  }

  List<String> tailMessages = [];

  for (String line in lines) {
    Iterable<Match> ms = new RegExp(r"(\d+):(\d+)").allMatches(line);
    if (ms.isEmpty) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("Unparseable line: $line");
      }
      continue;
    }
    Match m = ms.first;
    int l = int.parse(m.group(1));
    int c = int.parse(m.group(2));
    SourceMapSpan span = sourceMap.spanFor(l, c);
    if (span?.start == null) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("No sourcemap entry for line line: $line");
      }
      continue;
    }
    print(span.start.toolString);
  }

  if (tailMessages.isNotEmpty) {
    print("");
    print("Messages:");
    print("");
    for (String line in tailMessages) {
      print(line);
    }
  }
}

Test tool: translate dart2js stacktrace

Test tool: translate dart2js stacktrace

This is a first stab at an internal tool that can translate a dart2js
stacktrace to a "dart stacktrace".

First use figuring out a stacktrace in observatory which was done like
this:

dart translate_dart2js_stacktrace.dart http://localhost:9999/main.dart.js.map
<then copy paste the stacktrace into stdin, followed by a few empty lines>

Change-Id: Id33e66182213a3005bba3338df7dd638218609c2
Reviewed-on: https://dart-review.googlesource.com/3140
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test for initialization of dispatchPropertyName.

import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native;

@Native("Foo")
class Foo {
  String method(String x) native;
}

makeFoo() native;

void setup() native r"""
function Foo() {}
Foo.prototype.method = function(x) { return 'Foo ' + x; }

self.makeFoo = function() { return new Foo(); }
""";

main() {
  setup();

  // If the dispatchPropertyName is uninitialized, it will be `undefined` or
  // `null` instead of the secret string or Symbol. These properties on
  // `Object.prototype` will be retrieved by the lookup instead of `undefined`
  // for the dispatch record.
  JS('', r'self.Object.prototype["undefined"] = {}');
  JS('', r'self.Object.prototype["null"] = {}');
  Expect.equals('Foo A', makeFoo().method('A'));

  // Slightly different version that has malformed dispatch records.
  JS('', r'self.Object.prototype["undefined"] = {p: false}');
  JS('', r'self.Object.prototype["null"] = {p: false}');
  Expect.equals('Foo B', makeFoo().method('B'));
}

Add another test for initializing dispatchPropertyName that runs outside the browser

R=johnniwinther@google.com

BUG=

Review URL: https://codereview.chromium.org/2359023002 .