part of kafka.common;

/// Represents single node in a Kafka cluster.
class Broker {
  /// Unique ID of this broker within cluster.
  final int id;

  /// Host name or IP address of this broker.
  final String host;

  /// Port number of this broker.
  final int port;

  static final Map<String, Broker> _instances = new Map();

  /// Creates new instance of Kafka broker.
  factory Broker(int id, String host, int port) {
    var key = '${host}:${port}';
    if (!_instances.containsKey(key)) {
      _instances[key] = new Broker._(id, host, port);
    } else {
      if (_instances[key].id != id) throw new StateError('Broker ID mismatch.');
    }

    return _instances[key];
  }

  Broker._(this.id, this.host, this.port);
}

class TopicPartition {
  final String topicName;
  final int partitionId;

  static final Map<String, TopicPartition> _cache = new Map();

  TopicPartition._(this.topicName, this.partitionId);

  factory TopicPartition(String topicName, int partitionId) {
    var key = topicName + partitionId.toString();
    if (!_cache.containsKey(key)) {
      _cache[key] = new TopicPartition._(topicName, partitionId);
    }

    return _cache[key];
  }

  @override
  bool operator ==(TopicPartition other) {
    return (other.topicName == topicName && other.partitionId == partitionId);
  }

  @override
  int hashCode() {
    return (topicName + partitionId.toString()).hashCode;
  }
}

part of kafka.common;

/// Represents single node in a Kafka cluster.
class Broker {
  /// Unique ID of this broker within cluster.
  final int id;

  /// Host name or IP address of this broker.
  final String host;

  /// Port number of this broker.
  final int port;

  static final Map<String, Broker> _instances = new Map();

  /// Creates new instance of Kafka broker.
  factory Broker(int id, String host, int port) {
    var key = '${host}:${port}';
    if (!_instances.containsKey(key)) {
      _instances[key] = new Broker._(id, host, port);
    } else {
      if (_instances[key].id != id) throw new StateError('Broker ID mismatch.');
    }

    return _instances[key];
  }

  Broker._(this.id, this.host, this.port);
}

class TopicPartition {
  final String topicName;
  final int partitionId;

  static final Map<String, TopicPartition> _cache = new Map();

  TopicPartition._(this.topicName, this.partitionId);

  factory TopicPartition(String topicName, int partitionId) {
    var key = topicName + partitionId.toString();
    if (!_cache.containsKey(key)) {
      _cache[key] = new TopicPartition._(topicName, partitionId);
    }

    return _cache[key];
  }

  @override
  bool operator ==(TopicPartition other) {
    return (other.topicName == topicName && other.partitionId == partitionId);
  }

  @override
  int get hashCode => (topicName + partitionId.toString()).hashCode;
}

Fix for hasCode to be a getter instead of regular method in TopicPartition


// 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 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: ['tab_button.scss.css'],
  directives: [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive = false;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;

  @HostBinding('attr.disabled')
  String get hostDisabled => disabled ? "" : null;
}

// 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 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: ['tab_button.scss.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  directives: [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive = false;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;

  @HostBinding('attr.disabled')
  String get hostDisabled => disabled ? "" : null;
}

Change TabButton to be OnPush as it is used in an OnPush context, and there is no reason why it can't be OnPush.

PiperOrigin-RevId: 242756270


/// Creates a symlink to the reflectable package next to this package.
import "dart:io";

void main(List<String> args) {
  String projectRoot = args[0];
  // If projectRoot is relative we want to make it absolute, so the link
  // will be to an absolute location.
  Uri currentPathUri = new Uri.file(Directory.current.path +
                                    Platform.pathSeparator);
  Uri projectRootUri = currentPathUri.resolve(projectRoot);
  Uri reflectableLocation = projectRootUri.resolve(
      "../../../../../dart/third_party/pkg/reflectable/reflectable");
  Uri destination = projectRootUri.resolve("../reflectable/reflectable");
  print("Making a link to ${reflectableLocation.toFilePath()} "
        "at ${destination.toFilePath()}");
  new Link.fromUri(destination).create(reflectableLocation.toFilePath());
}

/// Creates a symlink to the reflectable package next to this package.
import "dart:io";

void main(List<String> args) {
  String projectRoot = args[0];
  // If projectRoot is relative we want to make it absolute, so the link
  // will be to an absolute location.
  Uri currentPathUri = new Uri.file(Directory.current.path +
                                    Platform.pathSeparator);
  Uri projectRootUri = currentPathUri.resolve(projectRoot);
  Uri reflectableLocation = projectRootUri.resolve(
      "../../../../../dart/third_party/pkg/reflectable/reflectable");
  Uri destination = projectRootUri.resolve("../reflectable/reflectable");
  print("Making a link to ${reflectableLocation.toFilePath()} "
        "at ${destination.toFilePath()}");
  bool exists = new Directory(reflectableLocation.toFilePath()).existsSync();
  print("Target exists: $exists");
  new Link.fromUri(destination).create(reflectableLocation.toFilePath());
}

Add diagnostic to see if the target of the created link exists.

BUG=
R=eernst@google.com

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


import 'package:ddays/task.dart';
import "package:test/test.dart";

void main() {
  test('task gets initialised correctly', () {
    var t1 = new Task('task1',null);
    expect(t1.summary, 'task1');
    var t2 = new Task('task2', new DateTime(2015,1,1));
    expect(t2.scheduled.month, 1);
  });
  test('addNote should add notes to tasknotes list.', () {
    var t1 = new Task('task1', null);
    t1.addNote('first note');
    expect(t1.tasknotes[0], 'first note');
  });

}

import 'package:ddays/task.dart';
import "package:test/test.dart";

void main() {
  test('task gets initialised correctly', () {
    var t1 = new Task('task1',null);
    expect(t1.summary, 'task1');
    var t2 = new Task('task2', new DateTime(2015,1,1));
    expect(t2.scheduled.month, 1);
  });
  test('addNote should add notes to tasknotes list.', () {
    var t1 = new Task('task1', null);
       var n1 = new TaskNote('first note');
       t1.addNote(n1);
       expect(t1.tasknotes[0].notebody, 'first note');
  });

}

Refactor test for addNote function.

Refactor test for addNote function.


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for 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 write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 12345; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for 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 write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Decrease size of test of write barrier verification.

It was close to timing out on Linux, and failing on Windows, likely due to OOM.

TBR=iposva@google.com

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

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


part of hop_runner;

Map<String, dynamic> config;

Directory get tool_dir => new File.fromUri(Platform.script).parent.absolute;
Directory get root_dir => tool_dir.parent;

Map<String, dynamic> load_config() => loadYaml(new File("${tool_dir.path}/build.yaml").readAsStringSync());

Map<String, dynamic> variables = {
  "tool_dir": tool_dir.path,
  "root_dir": root_dir.path
};

String parse_config_value(String input) {
  var out = input;
  for (var variable in variables.keys) {
    out = out.replaceAll("{${variable}}", variables[variable]);
  }
  return out;
}

dynamic getvar(String path, [dynamic defaultValue = false]) {
  var current = config;

  if (current.containsKey(path)) {
    return current[path];
  }

  var parts = path.split(r"\.");
  for (var part in parts) {
    if (current == null) {
      return null;
    }
    current = current[part];
  }
  if (current is String) {
    current = parse_config_value(current);
  }
  return current;
}

void init() {
  Directory.current = root_dir;
  config = load_config();
}

part of hop_runner;

Map<String, dynamic> config;

Directory get tool_dir => new File.fromUri(Platform.script).parent.absolute;
Directory get root_dir => tool_dir.parent;

Map<String, dynamic> load_config() {
  var it = loadYaml(new File("${tool_dir.path}/build.yaml").readAsStringSync());
  if (it.containsKey("variables")) {
    variables.addAll(it["variables"]);
  }
  return it;
}

Map<String, dynamic> variables = {
  "tool_dir": tool_dir.path,
  "root_dir": root_dir.path
};

String parse_config_value(String input) {
  var out = input;
  for (var variable in variables.keys) {
    out = out.replaceAll("{${variable}}", variables[variable]);
  }
  return out;
}

dynamic getvar(String path, [dynamic defaultValue = false]) {
  var current = config;

  if (current.containsKey(path)) {
    return current[path];
  }

  var parts = path.split(r"\.");
  for (var part in parts) {
    if (current == null) {
      return null;
    }
    current = current[part];
  }
  if (current is String) {
    current = parse_config_value(current);
  }
  return current;
}

void init() {
  Directory.current = root_dir;
  config = load_config();
}

Add Variables Support in Configuration

Build: Add Variables Support in Configuration


part of darwin;

class Generation<T extends Phenotype> {
  List<T> members = new List<T>();

  /**
   * Filters the generation to phenotypes that are similar to [ph] as defined
   * by their Hamming distance being less than [radius].
   *
   * This _includes_ the original [ph] (Because [ph]'s Hamming distance to
   * itself is [:0:].)
   */
  Iterable<T> getSimilarPhenotypes(T ph, num radius) {
    return members
        .where((T candidate) => ph.computeHammingDistance(candidate) < radius);
  }

  num cummulativeFitness;
  num get averageFitness {
    if (cummulativeFitness == null) return null;
    return cummulativeFitness / members.length;
  }
  num bestFitness;

  /**
   * Computes [cummulativeFitness] and [bestFitness], assuming all members of
   * the population are scored.
   */
  void computeSummary() {
    cummulativeFitness = 0;
    bestFitness = double.INFINITY;
    members.forEach((T ph) {
      cummulativeFitness += ph.result;
      if (ph.result < bestFitness) bestFitness = ph.result;
    });
  }
}

part of darwin;

class Generation<T extends Phenotype> {
  List<T> members = new List<T>();

  /**
   * Filters the generation to phenotypes that are similar to [ph] as defined
   * by their Hamming distance being less than [radius].
   *
   * This _includes_ the original [ph] (Because [ph]'s Hamming distance to
   * itself is [:0:].)
   */
  Iterable<T> getSimilarPhenotypes(T ph, num radius) {
    return members
        .where((T candidate) => ph.computeHammingDistance(candidate) < radius);
  }

  num cummulativeFitness;
  num get averageFitness {
    if (cummulativeFitness == null) return null;
    return cummulativeFitness / members.length;
  }
  num bestFitness;

  /**
   * Computes [cummulativeFitness] and [bestFitness], assuming all members of
   * the population are scored.
   */
  void computeSummary() {
    cummulativeFitness = 0;
    bestFitness = double.INFINITY;
    members.forEach((T ph) {
      cummulativeFitness += ph.result;
      if (ph.result < bestFitness) {
        bestFitness = ph.result;
        best = ph;
      }
    });
  }

  T best;
}

Add best phenotype to Generation as a field


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

part of dart.ffi;

/// This class is extended to define structs.
///
/// Fields in a struct, annotated with a subtype of [NativeType], are
/// automatically transformed into wrappers to access the fields of the struct
/// in native memory.
///
/// All fields in a struct must either have a type which extends [NativeType] or
/// else have an annotation indicating the corresponding native type (e.g.
/// "@Int32()" for "int").
///
/// Instances of a subclass of [Struct] have reference semantics and are backed
/// by native memory. The may allocated via allocation or loaded from a
/// [Pointer], but not by a generative constructor.
abstract class Struct extends NativeType {
  final Pointer<Struct> _addressOf;

  /// Construct a reference to the [nullptr].
  ///
  /// Use [StructPointer]'s `.ref` to gain references to native memory backed
  /// structs.
  Struct() : _addressOf = nullptr;

  Struct._fromPointer(this._addressOf);
}

/// Extension on [Struct] specialized for it's subtypes.
extension StructAddressOf<T extends Struct> on T {
  /// Returns the address backing the reference.
  Pointer<T> get addressOf => _addressOf as Pointer<T>;
}

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

part of dart.ffi;

/// This class is extended to define structs.
///
/// Fields in a struct, annotated with a subtype of [NativeType], are
/// automatically transformed into wrappers to access the fields of the struct
/// in native memory.
///
/// All fields in a struct must either have a type which extends [NativeType] or
/// else have an annotation indicating the corresponding native type (e.g.
/// "@Int32()" for "int").
///
/// Instances of a subclass of [Struct] have reference semantics and are backed
/// by native memory. The may allocated via allocation or loaded from a
/// [Pointer], but not by a generative constructor.
abstract class Struct extends NativeType {
  final Pointer<Struct> _addressOf;

  /// Construct a reference to the [nullptr].
  ///
  /// Use [StructPointer]'s `.ref` to gain references to native memory backed
  /// structs.
  Struct() : _addressOf = nullptr;

  Struct._fromPointer(this._addressOf);
}

/// Extension on [Struct] specialized for its subtypes.
extension StructAddressOf<T extends Struct> on T {
  /// Returns the address backing the reference.
  Pointer<T> get addressOf => _addressOf as Pointer<T>;
}

Fix spelling in ffi documentation

[vm/ffi] Fix spelling in ffi documentation

Fix spelling nit (it's -> its).

Closes https://github.com/dart-lang/sdk/pull/43483
https://github.com/dart-lang/sdk/pull/43483

GitOrigin-RevId: 5bc63e70f3846b131ea25dcdb81c6a66929f995b
Change-Id: I13d3a42896412d1111e9b9882911ade8bb7623a1
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/163362
Reviewed-by: Daco Harkes <930cbae0ca77f1954c53e32620d89cfcca318f00@google.com>
Commit-Queue: Daco Harkes <930cbae0ca77f1954c53e32620d89cfcca318f00@google.com>


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

enum IconThemeColor { white, black }

class IconThemeData {
  const IconThemeData({ this.color });
  final IconThemeColor color;

  bool operator ==(dynamic other) {
    if (other is! IconThemeData)
      return false;
    final IconThemeData typedOther = other;
    return color == typedOther;
  }

  int get hashCode => color.hashCode;

  String toString() => '$color';
}

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

enum IconThemeColor { white, black }

class IconThemeData {
  const IconThemeData({ this.color });
  final IconThemeColor color;

  bool operator ==(dynamic other) {
    if (other is! IconThemeData)
      return false;
    final IconThemeData typedOther = other;
    return color == typedOther.color;
  }

  int get hashCode => color.hashCode;

  String toString() => '$color';
}

Fix a type mismatch in IconThemeData.operator==


import 'dart:html';
import 'package:angular2/core.dart';
import 'package:intl/intl.dart';

@Component(
  selector: 'datepicker',
  templateUrl: 'datepicker_component.html',
  styleUrls: const['datepicker_component.css']
)

class DatepickerComponent implements OnInit{

  @Input() String componentId;

  String datepickerId;
  String initialDate;
  DateFormat dateFormat = new DateFormat("yyyy-MM-dd");
  bool hidden = true;

  @override
  void ngOnInit() {
    datepickerId = componentId+"-datepicker";
    var now = new DateTime.now();
    initialDate = dateFormat.format(now);
  }

  void toggleDatepicker() {
    if (hidden) {
      showDatepicker();
    } else {
      hideDatepicker();
    }
  }

  void showDatepicker() {
    document.getElementById(datepickerId).classes.remove("hide");
    hidden = false;
    document.getElementById(componentId).querySelector("input").focus();
  }

  void hideDatepicker() {
    document.getElementById(datepickerId).classes.add("hide");
    hidden = true;
  }

}

import 'dart:html';
import 'package:angular2/core.dart';
import 'package:intl/intl.dart';
import 'day_component.dart';

@Component(
  selector: 'datepicker',
  templateUrl: 'datepicker_component.html',
  styleUrls: const['datepicker_component.css'],
  directives: const[DayComponent]
)

class DatepickerComponent implements OnInit, AfterContentInit, AfterViewInit{

  @Input() String componentId;

  String datepickerId;
  String initialDate;
  DateFormat dateFormat = new DateFormat("yyyy-MM-dd");
  bool hidden = true;
  InputElement inputDate;

  ElementRef _elementRef;
  Element hostElement;

  @ViewChildren(DayComponent) List<DayComponent> dayList;

  DatepickerComponent(this._elementRef);

  @override
  void ngOnInit() {
    datepickerId = componentId+"-datepicker";
    var now = new DateTime.now();
    initialDate = dateFormat.format(now);
  }

  @override
  void ngAfterContentInit() {
    hostElement = _elementRef.nativeElement;
    inputDate = hostElement.querySelector('input') as InputElement;
  }

  @override
  void ngAfterViewInit() {
    for (var day in dayList) {
      day.hostElement.onClick.listen((event) => dateClickListener(day, event));
    }
  }

  void dateClickListener(DayComponent currentDay, Event event) {
    for (var day in dayList) {
      if (day.isSelected) {
        day.deselect();
        break;
      }
    }
    currentDay.select();
    inputDate.value = dateFormat.format(currentDay.date);
  }

  void toggleDatepicker() {
    if (hidden) {
      showDatepicker();
    } else {
      hideDatepicker();
    }
  }

  void showDatepicker() {
    hostElement.querySelector("#$datepickerId").classes.remove("hide");
    hidden = false;
    inputDate.focus();
  }

  void hideDatepicker() {
    hostElement.querySelector("#$datepickerId").classes.add("hide");
    hidden = true;
  }

}

Add click listener to day module.

Add click listener to day module.


import '../enums/attribute_type.dart';
import '../utils/token.dart';

/// Immutable external ID .
class DtdExternalId {
  DtdExternalId.public(String this.publicId, XmlAttributeType this.publicIdType,
      this.systemId, this.systemIdType);

  DtdExternalId.system(this.systemId, this.systemIdType)
      : publicId = null,
        publicIdType = null;

  /// The public identifier for the external subset of the document type
  /// definition. This is a string, or `null`.
  final String? publicId;

  final XmlAttributeType? publicIdType;

  /// The system identifier for the external subset of the document type
  /// definition. This is a URI as a string, or `null`.
  final String systemId;

  final XmlAttributeType systemIdType;

  @override
  String toString() {
    final buffer = StringBuffer();
    if (publicId != null) {
      buffer.write(XmlToken.doctypePublicId);
      buffer.write(XmlToken.whitespace);
      buffer.write(publicIdType!.token);
      buffer.write(publicId);
      buffer.write(publicIdType!.token);
    } else {
      buffer.write(XmlToken.doctypeSystemId);
    }
    buffer.write(XmlToken.whitespace);
    buffer.write(systemIdType.token);
    buffer.write(systemId);
    buffer.write(systemIdType.token);
    return buffer.toString();
  }

  @override
  int get hashCode => Object.hash(systemId, publicId);

  @override
  bool operator ==(Object other) =>
      other is DtdExternalId &&
      other.publicId == other.publicId &&
      other.systemId == other.systemId;
}

import '../enums/attribute_type.dart';
import '../utils/token.dart';

/// Immutable external ID.
class DtdExternalId {
  DtdExternalId.public(String this.publicId, XmlAttributeType this.publicIdType,
      this.systemId, this.systemIdType);

  DtdExternalId.system(this.systemId, this.systemIdType)
      : publicId = null,
        publicIdType = null;

  /// The public identifier for the external subset of the document type
  /// definition. This is a string, or `null`.
  final String? publicId;

  final XmlAttributeType? publicIdType;

  /// The system identifier for the external subset of the document type
  /// definition. This is a URI as a string, or `null`.
  final String systemId;

  final XmlAttributeType systemIdType;

  @override
  String toString() {
    final buffer = StringBuffer();
    if (publicId != null) {
      buffer.write(XmlToken.doctypePublicId);
      buffer.write(XmlToken.whitespace);
      buffer.write(publicIdType!.token);
      buffer.write(publicId);
      buffer.write(publicIdType!.token);
    } else {
      buffer.write(XmlToken.doctypeSystemId);
    }
    buffer.write(XmlToken.whitespace);
    buffer.write(systemIdType.token);
    buffer.write(systemId);
    buffer.write(systemIdType.token);
    return buffer.toString();
  }

  @override
  int get hashCode => Object.hash(systemId, publicId);

  @override
  bool operator ==(Object other) =>
      other is DtdExternalId &&
      other.publicId == other.publicId &&
      other.systemId == other.systemId;
}

Fix comment of External ID.

Fix comment of External ID.


import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

final examplesToSync = <List<String>>[
  <String>[
    'public/docs/_examples/template-syntax/dart',
    'git@github.com:angular-examples/template-syntax.git'
  ]
];

/// Syncs all angular.io example applications.
Future main(List<String> args) async {
  for (List<String> example in examplesToSync) {
    await syncer.main(example..addAll(args));
  }
}

import 'dart:async';

import 'package:dart_doc_syncer/documentation_updater.dart';

/// Syncs all angular.io example applications.
Future main() async {
  for (List<String> example in _examplesToSync) {
    try {
      final documentation = new DocumentationUpdater();
      await documentation.updateRepository(example[0], example[1]);
    } catch (e, stacktrace) {
      print('Error: $e, \nCause: $stacktrace');
    }
  }
}

final _examplesToSync = <List<String>>[
  <String>[
    'public/docs/_examples/template-syntax/dart',
    'git@github.com:angular-examples/template-syntax.git'
  ],
  <String>[
    'public/docs/_examples/pipes/dart',
    'git@github.com:angular-examples/pipes.git'
  ],
  <String>[
    'public/docs/_examples/server-communication/dart',
    'git@github.com:angular-examples/server-communication.git'
  ],
  <String>[
    'public/docs/_examples/quickstart/dart',
    'git@github.com:angular-examples/quickstart.git'
  ],
  <String>[
    'public/docs/_examples/displaying-data/dart',
    'git@github.com:angular-examples/displaying-data.git'
  ],
  <String>[
    'public/docs/_examples/forms/dart',
    'git@github.com:angular-examples/forms.git'
  ],
  <String>[
    'public/docs/_examples/hierarchical-dependency-injection/dart',
    'git@github.com:angular-examples/hierarchical-dependency-injection.git'
  ],
  <String>[
    'public/docs/_examples/dependency-injection/dart',
    'git@github.com:angular-examples/dependency-injection.git'
  ],
  <String>[
    'public/docs/_examples/attribute-directives/dart',
    'git@github.com:angular-examples/attribute-directives.git'
  ],
  <String>[
    'public/docs/_examples/architecture/dart',
    'git@github.com:angular-examples/architecture.git'
  ],
];

Add more repositories to sync.

Add more repositories to sync.


part of stream_transformers;

Stream _bindStream({Stream like, StreamSubscription onListen(EventSink sink), onCancel()}) {
  StreamSubscription subscription;
  StreamController controller;

  controller = _createControllerLikeStream(
      stream: like,
      onListen: () => subscription = onListen(controller),
      onPause: () => subscription.pause(),
      onResume: () => subscription.resume(),
      onCancel: () {
        var futures = [onCancel, subscription.cancel]
            .where((function) => function != null)
            .map((function) => function())
            .where((future) => future != null);
        return Future.wait(futures);
      });

  return controller.stream;
}

StreamController _createControllerLikeStream({Stream stream, void onListen(), void onCancel(), void onPause(), void onResume()}) {
  if (stream == null || !stream.isBroadcast) {
    return new StreamController(onListen: onListen, onCancel: onCancel, onPause: onPause, onResume: onResume);
  } else {
    return new StreamController.broadcast(onListen: onListen, onCancel: onCancel);
  }
}

Future _cancelSubscriptions(Iterable<StreamSubscription> subscriptions) {
  var futures = subscriptions
      .map((subscription) => subscription.cancel())
      .where((future) => future != null);
  return Future.wait(futures);
}

part of stream_transformers;

Stream _bindStream({Stream like, StreamSubscription onListen(EventSink sink), onCancel(), bool sync: false}) {
  StreamSubscription subscription;
  StreamController controller;

  controller = _createControllerLikeStream(
      stream: like,
      sync: sync,
      onListen: () => subscription = onListen(controller),
      onPause: () => subscription.pause(),
      onResume: () => subscription.resume(),
      onCancel: () {
        var futures = [onCancel, subscription.cancel]
            .where((function) => function != null)
            .map((function) => function())
            .where((future) => future != null);
        return Future.wait(futures);
      });

  return controller.stream;
}

StreamController _createControllerLikeStream({Stream stream, void onListen(), void onCancel(), void onPause(), void onResume(), bool sync: false}) {
  if (stream == null || !stream.isBroadcast) {
    return new StreamController(onListen: onListen, onCancel: onCancel, onPause: onPause, onResume: onResume, sync: sync);
  } else {
    return new StreamController.broadcast(onListen: onListen, onCancel: onCancel, sync: sync);
  }
}

Future _cancelSubscriptions(Iterable<StreamSubscription> subscriptions) {
  var futures = subscriptions
      .map((subscription) => subscription.cancel())
      .where((future) => future != null);
  return Future.wait(futures);
}

Allow creation of sync streams from internal stream factories


// 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 'dart:mirrors';
import 'package:lookup_map/lookup_map.dart'; // accessed via mirrors;
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

/// This dartdoc helps remove a warning for the unused import on [LookupMap].
main() {
  test('validate version number matches', () {
    var pubspecPath = Platform.script.resolve('../pubspec.yaml').path;
    var yaml = loadYaml(new File(pubspecPath).readAsStringSync());
    var version1 = yaml['version'];
    var library = currentMirrorSystem().findLibrary(#lookup_map);
    var version2 = library.getField(new Symbol('_version')).reflectee;
    expect(version1, version2);
  });
}

// 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 'dart:mirrors';
import 'package:lookup_map/lookup_map.dart'; // accessed via mirrors;
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

/// This dartdoc helps remove a warning for the unused import on [LookupMap].
main() {
  test('validate version number matches', () {
    var pubspec = Platform.script.resolve('../pubspec.yaml');
    var yaml = loadYaml(new File.fromUri(pubspec).readAsStringSync());
    var version1 = yaml['version'];
    var library = currentMirrorSystem().findLibrary(#lookup_map);
    var version2 = library.getField(new Symbol('_version')).reflectee;
    expect(version1, version2);
  });
}

Fix conversion from Uri to File in test, to use File.fromUri().

BUG=
R=wibling@google.com

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


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for 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 write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for 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 write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Reduce live size of test of write barrier verification.

TBR=iposva@google.com

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

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


library generated_getter_setter_spec;

import '../../_specs.dart';
import 'parser_spec.dart' as parser_spec;
import 'generated_getter_setter.dart';

main() {
  describe('hybrid getter-setter', () {
    beforeEach(module((Module module) {
      module.type(Parser, implementedBy: DynamicParser);
      module.type(ClosureMap, implementedBy: StaticClosureMap);
    }));
    //parser_spec.main();
  });
}

library generated_getter_setter_spec;

import '../../_specs.dart';
import 'parser_spec.dart' as parser_spec;
import 'generated_getter_setter.dart';

main() {
  describe('hybrid getter-setter', () {
    beforeEach(module((Module module) {
      module.type(Parser, implementedBy: DynamicParser);
      module.type(ClosureMap, implementedBy: StaticClosureMap);
    }));
    parser_spec.main();
  });
}

chore(parser): Enable parser tests using the generated hybrid parser.


// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_console_client library.
library dartbase_console_client;

import 'package:console/console.dart';
import 'package:dartbase_server/gamelogic.dart';

class LocalConsoleClient {
  final int numPlayers;
  Game _game;
  LocalConsoleClient(this.numPlayers){
    _game = new Game();
    for (var i = 1; i <= numPlayers; i++) {
      _game.addPlayer("Player${i}");
    }
    _game.startGame();

  }

}

void printBoard(Board board, BoardLoc viewLoc){
  var canvas = new Canvas(120, 48);

  if(board.contains(viewLoc)){
    _drawLoc(canvas, board[viewLoc], 60, 25);
  }

  print(canvas.frame());
}

void _drawLoc(Canvas canvas, PlayedCard pc, int viewX, int viewY){
  canvas.set(viewX, viewY);
}

// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_console_client library.
library dartbase_console_client;

import 'package:console/console.dart';
import 'package:dartbase_server/gamelogic.dart';

part 'print.dart';

class LocalConsoleClient {
  final int numPlayers;
  Game _game;
  LocalConsoleClient(this.numPlayers){
    _game = new Game();
    for (var i = 1; i <= numPlayers; i++) {
      _game.addPlayer("Player${i}");
    }
    _game.startGame();

  }

}

Add print part, remove print methods

Add print part, remove print methods


part of '../../pay.dart';

typedef PayGestureTapCallback = void Function(Pay client);

class GooglePayButtonWidget extends StatelessWidget {
  final Pay _googlePayClient;
  final GooglePayButton _googlePayButton;

  final Widget _childOnError;
  final Widget _loadingIndicator;

  GooglePayButtonWidget._(
    Key key,
    this._googlePayClient,
    this._googlePayButton,
    this._childOnError,
    this._loadingIndicator,
  ) : super(key: key);

  factory GooglePayButtonWidget({
    Key key,
    @required paymentConfigurationAsset,
    @required PayGestureTapCallback onPressed,
    type,
    color,
    childOnError,
    loadingIndicator,
  }) {
    Pay googlePayClient = Pay.fromAsset(paymentConfigurationAsset);
    GooglePayButton googlePayButton = GooglePayButton(
      onPressed: () => onPressed(googlePayClient),
      type: type,
      color: color,
    );

    return GooglePayButtonWidget._(
      key,
      googlePayClient,
      googlePayButton,
      childOnError,
      loadingIndicator,
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: _googlePayClient.userCanPay(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == true) {
            return SizedBox(
              width: double.infinity,
              child: _googlePayButton,
            );
          } else if (snapshot.hasError) {
            return _childOnError ?? SizedBox.shrink();
          }
        }

        return _loadingIndicator ?? SizedBox.shrink();
      },
    );
  }
}

part of '../../pay.dart';

typedef PayGestureTapCallback = void Function(Pay client);

class GooglePayButtonWidget extends StatelessWidget {
  final Pay _googlePayClient;
  final GooglePayButton _googlePayButton;

  final Widget _childOnError;
  final Widget _loadingIndicator;

  GooglePayButtonWidget._(
    Key key,
    this._googlePayClient,
    this._googlePayButton,
    this._childOnError,
    this._loadingIndicator,
  ) : super(key: key);

  factory GooglePayButtonWidget({
    Key key,
    @required paymentConfigurationAsset,
    @required PayGestureTapCallback onPressed,
    type,
    color,
    childOnError,
    loadingIndicator,
  }) {
    Pay googlePayClient = Pay.fromAsset(paymentConfigurationAsset);
    GooglePayButton googlePayButton = GooglePayButton(
      onPressed: () => onPressed(googlePayClient),
      type: type,
      color: color,
    );

    return GooglePayButtonWidget._(
      key,
      googlePayClient,
      googlePayButton,
      childOnError,
      loadingIndicator,
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: _googlePayClient.userCanPay(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == true) {
            return _googlePayButton;
          } else if (snapshot.hasError) {
            return _childOnError ?? SizedBox.shrink();
          }
        }

        return _loadingIndicator ?? SizedBox.shrink();
      },
    );
  }
}

Remove sizing opinion on the widget

Remove sizing opinion on the widget


// 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 'box.dart';
import 'object.dart';

class StatisticsBox extends RenderBox {

  StatisticsBox({int optionsMask: 0, int rasterizerThreshold: 0})
    : _optionsMask = optionsMask,
      _rasterizerThreshold = rasterizerThreshold;

  int _optionsMask;
  int get optionsMask => _optionsMask;
  void set optionsMask (int mask) {
    if (mask == _optionsMask) {
      return;
    }
    _optionsMask = mask;
    markNeedsPaint();
  }

  int _rasterizerThreshold;
  int get rasterizerThreshold => _rasterizerThreshold;
  void set rasterizerThreshold (int threshold) {
    if  (threshold == _rasterizerThreshold) {
      return;
    }
    _rasterizerThreshold = threshold;
    markNeedsPaint();
  }

  bool get sizedByParent => true;

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.minWidth;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.maxWidth;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.minHeight;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.maxHeight;
  }

  void performResize() {
    size = constraints.constrain(Size.infinite);
  }

  void paint(PaintingContext context, Offset offset) {
    context.paintStatistics(optionsMask, rasterizerThreshold, offset, size);
  }
}

// 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 'box.dart';
import 'object.dart';

class StatisticsBox extends RenderBox {

  StatisticsBox({int optionsMask: 0, int rasterizerThreshold: 0})
    : _optionsMask = optionsMask,
      _rasterizerThreshold = rasterizerThreshold;

  int _optionsMask;
  int get optionsMask => _optionsMask;
  void set optionsMask (int mask) {
    if (mask == _optionsMask) {
      return;
    }
    _optionsMask = mask;
    markNeedsPaint();
  }

  int _rasterizerThreshold;
  int get rasterizerThreshold => _rasterizerThreshold;
  void set rasterizerThreshold (int threshold) {
    if  (threshold == _rasterizerThreshold) {
      return;
    }
    _rasterizerThreshold = threshold;
    markNeedsPaint();
  }

  bool get sizedByParent => true;

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.minWidth;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.maxWidth;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.minHeight;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.maxHeight;
  }

  void performResize() {
    size = constraints.biggest;
  }

  void paint(PaintingContext context, Offset offset) {
    context.paintStatistics(optionsMask, rasterizerThreshold, offset, size);
  }
}

Remove an infinity in layout code.

Remove an infinity in layout code.


// 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:expect/expect.dart";
import "dart:async";
import "dart:io";
import "dart:isolate";

void testPauseList() {
  var keepAlive = new ReceivePort();
  new Directory("").createTemp().then((d) {
    // Linux reads 2K at a time.
    int total = 2 * 1024 + 1;
    for (int i = 0; i < total; i++) {
      new File("${d.path}/$i").createSync();
    }
    bool first = true;
    var subscription;
    int count = 0;
    subscription = d.list().listen((file) {
      if (first) {
        first = false;
        subscription.pause();
        Timer.run(() {
          for (int i = 0; i < total; i++) {
            new File("${d.path}/$i").deleteSync();
          }
          subscription.resume();
        });
      }
      count++;
    }, onDone: () {
      Expect.isTrue(count < total);
      keepAlive.close();
      d.delete().then((ignore) => keepAlive.close());
    });
  });
}

void main() {
  testPauseList();
}

// 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:expect/expect.dart";
import "dart:async";
import "dart:io";
import "dart:isolate";

void testPauseList() {
  var keepAlive = new ReceivePort();
  new Directory("").createTemp().then((d) {
    // Linux reads 2K at a time, so be sure to be >>.
    int total = 4 * 1024 + 1;
    for (int i = 0; i < total; i++) {
      new File("${d.path}/$i").createSync();
    }
    bool first = true;
    var subscription;
    int count = 0;
    subscription = d.list().listen((file) {
      if (first) {
        first = false;
        subscription.pause();
        Timer.run(() {
          for (int i = 0; i < total; i++) {
            new File("${d.path}/$i").deleteSync();
          }
          subscription.resume();
        });
      }
      count++;
    }, onDone: () {
      Expect.notEquals(total, count);
      keepAlive.close();
      d.delete().then((ignore) => keepAlive.close());
    });
  });
}

void main() {
  testPauseList();
}

Increase number of files created, to avoid flakyness on linux.

BUG=

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

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@24084 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.

library barback.test.package_graph.transform_test;

import 'package:barback/src/utils.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../utils.dart';

main() {
  initConfig();

  test("handles many parallel transformers", () {
    var files = new List.generate(100, (i) => "app|$i.txt");
    var rewrite = new RewriteTransformer("txt", "out");
    initGraph(files, {"app": [[rewrite]]});

    // Pause and resume apply to simulate parallel long-running transformers.
    rewrite.pauseApply();
    updateSources(files);
    schedule(pumpEventQueue);
    rewrite.resumeApply();

    for (var i = 0; i < 100; i++) {
      expectAsset("app|$i.out", "$i.out");
    }
    buildShouldSucceed();

    expect(rewrite.maxParallelRuns, completion(equals(10)));
  });
}

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

library barback.test.package_graph.transform_test;

import 'package:barback/src/utils.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../utils.dart';

main() {
  initConfig();

  test("handles many parallel transformers", () {
    currentSchedule.timeout *= 3;
    var files = new List.generate(100, (i) => "app|$i.txt");
    var rewrite = new RewriteTransformer("txt", "out");
    initGraph(files, {"app": [[rewrite]]});

    // Pause and resume apply to simulate parallel long-running transformers.
    rewrite.pauseApply();
    updateSources(files);
    schedule(pumpEventQueue);
    rewrite.resumeApply();

    for (var i = 0; i < 100; i++) {
      expectAsset("app|$i.out", "$i.out");
    }
    buildShouldSucceed();

    expect(rewrite.maxParallelRuns, completion(equals(10)));
  });
}

Increase barback scheduled_test timeout for many_parallel_transformers test.

BUG=dartbug.com/15483

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

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


// 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 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

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

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error on line'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

// 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 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

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

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error in'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

Fix test for analyzer error message.

Fix test for analyzer error message.

BUG=
R=nweiz@google.com

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

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


/*
 * 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.
 */
/**
 * @assertion Evaluation of a property extraction i of the form new T#
 * proceeds as follows:
 * ...
 * If T does not denote a class, a dynamic error occurs.
 * @description Check that it is a dynamic error if T denotes enum
 * @author sgrekhov@unipro.ru
 */
import '../../../../Utils/dynamic_check.dart';

enum E {a, b, c, m}

main() {
  checkDynamicError(() {
    var x = new E#;
  });
}

/*
 * 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.
 */
/**
 * @assertion Evaluation of a property extraction i of the form new T#
 * proceeds as follows:
 * ...
 * If T does not denote a class, a dynamic error occurs.
 * @description Check that it is a dynamic error if T denotes not existing class
 * @author sgrekhov@unipro.ru
 */
import '../../../../Utils/dynamic_check.dart';

main() {
  checkDynamicError(() {
    var x = new C#;
  });
}

Test fixed. Don't try instantiate enum

Test fixed. Don't try instantiate enum


// 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 'dart:html';

import 'package:angular/angular.dart';

/// Utility class to allow opening a URL in a new window.
@Injectable()
class NewWindowOpener {
  void open(String url) => openInNewWindow(url);
}

/// Opens the given url in a new window.
///
/// Gives a hint to Chrome that it should open the given link in a separate
/// process.
void openInNewWindow(String url) {
  var anchorElement = AnchorElement(href: url)
    ..rel = 'noreferrer'
    ..target = '_blank';
  document.body.append(anchorElement);
  anchorElement.click();
  anchorElement.remove();
}

// 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 'dart:html';

import 'package:angular/angular.dart';

/// Utility class to allow opening a URL in a new window.
@Injectable()
class NewWindowOpener {
  void open(String url) => openInNewWindow(url);
}

/// Opens the given url in a new window.
///
/// Gives a hint to Chrome that it should open the given link in a separate
/// process.
void openInNewWindow(String url) {
  var anchorElement = AnchorElement(href: url)
    ..rel = 'noopener noreferrer'
    ..target = '_blank';
  document.body.append(anchorElement);
  anchorElement.click();
  anchorElement.remove();
}

Update all components to use ref="noopener noreferrer" for target="_blank" links.

https://www.owasp.org/index.php/Reverse_Tabnabbing

PiperOrigin-RevId: 249578192


import 'interval.dart';

extension LengthIntervalNumExtension on Interval<num> {
  /// Returns the length an [Interval] as [int].
  ///
  /// Returns `0` if the interval is empty or `1` if the interval contains a
  /// single value. Throws an [ArgumentError] if one of  the bounds is unbound
  /// (infinite).
  int toIntLength() {
    if (isEmpty) {
      return 0;
    } else if (isSingle) {
      return 1;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      throw ArgumentError.value(this, 'interval', 'Interval is unbounded');
    } else {
      var lowerEndpoint = lower.endpoint!.ceil();
      if (lower.isOpen && lowerEndpoint == lower.endpoint) lowerEndpoint++;
      var upperEndpoint = upper.endpoint!.truncate();
      if (upper.isOpen && upperEndpoint == upper.endpoint) upperEndpoint--;
      return lowerEndpoint < upperEndpoint ? upperEndpoint - lowerEndpoint : 0;
    }
  }

  /// Returns the length an [Interval] as [double].
  ///
  /// Returns `0.0` if the interval is empty or `double.infinity` if one of
  /// the bounds is unbound (infinite).
  double toDoubleLength() => isEmpty
      ? 0.0
      : lower.isUnbounded || upper.isUnbounded
          ? double.infinity
          : upper.endpoint!.toDouble() - lower.endpoint!.toDouble();
}

import 'interval.dart';

extension LengthIntervalNumExtension on Interval<num> {
  /// Returns the length an [Interval] as [int].
  ///
  /// Returns `0` if the interval is empty or `1` if the interval contains a
  /// single value. Throws an [ArgumentError] if one of  the bounds is unbounded
  /// (infinite).
  int toIntLength() {
    if (isEmpty) {
      return 0;
    } else if (isSingle) {
      return 1;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      throw ArgumentError.value(this, 'interval', 'Interval is unbounded');
    } else {
      var lowerEndpoint = lower.endpoint!.ceil();
      if (lower.isOpen && lowerEndpoint == lower.endpoint) lowerEndpoint++;
      var upperEndpoint = upper.endpoint!.truncate();
      if (upper.isOpen && upperEndpoint == upper.endpoint) upperEndpoint--;
      return lowerEndpoint < upperEndpoint ? upperEndpoint - lowerEndpoint : 0;
    }
  }

  /// Returns the length an [Interval] as [double].
  ///
  /// Returns `0.0` if the interval is empty or contains a single value. Returns
  /// `double.infinity` if one of the bounds is unbounded (infinite).
  double toDoubleLength() {
    if (isEmpty || isSingle) {
      return 0.0;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      return double.infinity;
    } else {
      return upper.endpoint!.toDouble() - lower.endpoint!.toDouble();
    }
  }
}

Improve comments and code clarity for Interval.toDoubleLength() and Interval.toIntLength().


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

// SharedOptions=--enable-experiment=control-flow-collections,spread-collections

// Test that a null stream expression procudes a runtime error.
import 'package:async_helper/async_helper.dart';

void main() {
  asyncTest(() async {
    // Null stream.
    Stream<int> nullStream = null;
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int>[await for (var i in nullStream) 1]);
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int, int>{await for (var i in nullStream) 1: 1});
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int>{await for (var i in nullStream) 1});
  });
}

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

// SharedOptions=--enable-experiment=control-flow-collections,spread-collections

// Test that a null stream expression procudes a runtime error.
import 'package:async_helper/async_helper.dart';

void main() {
  asyncTest(() async {
    // Null stream.
    Stream<int> nullStream = null;
    asyncExpectThrows<Error>(
        () async => <int>[await for (var i in nullStream) 1]);
    asyncExpectThrows<Error>(
        () async => <int, int>{await for (var i in nullStream) 1: 1});
    asyncExpectThrows<Error>(
        () async => <int>{await for (var i in nullStream) 1});
  });
}

[tests] Update expected error NoSuchMethodError --> Error

Most (all?) implementations now throw ArgumentError since the
StreamIterator constructor no longer accepts null but the actual
type is not specified.
https://dart-review.googlesource.com/c/sdk/+/98001.

Change-Id: I10a24a67aa7353552c56d435ef206a2bc4f842fa
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/100987
Commit-Queue: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@google.com>
Reviewed-by: Bob Nystrom <afede3a9ebedb865bee78398feff6fbe97068f17@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.

/** Handles the `list` pub command. */
void commandList(PubOptions options, List<String> args) {
  // TODO(rnystrom): Validate args. Right now, this just lists the packages in
  // your cache.
  final cache = new PackageCache(options.cacheDir);
  cache.listAll().then((packages) {
    for (final package in packages) {
      print(package.name);
    }
  });
}

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

/** Handles the `list` pub command. */
void commandList(PubOptions options, List<String> args) {
  // TODO(rnystrom): Validate args. Right now, this just lists the packages in
  // your cache.
  final cache = new PackageCache(options.cacheDir);
  cache.listAll().then((packages) {
    packages.sort((a, b) => a.name.compareTo(b.name));
    for (final package in packages) {
      print(package.name);
    }
  });
}

Sort packages by name before listing them.

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

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


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


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

class Bound {
  run() {
    return 42;
  }
}

void main() {
  var runner = new Bound().run;
  Expect.equals(42, runner());
}

Fix for issue 1623: bind does not work on safari.
Review URL: https://chromiumcodereview.appspot.com//9365050

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


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


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for 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:typed_data';
import 'package:expect/expect.dart';

main() {
  final val = (0xffb15062).toSigned(32);
  final arr = new Int32x4List(1);
  arr[0] = new Int32x4(val, val, val, val);
  Expect.equals(val, arr[0].x);
  Expect.equals(val, arr[0].y);
  Expect.equals(val, arr[0].z);
  Expect.equals(val, arr[0].w);
}

Add regression test for http://dartbug.com/21220.

BUG=http://dartbug.com/21220
R=fschneider@google.com

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

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@41599 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