// 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=nonfunction-type-aliases

// Introduce an aliased type.

typedef T = Object;

// Use the aliased type.

abstract class C {
  T? v10;
  final T v12;
  C(): v12 = T();
  C.name1(this.v10, this.v12);
  factory C.name2(T arg1, T arg2) = C.name1;
}

abstract class D2 extends C with T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D3 implements T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D4 = C with T;
//             ^
// [analyzer] unspecified
// [cfe] unspecified

main() {
  T.named();
//  ^^^^^
// [analyzer] unspecified
// [cfe] unspecified

  T.staticMethod<T>();
//  ^^^^^^^^^^^^
// [analyzer] unspecified
// [cfe] Method not found: 'Object.staticMethod'.
//  ^^^^^^^^^^^^
// [cfe] A constructor invocation can't have type arguments on the constructor name.
}

// 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=nonfunction-type-aliases

// Introduce an aliased type.

typedef T = Object;

// Use the aliased type.

abstract class C {
  T? v10;
  final T v12;
  C(): v12 = T();
  C.name1(this.v10, this.v12);
  factory C.name2(T arg1, T arg2) = C1.name1;
}

class C1 implements C {
  C1.name1(T arg1, T arg2);
  noSuchMethod(Invocation invocation) => throw 0;
}

abstract class D2 extends C with T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D3 implements T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D4 = C with T;
//             ^
// [analyzer] unspecified
// [cfe] unspecified

main() {
  T.named();
//  ^^^^^
// [analyzer] unspecified
// [cfe] unspecified

  T.staticMethod<T>();
//  ^^^^^^^^^^^^
// [analyzer] unspecified
// [cfe] Method not found: 'Object.staticMethod'.
//  ^^^^^^^^^^^^
// [cfe] A constructor invocation can't have type arguments on the constructor name.
}

Fix one more test with factory redirect to abstract class.

Same as https://dart-review.googlesource.com/c/sdk/+/175361

Change-Id: I0f6b9032e4f2718bceb00010080bc5ca0835a761
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/175580
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Reviewed-by: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));

  });
}

import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('2015'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    tester.tap(tester.findText('2014'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    expect(currentValue, equals(new DateTime(2014, 6, 9)));
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));
  });
}

Test year selection for date picker

Test year selection for date picker


part of material;

class LambertMaterial implements Material {
  String name;

  Blending blending = const Blending(
      sourceColorFactor: BlendingFactor.sourceAlpha,
      destinationColorFactor: BlendingFactor.oneMinusSourceAlpha);

  DepthTest depthTest = const DepthTest();

  StencilTest stencilTest;

  CullingMode faceCulling;

  Vector3 diffuseColor = new Vector3(0.5, 0.5, 0.5);

  Texture2D diffuseMap;

  Vector3 emissionColor = new Vector3.zero();

  Texture2D emissionMap;

  double opacity = 1.0;

  Texture2D opacityMap;

  Texture2D bumpMap;

  Texture2D normalMap;
}

part of material;

class LambertMaterial implements Material {
  String name;

  Blending blending = const Blending(
      sourceColorFactor: BlendingFactor.sourceAlpha,
      destinationColorFactor: BlendingFactor.oneMinusSourceAlpha);

  DepthTest depthTest = const DepthTest();

  StencilTest stencilTest;

  CullingMode faceCulling;

  Vector3 diffuseColor = new Vector3(0.5, 0.5, 0.5);

  Texture2D diffuseMap;

  Vector3 emissionColor = new Vector3.zero();

  Texture2D emissionMap;

  double opacity = 1.0;

  Texture2D opacityMap;

  Texture2D normalMap;
}

Drop ambition to add bump (height) mapping


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

abstract class Link<T> {
  factory Link.create() = LinkFactory<T>.create;
}

class LinkFactory<T> {
  factory LinkFactory.create() { return null; }
}

main() {
  var a = new Link<int>.create();
}

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

abstract class Link<T> {
  factory Link.create() = LinkFactory<T>.create;
}

class LinkFactory<T> implements Link<T> {
  factory LinkFactory.create() { return null; }
}

main() {
  var a = new Link<int>.create();
}

Remove analyzer warning from test.

Remove analyzer warning from test.

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


library LocationTest;
import '../../pkg/unittest/lib/unittest.dart';
import '../../pkg/unittest/lib/html_config.dart';
import 'dart:html';

main() {
  useHtmlConfiguration();

  var isLocation = predicate((x) => x is Location, 'is a Location');

  test('location hash', () {
      final location = window.location;
      expect(location, isLocation);

      // The only navigation we dare try is hash.
      location.hash = 'hello';
      var h = location.hash;
      expect(h, '#hello');
    });

  test('location.origin', () {
    var origin = window.location.origin;

    // We build up the origin from Uri, then make sure that it matches.
    var uri = new Uri(window.location.href);
    var reconstructedOrigin = '${uri.scheme}://${uri.host}';
    if (uri.port != 0) {
      reconstructedOrigin = '$reconstructedOrigin:${uri.port}';
    }

    expect(origin, reconstructedOrigin);
  });
}

library LocationTest;
import '../../pkg/unittest/lib/unittest.dart';
import '../../pkg/unittest/lib/html_config.dart';
import 'dart:html';

main() {
  useHtmlConfiguration();

  var isLocation = predicate((x) => x is Location, 'is a Location');

  test('location hash', () {
      final location = window.location;
      expect(location, isLocation);

      // The only navigation we dare try is hash.
      location.hash = 'hello';
      var h = location.hash;
      expect(h, '#hello');
    });

  test('location.origin', () {
    var origin = window.location.origin;

    // We build up the origin from Uri, then make sure that it matches.
    var uri = Uri.parse(window.location.href);
    var reconstructedOrigin = '${uri.scheme}://${uri.host}';
    if (uri.port != 0) {
      reconstructedOrigin = '$reconstructedOrigin:${uri.port}';
    }

    expect(origin, reconstructedOrigin);
  });
}

Fix a test after recent uri change.

Fix a test after recent uri change.

TBR=sgjesse@google.com

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

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


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

part of ManyOverriddenNoSuchMethodTest.dart;

class GetName {
  foo(a, b) => "foo";
}

String getName(im) => reflect(new GetName()).delegate(im);

class OverriddenNoSuchMethod {

  OverriddenNoSuchMethod() {}

  noSuchMethod(Invocation mirror) {
    Expect.equals("foo", getName(mirror));
    // 'foo' was called with two parameters (not counting receiver).
    List args = mirror.positionalArguments;
    Expect.equals(2, args.length);
    Expect.equals(101, args[0]);
    Expect.equals(202, args[1]);
    return 5;
  }

  static testMain() {
    var obj = new OverriddenNoSuchMethod();
    Expect.equals(5, obj.foo(101, 202));
  }
}

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

part of OverriddenNoSuchMethodTest.dart;

class GetName {
  foo(a, b) => "foo";
}

String getName(im) => reflect(new GetName()).delegate(im);

class OverriddenNoSuchMethod {

  OverriddenNoSuchMethod() {}

  noSuchMethod(Invocation mirror) {
    Expect.equals("foo", getName(mirror));
    // 'foo' was called with two parameters (not counting receiver).
    List args = mirror.positionalArguments;
    Expect.equals(2, args.length);
    Expect.equals(101, args[0]);
    Expect.equals(202, args[1]);
    return 5;
  }

  static testMain() {
    var obj = new OverriddenNoSuchMethod();
    Expect.equals(5, obj.foo(101, 202));
  }
}

Fix another part-of related test failure

Library names must match.

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

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


// To parse this JSON data, do
//
//     final studentIdBarcodeModel = studentIdBarcodeModelFromJson(jsonString);

import 'dart:convert';

StudentIdBarcodeModel studentIdBarcodeModelFromJson(String str) =>
    StudentIdBarcodeModel.fromJson(json.decode(str));

String studentIdBarcodeModelToJson(StudentIdBarcodeModel data) =>
    json.encode(data.toJson());

class StudentIdBarcodeModel {
  String studentId;
  int barCode;

  StudentIdBarcodeModel({
    this.studentId,
    this.barCode,
  });

  factory StudentIdBarcodeModel.fromJson(Map<String, dynamic> json) =>
      StudentIdBarcodeModel(
        studentId: json["studentId"],
        barCode: json["barCode"] == 0 ? null : json["barCode"],
      );

  Map<String, dynamic> toJson() => {
        "studentId": studentId,
        "barCode": barCode,
      };
}

// To parse this JSON data, do
//
//     final studentIdBarcodeModel = studentIdBarcodeModelFromJson(jsonString);

import 'dart:convert';

StudentIdBarcodeModel studentIdBarcodeModelFromJson(String str) =>
    StudentIdBarcodeModel.fromJson(json.decode(str));

String studentIdBarcodeModelToJson(StudentIdBarcodeModel data) =>
    json.encode(data.toJson());

class StudentIdBarcodeModel {
  String studentId;
  int barCode;

  StudentIdBarcodeModel({
    this.studentId,
    this.barCode,
  });

  factory StudentIdBarcodeModel.fromJson(Map<String, dynamic> json) =>
      StudentIdBarcodeModel(
        studentId: json["studentId"],
        barCode: json["barCode"] == null ? 0 : json["barCode"],
      );

  Map<String, dynamic> toJson() => {
        "studentId": studentId,
        "barCode": barCode == null ? 0 : barCode,
      };
}

Initialize barcode model barCode data type as int to resolve null exceptions


library oauth1;

export 'src/utils.dart';
export 'src/client_credentials.dart';
export 'src/credentials.dart';
export 'src/signature_method.dart';
export 'src/client.dart';
export 'src/authorization.dart';
export 'src/platform.dart';

library oauth1;

export 'src/client_credentials.dart';
export 'src/credentials.dart';
export 'src/signature_method.dart';
export 'src/client.dart';
export 'src/authorization.dart';
export 'src/platform.dart';

Remove utils.dart export from library

Remove utils.dart export from library


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

import 'package:angular/angular.dart';

// TODO(google): Remove this once use of '#' in a template is either
// consistent, or has a way to declare specifically what you want - e.g. the
// component instance or the element ref. Today, using # on an HTML element will
// be an elementRef, but # on a component will be a component instance.

/// Place on an element or component to expose the [ElementRef] as 'ref'.
///
/// Example usage:
///     <material-button ref #button="ref"></materialButton>
///     <!-- You can now use 'button' in this template as a property -->
@Directive(
  selector: '[ref]', exportAs: 'ref',
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class ReferenceDirective {
  final ElementRef elementRef;

  ReferenceDirective(this.elementRef);
}

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

import 'package:angular/angular.dart';

// TODO(google): Remove this once use of '#' in a template is either
// consistent, or has a way to declare specifically what you want - e.g. the
// component instance or the element ref. Today, using # on an HTML element will
// be an elementRef, but # on a component will be a component instance.

/// Place on an element or component to expose the [ElementRef] as 'ref'.
///
/// Example usage:
///     <material-button ref #button="ref"></materialButton>
///     <!-- You can now use 'button' in this template as a property -->
@Directive(
  selector: '[ref]',
  exportAs: 'ref',
)
class ReferenceDirective {
  final ElementRef elementRef;

  ReferenceDirective(this.elementRef);
}

Remove visibility.all from @Component annotations. This is potentially BREAKING
change.

Please review carefully. Breakage will only be caught if the code is covered by
tests. Reject this change if you believe it breaks you.

If the component needs to be injected anywhere in the app, you can get a
runtime exception after this change. This should be caught by tests using your
components, and fixing the issue should be trivial, as the exceptions have good
error messages, such as "No provider found for FooComponent".

PiperOrigin-RevId: 190729754


import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../../../core/helpers/color_palette_helper.dart';

class DeleteSyncedItemButton extends StatelessWidget {
  const DeleteSyncedItemButton({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          FaIcon(
            FontAwesomeIcons.trash,
            size: 20,
            color: TautulliColorPalette.not_white,
          ),
          SizedBox(height: 4),
          Text(
            'Delete',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../../../core/helpers/color_palette_helper.dart';

class DeleteSyncedItemButton extends StatelessWidget {
  const DeleteSyncedItemButton({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          FaIcon(
            FontAwesomeIcons.trashAlt,
            size: 20,
            color: TautulliColorPalette.not_white,
          ),
          SizedBox(height: 4),
          Text(
            'Delete',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}

Use the same trash icon as server settings page.


// 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 "../language/compiler_annotations.dart";

@DontInline()
returnStringOrNull() {
  () => 42;
  return new DateTime.now().millisecondsSinceEpoch == 0 ? 'foo' : null;
}

main() {
  Expect.throws(() => 'foo' + returnStringOrNull(),
                (e) => e is ArgumentError);
  Expect.throws(() => 'foo'.split(returnStringOrNull()),
                (e) => e is ArgumentError || e is NoSuchMethodError);
}

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

@NoInline()
@AssumeDynamic()
returnStringOrNull() {
  return new DateTime.now().millisecondsSinceEpoch == 0 ? 'foo' : null;
}

main() {
  Expect.throws(() => 'foo' + returnStringOrNull(),
                (e) => e is ArgumentError);
  Expect.throws(() => 'foo'.split(returnStringOrNull()),
                (e) => e is ArgumentError || e is NoSuchMethodError);
}

Fix test to not reach out of current dir

This lets us use the same test for DDC

TBR=vsm@google.com

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


part of streamy.runtime;

/// A [StreamTransformer] that de-duplicates entities. This will cause
/// metadata about the entity (Entity.streamy) to be inaccurate, but will
/// prevent multiple values from being published on [Stream]s when core [Entity]
/// data has not changed.
class EntityDedupTransformer extends StreamEventTransformer<Entity, Entity> {
  var _last = null;

  handleData(Entity data, EventSink<Entity> sink) {
    if (data != _last) {
      sink.add(data);
    }
    _last = data;
  }
}

/// A [StreamTransformer] that closes the stream after the RPC reply is
/// received.
class OneShotRequestTransformer implements StreamTransformer<Entity, Entity> {

  Stream<Entity> bind(Stream<Entity> input) {
    var output = new StreamController<Entity>();
    var sub;
    sub = input.listen((e) {
      output.add(e);
      if (e.streamy.source == 'RPC') {
        sub.cancel();
        output.close();
      }
    });
    sub
      ..onError(output.addError)
      ..onDone(output.close);
    return output.stream;
  }
}

abstract class RequestStreamTransformer {
  Stream bind(Request request, Stream stream);
}

class TransformingRequestHandler extends RequestHandler {
  final RequestHandler delegate;
  final RequestStreamTransformer transformer;

  TransformingRequestHandler(this.delegate, this.transformer);

  Stream handle(Request request) =>
      transformer.bind(request, delegate.handle(request));
}

part of streamy.runtime;

/// A [StreamTransformer] that de-duplicates entities. This will cause
/// metadata about the entity (Entity.streamy) to be inaccurate, but will
/// prevent multiple values from being published on [Stream]s when core [Entity]
/// data has not changed.
class EntityDedupTransformer<T extends Entity>
    extends StreamEventTransformer<T, T> {
  var _last = null;

  handleData(T data, EventSink<T> sink) {
    if (data != _last) {
      sink.add(data);
    }
    _last = data;
  }
}

/// A [StreamTransformer] that closes the stream after the RPC reply is
/// received.
class OneShotRequestTransformer<T extends Entity>
    implements StreamTransformer<T, T> {

  Stream<T> bind(Stream<T> input) {
    var output = new StreamController<T>();
    var sub;
    sub = input.listen((e) {
      output.add(e);
      if (e.streamy.source == 'RPC') {
        sub.cancel();
        output.close();
      }
    });
    sub
      ..onError(output.addError)
      ..onDone(output.close);
    return output.stream;
  }
}

abstract class RequestStreamTransformer {
  Stream bind(Request request, Stream stream);
}

class TransformingRequestHandler extends RequestHandler {
  final RequestHandler delegate;
  final RequestStreamTransformer transformer;

  TransformingRequestHandler(this.delegate, this.transformer);

  Stream handle(Request request) =>
      transformer.bind(request, delegate.handle(request));
}

Make transformer type parameters more concrete to let users control types.


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

library test.integration.analysis.error;

import 'package:analysis_server/src/protocol.dart';
import 'package:unittest/unittest.dart';

import '../../reflective_tests.dart';
import '../integration_tests.dart';

@ReflectiveTestCase()
class AnalysisErrorIntegrationTest extends AbstractAnalysisServerIntegrationTest
    {
  test_detect_simple_error() {
    String pathname = sourcePath('test.dart');
    writeFile(pathname,
        '''
main() {
  var x // parse error: missing ';'
}''');
    standardAnalysisSetup();
    return analysisFinished.then((_) {
      expect(currentAnalysisErrors[pathname], isList);
      List<AnalysisError> errors = currentAnalysisErrors[pathname];
      expect(errors, hasLength(1));
      expect(errors[0].location.file, equals(pathname));
    });
  }
}

main() {
  runReflectiveTests(AnalysisErrorIntegrationTest);
}

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

library test.integration.analysis.error;

import 'package:analysis_server/src/protocol.dart';
import 'package:unittest/unittest.dart';

import '../../reflective_tests.dart';
import '../integration_tests.dart';

@ReflectiveTestCase()
class AnalysisErrorIntegrationTest extends AbstractAnalysisServerIntegrationTest
    {
  test_detect_simple_error() {
    String pathname = sourcePath('test.dart');
    writeFile(pathname,
        '''
main() {
  print(null) // parse error: missing ';'
}''');
    standardAnalysisSetup();
    return analysisFinished.then((_) {
      expect(currentAnalysisErrors[pathname], isList);
      List<AnalysisError> errors = currentAnalysisErrors[pathname];
      expect(errors, hasLength(1));
      expect(errors[0].location.file, equals(pathname));
    });
  }
}

main() {
  runReflectiveTests(AnalysisErrorIntegrationTest);
}

Fix integration test to avoid new 'Unused local variable' hint.

R=scheglov@google.com

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

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


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Test that dart2js gvns dynamic getters that don't have side
// effects.

import 'compiler_helper.dart';
import 'parser_helper.dart';

const String TEST = r"""
class A {
  var foo;
  bar(a) {
    return a.foo + a.foo;
  }
}

main() {
  new A().bar(new Object());
}
""";

main() {
  Uri uri = new Uri.fromComponents(scheme: 'source');
  var compiler = compilerFor(TEST, uri);
  compiler.runCompiler(uri);
  String generated = compiler.assembledCode;
  RegExp regexp = new RegExp(r"get\$foo");
  Iterator matches = regexp.allMatches(generated).iterator;
  checkNumberOfMatches(matches, 1);
  var cls = findElement(compiler, 'A');
  Expect.isNotNull(cls);
  var element = cls.lookupLocalMember(buildSourceString('foo'));
  Expect.isNotNull(element);
  Expect.isFalse(compiler.world.userDefinedGetters.contains(element));
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Test that dart2js gvns dynamic getters that don't have side
// effects.

import 'compiler_helper.dart';
import 'parser_helper.dart';

const String TEST = r"""
class A {
  var foo;
  bar(a) {
    return a.foo + a.foo;
  }
}

main() {
  new A().bar(new Object());
}
""";

main() {
  Uri uri = new Uri.fromComponents(scheme: 'source');
  var compiler = compilerFor(TEST, uri);
  compiler.runCompiler(uri);
  String generated = compiler.assembledCode;
  RegExp regexp = new RegExp(r"get\$foo");
  Iterator matches = regexp.allMatches(generated).iterator;
  checkNumberOfMatches(matches, 1);
  var cls = findElement(compiler, 'A');
  Expect.isNotNull(cls);
  SourceString name = buildSourceString('foo');
  var element = cls.lookupLocalMember(name);
  Expect.isNotNull(element);
  Selector selector = new Selector.getter(name, null);
  Expect.isFalse(compiler.world.hasAnyUserDefinedGetter(selector));
}

Fix build by updating test to use different check for user-defined getters.

TBR'ed.

R=ngeoffray@google.com
BUG=

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

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


import 'package:pay_platform_interface/core/payment_item.dart';

abstract class PayPlatform {
  /**
   * TBA
   */
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile);

  /**
   * TBA
   */
  Future<Map<String, dynamic>> showPaymentSelector(
      Map<String, dynamic> paymentProfile, List<PaymentItem> paymentItems);
}

import 'package:pay_platform_interface/core/payment_item.dart';

abstract class PayPlatform {
  /// Determines whether the caller can make a payment with a given
  /// configuration.
  ///
  /// Returns a [Future] that resolves to a boolean value with the result.
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile);

  /// Triggers the action to show the payment selector to complete a payment
  /// with the configuration and a list of [PaymentItem] to determine the price
  /// elements to show in the payment selector.
  ///
  /// Returns a [Future] with the result of the selection.
  Future<Map<String, dynamic>> showPaymentSelector(
      Map<String, dynamic> paymentProfile, List<PaymentItem> paymentItems);
}

Add docu to the platform interface

Add docu to the platform interface


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

library native_types;

import 'test_base.dart';

abstract class C {}

class D {}

var foo = bar;
var bar = foo;

main() {
  expectTrue(1 is int);
  expectTrue(1 is! double);

  expectTrue(new List<int>() is List<int>);
  expectTrue(new List<int>() is! List<double>);
  expectTrue("hest" is String);
  expectTrue("hest" is! int);

  expectTrue(null is! String);
  expectTrue(null is dynamic);
  expectTrue(null is Object);

  expectTrue(true is bool);
  expectTrue(true is! int);

  // Test error and exception classes
  expectThrows(() => new C(), (e) => e is AbstractClassInstantiationError);

  expectThrows(() => new D().foo(), (e) => e is NoSuchMethodError);

  expectThrows(() => foo, (e) => e is CyclicInitializationError);

  expectThrows(() => [][1], (e) => e is RangeError);

  expectTrue(new UnsupportedError("") is UnsupportedError);

  expectTrue(new ArgumentError() is ArgumentError);

  expectTrue(
      new IntegerDivisionByZeroException() is IntegerDivisionByZeroException);
}

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

library native_types;

import 'test_base.dart';

abstract class C {}

class D {}

var foo = bar;
var bar = foo;

main() {
  expectTrue(1 is int);
  expectTrue(1 is! double);

  expectTrue(new List<int>() is List<int>);
  expectTrue(new List<int>() is! List<double>);
  expectTrue("hest" is String);
  expectTrue("hest" is! int);

  expectTrue(null is! String);
  expectTrue(null is dynamic);
  expectTrue(null is Object);

  expectTrue(true is bool);
  expectTrue(true is! int);

  // Test error and exception classes
  expectThrows(() => new C(), (e) => e is AbstractClassInstantiationError);  /// 01: static type warning

  expectThrows(() => new D().foo(), (e) => e is NoSuchMethodError);  /// 02: static type warning

  expectThrows(() => foo, (e) => e is CyclicInitializationError);

  expectThrows(() => [][1], (e) => e is RangeError);

  expectTrue(new UnsupportedError("") is UnsupportedError);

  expectTrue(new ArgumentError() is ArgumentError);

  expectTrue(
      new IntegerDivisionByZeroException() is IntegerDivisionByZeroException);
}

Add multitest markers to reify test

Add multitest markers to reify test

TBR=dmitryas@google.com

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


part of mac.utils;

Future<String> fetch(String url) async {
  var uri = Uri.parse(url);
  var client = new HttpClient();
  var request = await client.getUrl(uri);
  var response = await request.close();
  if (response.statusCode != 200) {
    throw new Exception("Failed to fetch ${url}");
  }
  return response.transform(UTF8.decoder).join().then((out) {
    client.close();
    return out;
  });
}

Future<dynamic> fetchJSON(String url) async {
  var text = await fetch(url);
  var json = JSON.decode(text);
  return json;
}

part of mac.utils;

Future<String> fetch(String url) async {
  var uri = Uri.parse(url);
  var client = new HttpClient();
  var request = await client.getUrl(uri);
  var response = await request.close();
  if (response.statusCode != 200) {
    throw new Exception("Failed to fetch ${url}");
  }
  return UTF8.decoder.bind(response).join().then((out) {
    client.close();
    return out;
  });
}

Future<dynamic> fetchJSON(String url) async {
  var text = await fetch(url);
  var json = JSON.decode(text);
  return json;
}

Prepare for Uint8List SDK breaking change

A recent change to the Dart SDK updated `HttpClientResponse`
to implement `Stream<Uint8List>` rather than implementing
`Stream<List<int>>`.

This forwards-compatible chnage updates calls to
`Stream.transform(StreamTransformer)` to instead call the
functionally equivalent `StreamTransformer.bind(Stream)`
API, which puts the stream in a covariant position and
thus causes the SDK change to be non-breaking.

https://github.com/dart-lang/sdk/issues/36900


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

/// The colorful library.
library colorful;

class Color {
  int _r;
  int _g;
  int _b;

  Color(this._r, this._g, this._b);

  get r => _r;
  get g => _g;
  get b => _b;

  bool isValid() {
    return 0 <= this._r && this._r <= 255 &&
           0 <= this._g && this._g <= 255 &&
           0 <= this._b && this._b <= 255;
  }
}

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

/// The colorful library.
library colorful;

class Color {
  double _r;
  double _g;
  double _b;

  Color(this._r, this._g, this._b);

  get r => _r;
  get g => _g;
  get b => _b;

  bool isValid() {
    return 0.0 <= this._r && this._r <= 1.0 &&
           0.0 <= this._g && this._g <= 1.0 &&
           0.0 <= this._b && this._b <= 1.0;
  }

}

Use double for RGB color.

Use double for RGB color.


import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

const String APP_ID = "2982LV-6WP5YYAWLQ";

@Command("w", description: "Wolfram Alpha", prefix: "Wolfram")
w(String input) => wolfram(input);

@Command("wolfram", description: "Wolfram Alpha", prefix: "Wolfram")
wolfram(String input) async {
  var url = "http://api.wolframalpha.com/v2/query?output=json&input=${Uri.encodeComponent(input)}&appid=${APP_ID}";
  var json = await fetchJSON(url);
  var result = json.queryresult;
  try {
    if (result.pods == null) {
      var dym = result.didyoumeans;
      if (dym != null && dym.isNotEmpty) {
        var word = dym[0].val;
        return "Did you mean ${word}?";
      } else {
        return "No Result Found.";
      }
    }

    var pods = new SimpleMap({});

    for (var pod in result.pods) {
      pods[pod.title] = pod;
    }

    var plainPods = [
      "Result",
      "Decimal approximation",
      "Response",
      "Definitions",
      "Definition"
    ];

    for (var p in plainPods) {
      if (pods.containsKey(p)) {
        return pods[p].subpods[0].plaintext;
      }
    }
  } catch (e) {
    return "Failed to get output.";
  }

  return "Pod is not yet supported.";
}

import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

const String APP_ID = "2982LV-6WP5YYAWLQ";

@Command("w", description: "Wolfram Alpha", prefix: "Wolfram")
w(String input) => wolfram(input);

@Command("wolfram", description: "Wolfram Alpha", prefix: "Wolfram")
wolfram(String input) async {
  var url = "http://api.wolframalpha.com/v2/query?output=json&input=${Uri.encodeComponent(input)}&appid=${APP_ID}";
  var json = await fetchJSON(url);
  var result = json.queryresult;
  try {
    if (result.pods == null) {
      var dym = result.didyoumeans;
      if (dym != null && dym.isNotEmpty) {
        var word = dym[0].val;
        return "Did you mean ${word}?";
      } else {
        return "No Result Found.";
      }
    }

    var pods = new SimpleMap({});

    for (var pod in result.pods) {
      pods[pod.title] = pod;
    }

    var plainPods = [
      "Result",
      "Decimal approximation",
      "Response",
      "Definitions",
      "Definition",
      "Chemical names and formulas"
    ];

    for (var p in plainPods) {
      if (pods.containsKey(p)) {
        return pods[p].subpods[0].plaintext;
      }
    }
  } catch (e) {
    return "Failed to get output.";
  }

  return "Pod is not yet supported.";
}

Add Support for Chemical Names and Formulas


import '../lib/import_table.dart';

main() {
  List<String> paths = new List<String>();
  paths.add("file://");
  paths.add("file:///a");
  paths.add("file:///a/b");
  paths.add("file:///a/b/c");

  int end = paths.length;
  for (int i = 0; i < end; i++) {
    paths.add(paths[i] + "/d.dart");
    paths.add(paths[i] + "/e.dart");
    paths.add(paths[i] + "/");
  }
  paths[0] = "file:///";
  paths.sort();
  for (int i = 0; i < paths.length; i++) {
    for (int j = 0; j < paths.length; j++) {
      check(paths[i], paths[j]);
    }
  }
  check("", "");
}

void check(String target, String ref) {
  Uri uriTarget = Uri.parse(target);
  Uri uriRef = Uri.parse(ref);
  String relative = relativeUriPath(uriTarget, uriRef);
  if (Uri.base.resolveUri(uriTarget) !=
      Uri.base.resolveUri(uriRef).resolve(relative)) {
    throw "Failure on '$target' and '$ref': Got '$relative' which resolves to "
        "${uriRef.resolve(relative)}";
  }
}

import 'package:kernel/import_table.dart';

main() {
  List<String> paths = new List<String>();
  paths.add("file://");
  paths.add("file:///a");
  paths.add("file:///a/b");
  paths.add("file:///a/b/c");

  int end = paths.length;
  for (int i = 0; i < end; i++) {
    paths.add(paths[i] + "/d.dart");
    paths.add(paths[i] + "/e.dart");
    paths.add(paths[i] + "/");
  }
  paths[0] = "file:///";
  paths.sort();
  for (int i = 0; i < paths.length; i++) {
    for (int j = 0; j < paths.length; j++) {
      check(paths[i], paths[j]);
    }
  }
  check("", "");
}

void check(String target, String ref) {
  Uri uriTarget = Uri.parse(target);
  Uri uriRef = Uri.parse(ref);
  String relative = relativeUriPath(uriTarget, uriRef);
  if (Uri.base.resolveUri(uriTarget) !=
      Uri.base.resolveUri(uriRef).resolve(relative)) {
    throw "Failure on '$target' and '$ref': Got '$relative' which resolves to "
        "${uriRef.resolve(relative)}";
  }
}

Fix relative import from pkg/kernel/test to pkg/kernel/lib.

This doesn't work due to the file organization used in google3.

Change-Id: I814a087bd9c6e10fc7738c782af6f54fde3cf000
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/99181
Auto-Submit: Paul Berry <72d414e3a99fb120308437779d51667bcc0984eb@google.com>
Commit-Queue: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>
Reviewed-by: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>


import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';
import 'package:angular_router/angular_router.dart';
import 'package:gitpods/src/user/user.dart';
import 'package:gitpods/src/user/user_service.dart';

@Component(
  selector: 'profile',
  templateUrl: 'profile_component.html',
  directives: const [COMMON_DIRECTIVES, formDirectives],
)
class ProfileComponent implements OnInit {
  final Router _router;
  final UserService _userService;

  ProfileComponent(this._router, this._userService);

  bool loading;
  User user;

  @override
  void ngOnInit() {
    this._userService.me().then((user) => this.user = user);
  }

  void submit(Event e) {
    e.preventDefault();
    loading = true;

    this._userService.update(user).then((user) {
      loading = false;
      this._router.navigate(['/UserProfile',{'username': user.username}]);
    });
  }
}

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';
import 'package:angular_router/angular_router.dart';
import 'package:gitpods/src/loading_component.dart';
import 'package:gitpods/src/user/user.dart';
import 'package:gitpods/src/user/user_service.dart';

@Component(
  selector: 'profile',
  templateUrl: 'profile_component.html',
  directives: const [
    COMMON_DIRECTIVES,
    formDirectives,
    LoadingComponent,
  ],
)
class ProfileComponent implements OnInit {
  final Router _router;
  final UserService _userService;

  ProfileComponent(this._router, this._userService);

  bool loading;
  User user;

  @override
  void ngOnInit() {
    this._userService.me().then((user) => this.user = user);
  }

  void submit(Event e) {
    e.preventDefault();
    loading = true;

    this._userService.update(user).then((user) {
      loading = false;
      this._router.navigate(['/UserProfile',{'username': user.username}]);
    });
  }
}

Add LoadingComponent as directive to profile setting component


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

/**
 * Simple code with broad use cases.
 */
library quiver.core;

part 'src/core/hash.dart';
part 'src/core/optional.dart';

/**
 * Returns the first non-null argument. If all arguments are null, throws
 * an [ArgumentError].
 *
 * Note: if [o1] is an [Optional], this can be accomplished with `o1.or(o2)`.
 */
Object firstNonNull(o1, o2, [o3, o4]) {
  if (o1 != null) return o1;
  if (o2 != null) return o2;
  if (o3 != null) return o3;
  if (o4 != null) return o4;
  throw new ArgumentError('All arguments were null');
}

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

/**
 * Simple code with broad use cases.
 */
library quiver.core;

part 'src/core/hash.dart';
part 'src/core/optional.dart';

/**
 * Returns the first non-null argument. If all arguments are null, throws
 * an [ArgumentError].
 *
 * Note: if [o1] is an [Optional], this can be accomplished with `o1.or(o2)`.
 */
firstNonNull(o1, o2, [o3, o4]) {
  if (o1 != null) return o1;
  if (o2 != null) return o2;
  if (o3 != null) return o3;
  if (o4 != null) return o4;
  throw new ArgumentError('All arguments were null');
}

Change return type of firstNonNull to dynamic


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

/// Simple command line interface to launching browsers.
/// Uses the browser_controller framework.
/// The usage is:
///   DARTBIN launch_browser.dart BROWSER_NAME URL
/// DARTBIN should be the checked in stable binary.

import 'package:test_runner/src/browser_controller.dart';
import 'package:test_runner/src/configuration.dart';

void printHelp() {
  print("Usage pattern:");
  print("launch_browser.dart browser url");
  print("Supported browsers: ${Browser.supportedBrowsers}");
}

void main(List<String> arguments) {
  if (arguments.length != 2) {
    print("Wrong number of arguments, please pass in exactly two arguments");
    printHelp();
    return;
  }
  var name = arguments[0];

  if (!Browser.supportedBrowser(name)) {
    print("Specified browser not supported");
    printHelp();
    return;
  }

  var runtime = Runtime.find(name);
  var configuration = TestConfiguration(
      configuration: Configuration(
          "dummy configuration", null, null, null, runtime, null));
  var executable = configuration.browserLocation;
  var browser = Browser.byRuntime(runtime, executable);
  browser.start(arguments[1]);
}

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

/// Simple command line interface to launching browsers.
/// Uses the browser_controller framework.
/// The usage is:
///   DARTBIN launch_browser.dart BROWSER_NAME URL
/// DARTBIN should be the checked in stable binary.

import 'package:test_runner/src/browser_controller.dart';
import 'package:test_runner/src/configuration.dart';

void printHelp() {
  print("Usage pattern:");
  print("launch_browser.dart browser url");
  print("Supported browsers: ${Browser.supportedBrowsers}");
}

void main(List<String> arguments) {
  if (arguments.length != 2) {
    print("Wrong number of arguments, please pass in exactly two arguments");
    printHelp();
    return;
  }
  var name = arguments[0];

  if (!Browser.supportedBrowser(name)) {
    print("Specified browser not supported");
    printHelp();
    return;
  }

  var runtime = Runtime.find(name);
  var configuration = TestConfiguration(
      configuration: Configuration(
          "dummy-configuration", null, null, null, runtime, null));
  var executable = configuration.browserLocation;
  var browser = Browser.byRuntime(runtime, executable);
  browser.start(arguments[1]);
}

Replace space from test config name

[pkg:test_runner] Replace space from test config name

https://dart-review.googlesource.com/c/sdk/+/181404 disallows spaces
in Configurations.

Change-Id: I0582eca064bd6d88ebcbbf411e44a6147895148c
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/184902
Auto-Submit: Srujan Gaddam <4175f2f2dd3cde6c8ffb10fc9674dc09abf813fe@google.com>
Commit-Queue: William Hesse <a821cddceae7dc400f272e3cb1a72f400f9fed6d@google.com>
Reviewed-by: William Hesse <a821cddceae7dc400f272e3cb1a72f400f9fed6d@google.com>


import 'package:flutter/widgets.dart';

void main() {
  runApp(new Center(child: new Text('Hello, world!')));
}

class MySampleHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

import 'package:flutter/widgets.dart';

void main() {
  runApp(new Center(
      child: new Text(
    'Hello, world!',
    textDirection: TextDirection.ltr,
  )));
}

class MySampleHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

Add missing text direction for running flutter tests


part of ChattyWorker;

_workerStarter(message) {
  message[0].startWorking(message[1]);
}

abstract class Boss {

  ReceivePort response;
  SendPort request;

  Boss() {
    response = new ReceivePort();
    response.listen((message) {
      if (message is SendPort) {
        request = message;
        speak(Status.READY);
      } else {
        manage(message);
      }
    });
  }

  void doYourJob(Worker worker) {
    Isolate.spawn(_workerStarter, [worker, response.sendPort]);
  }

  void manage(message);

  void speak(message) {
    request.send(message);
  }

  void byebye() {
    response.close();
  }

}

part of ChattyWorker;

_manager(message) {
  message[0].startWorking(message[1]);
}

abstract class Boss {

  ReceivePort response;
  SendPort request;

  Boss() {
    response = new ReceivePort();
    response.listen((message) {
      if (message is SendPort) {
        request = message;
        speak(Status.READY);
      } else {
        manage(message);
      }
    });
  }

  void doYourJob(Worker worker) {
    Isolate.spawn(_manager, [worker, response.sendPort]);
  }

  void manage(message);

  void speak(message) {
    request.send(message);
  }

  void byebye() {
    response.close();
  }

}

Revert "rename manager to workerStarter"

This reverts commit f6e51634a05181f837fef270cb0ef25580c18c4b.


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

library dart2js.serialization.compilation1_test;

import 'compilation_test_helper.dart' as test;
import 'test_data.dart';

main() {
  test.main(['0', '0']);
}

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

library dart2js.serialization.compilation0_test;

import 'compilation_test_helper.dart' as test;
import 'test_data.dart';

main() {
  test.main(['0', '0']);
}

Rename library name in test.

Rename library name in test.

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


import 'package:moor_generator/src/analyzer/errors.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group("reports error when an import can't be found", () {
    test('in moor file', () async {
      final state = TestState.withContent({
        'foo|lib/a.moor': '''
import 'b.moor';
        ''',
      });

      final result = await state.analyze('package:foo/a.moor');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInMoorFile>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });

    test('in a dart file', () async {
      final state = TestState.withContent({
        'foo|lib/a.dart': '''
import 'package:moor/moor.dart';

@UseMoor(include: {'b.moor'})
class Database {

}
            ''',
      });

      final result = await state.analyze('package:foo/a.dart');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInDartCode>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });
  });
}

import 'package:moor_generator/src/analyzer/errors.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group("reports error when an import can't be found", () {
    test('in moor file', () async {
      final state = TestState.withContent({
        'foo|lib/a.moor': '''
import 'b.moor';
        ''',
      });

      final result = await state.analyze('package:foo/a.moor');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInMoorFile>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });

    test('in a dart file', () async {
      final state = TestState.withContent({
        'foo|lib/a.dart': '''
import 'package:moor/moor.dart';

@UseMoor(include: {'b.moor'})
class Database {

}
            ''',
      });

      final result = await state.analyze('package:foo/a.dart');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInDartCode>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    }, tags: 'analyzer');
  });
}

Add another missing analyzer tag to test


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

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs an informative message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the message.
  void info(String message, [Span span]) {
    _printMessage('info', message, span);
  }

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}

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

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs an informative message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the message.
  void info(String message, [Span span]) {
    _printMessage('info', message, span);
  }

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix: $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}

Use our own DiagnosticHandler for dart2js.

Instead of implementing SourceFileProvider and using dart2js's
built in DiagnosticHandler, we just provide our own
CompilerInputProvider and DiagnosticHandler functions. This avoids
implementing stuff in SourceFileProvider and, more importantly,
lets us handle missing source files better.

The DiagnosticHandler in dart2js just barfs and trashes the original
error if it can't find a source file to associate with it. The windows
bots are currently failing on an error I can't see because it doesn't
have a source file.

BUG=
R=nweiz@google.com

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

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


import 'package:args/args.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:angular/source_gen.dart';
import 'package:angular_compiler/angular_compiler.dart';

const String TEMPLATE_EXTENSION_PARAM = 'template_extension';
const String CODEGEN_MODE_PARAM = 'codegen_mode';

Builder templateBuilder(BuilderOptions options) {
  final compilerFlags = new CompilerFlags(
    genDebugInfo: options.config[CODEGEN_MODE_PARAM] == 'debug',
  );
  if (options.config[CODEGEN_MODE_PARAM] == 'outline') {
    return new TemplateOutliner(compilerFlags,
        extension: options.config[TEMPLATE_EXTENSION_PARAM]);
  }
  return new LibraryBuilder(new TemplateGenerator(compilerFlags),
      generatedExtension: options.config[TEMPLATE_EXTENSION_PARAM]);
}

Builder templatePlaceholderBuilder(_) => const TemplatePlaceholderBuilder();

final _argParser = new ArgParser()
  ..addOption(CODEGEN_MODE_PARAM,
      help: 'What mode to run the code generator in. Either release or debug.')
  ..addOption(TEMPLATE_EXTENSION_PARAM,
      help: 'Generated template extension.', defaultsTo: '.template.dart');

Remove unused local var _argParser.

Remove unused local var _argParser.

PiperOrigin-RevId: 177630622


// 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 "dart:io";

test(int milliseconds) {
  var watch = new Stopwatch();
  watch.start();
  sleep(new Duration(milliseconds: milliseconds));
  watch.stop();
  Expect.isTrue(watch.elapsedMilliseconds >= milliseconds);
}

main() {
  test(1);
  test(10);
  test(100);
}

// 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 "dart:io";

test(int milliseconds) {
  var watch = new Stopwatch();
  watch.start();
  sleep(new Duration(milliseconds: milliseconds));
  watch.stop();
  Expect.isTrue(watch.elapsedMilliseconds + 1 >= milliseconds);
}

main() {
  test(1);
  test(10);
  test(100);
}

Make sleep test resilient to timer rounding issues

TBR=ager@google.com

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

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


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

library kernel.transformations.setup_builtin_library;

import '../ast.dart';

// The DartVM has a special `dart:_builtin` library which exposes a
// `_getMainClosure()` method.  We need to change this method to return a
// closure of `main()`.
Program transformProgram(Program program,
    {String libraryUri: 'dart:_builtin'}) {
  Procedure mainMethod = program.mainMethod;

  Library builtinLibrary;
  for (Library library in program.libraries) {
    if (library.importUri.toString() == libraryUri) {
      builtinLibrary = library;
      break;
    }
  }

  if (builtinLibrary == null) {
    throw new Exception('Could not find "dart:_builtin" library');
  }

  FunctionNode getMainClosure;
  for (Procedure procedure in builtinLibrary.procedures) {
    if (procedure.name.name == '_getMainClosure') {
      getMainClosure = procedure.function;
      break;
    }
  }

  if (getMainClosure == null) {
    throw new Exception('Could not find "_getMainClosure" in "$libraryUri"');
  }

  var returnMainStatement = new ReturnStatement(new StaticGet(mainMethod));
  getMainClosure.body = returnMainStatement;
  returnMainStatement.parent = getMainClosure;

  return program;
}

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

library kernel.transformations.setup_builtin_library;

import '../ast.dart';

// The DartVM has a special `dart:_builtin` library which exposes a
// `_getMainClosure()` method.  We need to change this method to return a
// closure of `main()`.
Program transformProgram(Program program,
    {String libraryUri: 'dart:_builtin'}) {
  Procedure mainMethod = program.mainMethod;

  if (mainMethod == null) return program;

  Library builtinLibrary;
  for (Library library in program.libraries) {
    if (library.importUri.toString() == libraryUri) {
      builtinLibrary = library;
      break;
    }
  }

  if (builtinLibrary == null) {
    throw new Exception('Could not find "dart:_builtin" library');
  }

  FunctionNode getMainClosure;
  for (Procedure procedure in builtinLibrary.procedures) {
    if (procedure.name.name == '_getMainClosure') {
      getMainClosure = procedure.function;
      break;
    }
  }

  if (getMainClosure == null) {
    throw new Exception('Could not find "_getMainClosure" in "$libraryUri"');
  }

  var returnMainStatement = new ReturnStatement(new StaticGet(mainMethod));
  getMainClosure.body = returnMainStatement;
  returnMainStatement.parent = getMainClosure;

  return program;
}

Allow main to be null for modular tranformation.

R=asgerf@google.com

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


// 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=non-nullable

// Test that `x ?? y` results in type LUB(x!, y)
void main() {
  f1(null, 2);
}

void f1(
    int? nullableInt,
    int nonNullInt,
) {
  (nullableInt ?? nonNullInt) + 1;
  (nullableInt ?? nullableInt) + 1;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.UNCHECKED_USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nullableInt) + 1;
//               ^^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.UNCHECKED_USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nonNullInt) + 1;
//               ^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
}

// TODO(mfairhurst) add cases with type parameter types

// 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=non-nullable

// Test that `x ?? y` results in type LUB(x!, y)
void main() {
  f1(null, 2);
}

void f1(
    int? nullableInt,
    int nonNullInt,
) {
  (nullableInt ?? nonNullInt) + 1;
  (nullableInt ?? nullableInt) + 1;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nullableInt) + 1;
//               ^^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nonNullInt) + 1;
//               ^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
}

// TODO(mfairhurst) add cases with type parameter types

Fix a test to get the analyzer nnbd bot to pass

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


library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
    ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..classes.add('hideedittask')
    ..append(ti);
  return li;
}

DivElement taskContainer(String tasksummary) {
  DivElement div = new DivElement();
  div
    ..classes.add('taskcontainer')
    ..append(singleTaskElement(tasksummary))
    ..append(editTaskElement(tasksummary));
  return div;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) {
    div.append(singleTaskElement(i['summary']));
    div.append(editTaskElement(i['summary']));
  });
}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  DivElement div = taskContainer(tasksummary);
  querySelector('#listtasks').children.insert(0, div);
}

library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
    ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..classes.add('hideedittask')
    ..append(ti);
  return li;
}

DivElement taskContainer(String tasksummary) {
  DivElement div = new DivElement();
  div
    ..classes.add('taskcontainer')
    ..append(singleTaskElement(tasksummary))
    ..append(editTaskElement(tasksummary));
  return div;
}

// append for each task in tasks a taskContainer
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) => div.append(taskContainer(i['summary'])));
}

// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  DivElement div = taskContainer(tasksummary);
  querySelector('#listtasks').children.insert(0, div);
}

Change displayTasks to use taskContainer element.


import 'dart:io';
import 'package:twitter/twitter.dart';

main(){
  var envVars = Platform.environment;
  print(envVars['CONSUMER_KEY']);
  print(envVars['CONSUMER_SECRET']);
  print(envVars['ACCESS_TOKEN']);
  print(envVars['ACCESS_TOKEN_SECRET']);
  var map = {
      "consumerKey": envVars['CONSUMER_KEY'],
      "consumerSecret": envVars['CONSUMER_SECRET'],
      "accessToken": envVars['ACCESS_TOKEN'],
      "accessSecret": envVars['ACCESS_TOKEN_SECRET']
  };
  var twitter = new Twitter.fromMap(map);
  try {
    var a = twitter.request("GET", "statuses/home_timeline.json");
    a.then((value){
      new File("test.json").writeAsString(value.body);
    });
  } catch(e) {
  } finally {
  }
  return;
}

import 'dart:io';
import 'package:twitter/twitter.dart';

main() {
  var envVars = Platform.environment;
  print(envVars['CONSUMER_KEY']);
  print(envVars['CONSUMER_SECRET']);
  print(envVars['ACCESS_TOKEN']);
  print(envVars['ACCESS_TOKEN_SECRET']);
  var map = {
      "consumerKey": envVars['CONSUMER_KEY'],
      "consumerSecret": envVars['CONSUMER_SECRET'],
      "accessToken": envVars['ACCESS_TOKEN'],
      "accessSecret": envVars['ACCESS_TOKEN_SECRET']
  };
  Twitter twitter = new Twitter.fromMap(map);

  try {
    var a = twitter.request("POST", "statuses/update.json",body: {"status":"test"});
    a.then((value){
      new File("test.json").writeAsString(value.body);
    });
  } catch(e) {
  } finally {
  }
  return;
}

Fix example according to filename

Fix example according to filename


library frappe.test_runner;

import 'event_stream_test.dart' as eventStreamTest;
import 'property_test.dart' as propertyTest;
import 'constant_property_test.dart' as constantPropertyTest;
import 'stream_property_test.dart' as streamPropertyTest;
import 'computed_property_test.dart' as computedPropertyTest;
import 'collect_reactable_test.dart' as collectReactableTest;

void main() {
  eventStreamTest.main();
  propertyTest.main();
  constantPropertyTest.main();
  streamPropertyTest.main();
  computedPropertyTest.main();
  collectReactableTest.main();
}

library frappe.test_runner;

import 'event_stream_test.dart' as event_stream_test;
import 'property_test.dart' as property_test;
import 'constant_property_test.dart' as constant_property_test;
import 'stream_property_test.dart' as stream_property_test;
import 'computed_property_test.dart' as computed_property_test;
import 'collect_reactable_test.dart' as collect_reactable_test;

void main() {
  event_stream_test.main();
  property_test.main();
  constant_property_test.main();
  stream_property_test.main();
  computed_property_test.main();
  collect_reactable_test.main();
}

Use underscores for import aliases

Use underscores for import aliases


import 'dart:async';

import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:moor_generator/integrations/build.dart';
import 'package:test/test.dart';

void main() {
  test('generator emits warning about wrong language version', () async {
    final logs = StreamController<String>();

    final expectation = expectLater(
      logs.stream,
      emits(
        allOf(
          contains('Dart 2.1'),
          contains('Please consider raising the minimum SDK version'),
        ),
      ),
    );

    await testBuilder(
      moorBuilder(BuilderOptions.empty),
      {
        'foo|lib/a.dart': '''
// @dart = 2.1

import 'package:moor/moor.dart';

@UseMoor(tables: [])
class Database {}
        ''',
      },
      reader: await PackageAssetReader.currentIsolate(),
      onLog: (log) {
        logs.add(log.message);
      },
    );

    await expectation;
    await logs.close();
  });
}

import 'dart:async';

import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:moor_generator/integrations/build.dart';
import 'package:test/test.dart';

void main() {
  test('generator emits warning about wrong language version', () async {
    final logs = StreamController<String>();

    final expectation = expectLater(
      logs.stream,
      emitsThrough(
        allOf(
          contains('Dart 2.1'),
          contains('Please consider raising the minimum SDK version'),
        ),
      ),
    );

    await testBuilder(
      moorBuilder(BuilderOptions.empty),
      {
        'foo|lib/a.dart': '''
// @dart = 2.1

import 'package:moor/moor.dart';

@UseMoor(tables: [])
class Database {}
        ''',
      },
      reader: await PackageAssetReader.currentIsolate(),
      onLog: (log) {
        logs.add(log.message);
      },
    );

    await expectation;
    await logs.close();
  });
}

Use emitsThrough instead of emits

Use emitsThrough instead of emits


main() {
  var s = "Hello!";
  var l = [0, 1];
  var m = {
    "l": l,
    "s": s,
    new DateTime.now(): "today",
    new DateTime.now().add(const Duration(days: 1)): "tomorrow",
    true: true,
    1: "one",
    1.1: "one-point-one",
  };
  print("Hello, world!"); // BREAKPOINT1
}

main() {
  var s = "Hello!";
  var l = [0, 1];
  var m = {
    "l": l,
    "s": s,
    new DateTime.now(): "today",
    new DateTime.now().add(const Duration(days: 1)): "tomorrow",
    true: true,
    1: "one",
    1.1: "one-point-one",
  };
  if (m[true]) {
    print("Hello, world!"); // BREAKPOINT1
  }
}

Fix compile warning in Dart test project


import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });

}

import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });
  test('3 singleTaskElements should have been inserted', () {
    expect(querySelectorAll('.singletask').length,3);
  });

}

Add test for insertTask function

Add test for insertTask function


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

class _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

  final String memberName;
  final List positionalArguments;
  final Map<String,dynamic> namedArguments = null;

  final int _type;

  _InvocationMirror(this.memberName, this._type, this.positionalArguments);

  static _allocateInvocationMirror(name, arguments) {
    return new _InvocationMirror(name, METHOD, arguments);
  }

  bool get isMethod => _type == METHOD;
  bool get isAccessor => _type != METHOD;
  bool get isGetter => _type == GETTER;
  bool get isSetter => _type == SETTER;

  invokeOn(Object receiver) {
    throw new UnsupportedOperation("invokeOn not implemented yet");
  }
}

// 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 _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

  final String memberName;
  final List positionalArguments;
  final Map<String,dynamic> namedArguments = null;

  final int _type;

  _InvocationMirror(this.memberName, this._type, this.positionalArguments);

  static _allocateInvocationMirror(name, arguments) {
    return new _InvocationMirror(name, METHOD, arguments);
  }

  bool get isMethod => _type == METHOD;
  bool get isAccessor => _type != METHOD;
  bool get isGetter => _type == GETTER;
  bool get isSetter => _type == SETTER;

  invokeOn(Object receiver) {
    throw new UnsupportedError("invokeOn not implemented yet");
  }
}

Fix throw statement in _InvocationMirror.invokeOn on VM's library.

UnsupportedOperation was renamed to UnsupportedError.

R=fschneider@google.com

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

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


library dart_coveralls.calc;

import 'dart:io';

import 'package:dart_coveralls/dart_coveralls.dart';

import 'command_line.dart';

class CalcPart extends Object with CommandLinePart {
  final ArgParser parser;

  CalcPart() : parser = _initializeParser();

  static ArgParser _initializeParser() {
    var _parser = new ArgParser(allowTrailingOptions: true);
    _parser
      ..addFlag("help", help: "Prints this help", negatable: false)
      ..addOption("workers",
          help: "Number of workers for parsing", defaultsTo: "1")
      ..addOption("output", help: "Output file path")
      ..addOption("package-root",
          help: "Root of the analyzed package", defaultsTo: ".");
    return _parser;
  }

  execute(ArgResults res) {
    if (res.rest.length != 1) return print(parser.usage);

    var pRoot = new Directory(res["package-root"]);
    var file = new File(res.rest.single);
    var workers = int.parse(res["workers"]);

    if (!pRoot.existsSync()) return print("Root directory does not exist");
    if (!file.existsSync()) return print("Dart file does not exist");

    var collector = new LcovCollector(pRoot, file);

    return collector.getLcovInformation(workers: workers).then((r) {
      if (res["output"] != null) {
        return new File(res["output"]).writeAsStringSync(r.toString());
      }
      return print(r.toString());
    });
  }
}

library dart_coveralls.calc;

import 'dart:io';

import 'package:dart_coveralls/dart_coveralls.dart';

import 'command_line.dart';

class CalcPart extends Object with CommandLinePart {
  final ArgParser parser;

  CalcPart() : parser = _initializeParser();

  static ArgParser _initializeParser() {
    var _parser = new ArgParser(allowTrailingOptions: true);
    _parser
      ..addFlag("help", help: "Prints this help", negatable: false)
      ..addOption("workers",
          help: "Number of workers for parsing", defaultsTo: "1")
      ..addOption("output", help: "Output file path")
      ..addOption("package-root",
          help: "Root of the analyzed package", defaultsTo: ".");
    return _parser;
  }

  execute(ArgResults res) {
    if (res.rest.length != 1) return print(parser.usage);

    var pRoot = new Directory(res["package-root"]);
    var file = new File(res.rest.single);
    var workers = int.parse(res["workers"]);

    if (!pRoot.existsSync()) return print("Root directory does not exist");
    if (!file.existsSync()) return print("Dart file does not exist");

    var collector = new LcovCollector(pRoot, file);

    return collector.getLcovInformation(workers: workers).then((r) {
      print(r.processResult.stdout);
      if (res["output"] != null) {
        return new File(res["output"]).writeAsStringSync(r.result);
      }
      return print(r.result);
    });
  }
}

Fix problem with instance of coverage result


import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@PluginInstance()
Plugin plugin;
@BotInstance()
BotConnector bot;

@Command("qr", description: "Generate QR Codes", usage: "<input>")
qr(CommandEvent event) => event.transform((input) {
  return shortenUrl("https://chart.googleapis.com/chart?chs=178x178&cht=qr&chl=${Uri.encodeComponent(input)}");
}, prefix: "QR");

import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@PluginInstance()
Plugin plugin;
@BotInstance()
BotConnector bot;

@Command("qr", description: "Generate QR Codes", usage: "<input>")
qr(CommandEvent event) => event.transform((input) {
  return shortenUrl("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${Uri.encodeComponent(input)}");
}, prefix: "QR");

Use a different QR Generator API

Use a different QR Generator API


// @dart=2.9

import 'package:flutter/material.dart';

import '../../features/help/presentation/pages/help_page.dart';
import '../error/failure.dart';
import '../helpers/failure_mapper_helper.dart';

Future<void> showFailureAlertDialog({
  @required BuildContext context,
  @required Failure failure,
  bool showHelp = false,
}) {
  return showDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) {
      return AlertDialog(
        title: Text(FailureMapperHelper.mapFailureToMessage(failure)),
        content: Text(FailureMapperHelper.mapFailureToSuggestion(failure)),
        actions: <Widget>[
          if (showHelp)
            TextButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    fullscreenDialog: true,
                    builder: (context) => const HelpPage(),
                  ),
                );
              },
              child: const Text('HELP'),
            ),
          TextButton(
            child: const Text('CLOSE'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

// @dart=2.9

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';

import '../../features/help/presentation/pages/help_page.dart';
import '../../translations/locale_keys.g.dart';
import '../error/failure.dart';
import '../helpers/failure_mapper_helper.dart';

Future<void> showFailureAlertDialog({
  @required BuildContext context,
  @required Failure failure,
  bool showHelp = false,
}) {
  return showDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) {
      return AlertDialog(
        title: Text(FailureMapperHelper.mapFailureToMessage(failure)),
        content: Text(FailureMapperHelper.mapFailureToSuggestion(failure)),
        actions: <Widget>[
          if (showHelp)
            TextButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    fullscreenDialog: true,
                    builder: (context) => const HelpPage(),
                  ),
                );
              },
              child: const Text(LocaleKeys.button_help).tr(),
            ),
          TextButton(
            child: const Text(LocaleKeys.button_close).tr(),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

Update failure alert dialog with translation keys.


library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
   ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..casses.add('hideedittask')
    ..append(ti);
  return li;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) => div.append(singleTaskElement(i['summary'])));

}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  LIElement st = singleTaskElement(tasksummary);
  querySelector('#listtasks').children.insert(0,st);
}

library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
   ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..classes.add('hideedittask')
    ..append(ti);
  return li;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) => div.append(singleTaskElement(i['summary'])));

}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  LIElement st = singleTaskElement(tasksummary);
  querySelector('#listtasks').children.insert(0,st);
}

Fix typo in classes.add ...

Fix typo in classes.add ...


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

import '../../../lib/src/exit_codes.dart' as exit_codes;
import '../../descriptor.dart' as d;
import '../../test_pub.dart';

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs "bin/nope.dart", which '
        'was not found in foo.');
    pub.shouldExit();
  });
}

// 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 'package:path/path.dart' as p;

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

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs '
        '"${p.join('bin', 'nope.dart')}", which was not found in foo.');
    pub.shouldExit();
  });
}

Fix binstub test on windows.

Fix binstub test on windows.

R=nweiz@google.com

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

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


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

part of liquid;

/// [Context] that is used to propagate information through Virtual DOM.
///
/// [Component]'s implement this interface.
abstract class Context implements vdom.Context {
  /// Parent is attached to the DOM
  bool get isAttached;

  /// Depth relative to other Contexts, it is used to sort write tasks by
  /// its depth, so the lowest depth have the highest priority and will
  /// be executed first.
  int get _depth;
}

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

part of liquid;

/// [Context] that is used to propagate information through Virtual DOM.
///
/// [Component]'s implement this interface.
abstract class Context implements vdom.Context {
  /// Parent is attached to the Document.
  bool get isAttached;

  /// Depth relative to other Contexts, it is used to sort write tasks by
  /// its depth, so the lowest depth have the highest priority and will
  /// be executed first.
  int get _depth;
}

Fix comment in Context class

Fix comment in Context class


#library('roguekit');

#import('dart:html', prefix: 'html');

#import('content.dart');
#import('engine.dart');
#import('ui.dart');
#import('util.dart');

main() {
  final content = createContent();

  final terminal = new DomTerminal(100, 40, html.document.query('#terminal'));
  final keyboard = new Keyboard(html.document);
  final ui = new UserInterface(keyboard, terminal);
  ui.push(new MainMenuScreen(content));

  final element = html.document.query('pre');

  tick(time) {
    ui.tick();
    html.window.webkitRequestAnimationFrame(tick, element);
  }

  html.window.webkitRequestAnimationFrame(tick, element);
}

class Fps {
  Fps() : ticks = new List(NUM_TICKS) {
    for (var i = 0; i < NUM_TICKS; i++) ticks[i] = 0;
  }

  tick(time) {
    // Get the duration between the oldest and newest ticks in the buffer.
    final start = ticks[head];
    final end = time;
    print((end - start) / NUM_TICKS);

    // Add it to the buffer.
    ticks[head] = time;
    head = (head + 1) % NUM_TICKS;
  }

  static final NUM_TICKS = 100;
  /// Circular buffer of past frame times.
  final List ticks;
  int head = 0;
}

#library('roguekit');

#import('dart:html', prefix: 'html');

#import('content.dart');
#import('engine.dart');
#import('ui.dart');
#import('util.dart');

main() {
  final content = createContent();

  final terminal = new DomTerminal(100, 40, html.document.query('#terminal'));
  final keyboard = new Keyboard(html.document);
  final ui = new UserInterface(keyboard, terminal);

  ui.push(new MainMenuScreen(content));

  /*
  final home = new HeroHome();
  final game = new Game(content.areas[0], 0, home);
  ui.push(new GameScreen(home, game));
  */

  final element = html.document.query('pre');

  tick(time) {
    ui.tick();
    html.window.webkitRequestAnimationFrame(tick, element);
  }

  html.window.webkitRequestAnimationFrame(tick, element);
}

class Fps {
  Fps() : ticks = new List(NUM_TICKS) {
    for (var i = 0; i < NUM_TICKS; i++) ticks[i] = 0;
  }

  tick(time) {
    // Get the duration between the oldest and newest ticks in the buffer.
    final start = ticks[head];
    final end = time;
    print((end - start) / NUM_TICKS);

    // Add it to the buffer.
    ticks[head] = time;
    head = (head + 1) % NUM_TICKS;
  }

  static final NUM_TICKS = 100;
  /// Circular buffer of past frame times.
  final List ticks;
  int head = 0;
}

Add temp code for going straight to game.


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

import 'package:angular/angular.dart';
import 'package:angular_components/content/deferred_content_aware.dart';

import 'material_drawer_base.dart';

/// A persistent drawer that can be pinned open or closed.
///
/// Need to include package:angular_components/app_layout/layout.scss.css
/// in the list of styleUrls of the containing component.
///
/// Works with deferred content.
/// __Example usage:__
///     <material-drawer persistent #drawer="drawer">
///         ... content here ...
///     </material-drawer>
///     <material-button (trigger)="drawer.toggle()">
///       Toggle Drawer
///     </material-button>
@Directive(
  selector: 'material-drawer[persistent]',
  exportAs: 'drawer',
  providers: const [
    const Provider(DeferredContentAware,
        useExisting: MaterialPersistentDrawerDirective),
  ],
  host: const {
    '[class.mat-drawer-collapsed]': '!visible',
    '[class.mat-drawer-expanded]': 'visible',
  },
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class MaterialPersistentDrawerDirective extends MaterialDrawerBase {
  MaterialPersistentDrawerDirective() : super();
}

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

import 'package:angular/angular.dart';
import 'package:angular_components/content/deferred_content_aware.dart';

import 'material_drawer_base.dart';

/// A persistent drawer that can be pinned open or closed.
///
/// Need to include package:angular_components/app_layout/layout.scss.css
/// in the list of styleUrls of the containing component.
///
/// Works with deferred content.
/// __Example usage:__
///     <material-drawer persistent #drawer="drawer">
///         ... content here ...
///     </material-drawer>
///     <material-button (trigger)="drawer.toggle()">
///       Toggle Drawer
///     </material-button>
@Directive(
  selector: 'material-drawer[persistent]',
  exportAs: 'drawer',
  providers: const [
    const Provider(DeferredContentAware,
        useExisting: MaterialPersistentDrawerDirective),
  ],
  host: const {
    '[class.mat-drawer-collapsed]': '!visible',
    '[class.mat-drawer-expanded]': 'visible',
  },
  visibility: Visibility.all, // Injected by child elements.
)
class MaterialPersistentDrawerDirective extends MaterialDrawerBase {
  MaterialPersistentDrawerDirective() : super();
}

Remove visibility.all from @Component annotations. This is potentially BREAKING
change.

Please review carefully. Breakage will only be caught if the code is covered by
tests. Reject this change if you believe it breaks you.

If the component needs to be injected anywhere in the app, you can get a
runtime exception after this change. This should be caught by tests using your
components, and fixing the issue should be trivial, as the exceptions have good
error messages, such as "No provider found for FooComponent".

PiperOrigin-RevId: 189922359


// 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 polymer.src.reflected_type;

// These are used by _getReflectedTypeWorkaround, see http://dartbug.com/12607
@MirrorsUsed(targets:
    const ['_js_helper.createRuntimeType', 'dart._js_mirrors.JsClassMirror'],
    override: 'polymer.src.reflected_type')
import 'dart:mirrors';

// Horrible hack to work around: http://dartbug.com/12607
Type getReflectedTypeWorkaround(ClassMirror cls) {
  // On Dart VM, just return reflectedType.
  if (1.0 is! int) return cls.reflectedType;

  var mangledName = reflect(cls).getField(_mangledNameField).reflectee;
  Type type = _jsHelper.invoke(#createRuntimeType, [mangledName]).reflectee;
  return type;
}

final LibraryMirror _jsHelper =
    currentMirrorSystem().libraries[Uri.parse('dart:_js_helper')];

final Symbol _mangledNameField = () {
  var jsClassMirrorMirror = reflect(reflectClass(ClassMirror)).type;
  for (var name in jsClassMirrorMirror.variables.keys) {
    if (MirrorSystem.getName(name) == '_mangledName') return name;
  }
}();

// 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 polymer.src.reflected_type;

// These are used by _getReflectedTypeWorkaround, see http://dartbug.com/12607
@MirrorsUsed(targets:
    const ['_js_helper.createRuntimeType', 'dart._js_mirrors.JsClassMirror'],
    override: 'polymer.src.reflected_type')
import 'dart:mirrors';

// Horrible hack to work around: http://dartbug.com/12607
Type getReflectedTypeWorkaround(ClassMirror cls) {
  // On Dart VM, just return reflectedType.
  if (1.0 is! int) return cls.reflectedType;

  var mangledName = reflect(cls).getField(_mangledNameField).reflectee;
  Type type = _jsHelper.invoke(#createRuntimeType, [mangledName]).reflectee;
  return type;
}

final LibraryMirror _jsHelper =
    currentMirrorSystem().libraries[Uri.parse('dart:_js_helper')];

final Symbol _mangledNameField = () {
  var jsClassMirrorMirror = reflect(reflectClass(ClassMirror)).type;
  for (var name in jsClassMirrorMirror.declarations.keys) {
    if (MirrorSystem.getName(name) == '_mangledName') return name;
  }
}();

Remove use of deprecated mirror API from code that only runs against dart2js.

R=ahe@google.com, jmesserly@google.com

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

git-svn-id: 0aa7e0b98478d6ef7145d04e8154f8ab2209deba@30902 260f80e4-7a28-3924-810f-c04153c831b5


/// A wrapper around a native element inside of a View.
///
/// An `ElementRef` is backed by a render-specific element. In the browser, this
/// is usually a DOM element.
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here, i.e.
// users have to ask for what they need. With that, we can build better analysis
// tools and could do better codegen in the future.
class ElementRef {
  /// The underlying native element or `null` if direct access to native
  /// elements is not supported (e.g. when the application runs in a web
  /// worker).
  ///
  /// Use with caution: Use this API as the last resort when direct access to
  /// DOM is needed. Use templating and data-binding provided by Angular
  /// instead. Alternatively you take a look at [Renderer] which provides API
  /// that can safely be used even when direct access to native elements is not
  /// supported.
  ///
  /// Relying on direct DOM access creates tight coupling between your
  /// application and rendering layers which will make it impossible to separate
  /// the two and deploy your application into a web worker.
  dynamic nativeElement;
  ElementRef(dynamic nativeElement) {
    this.nativeElement = nativeElement;
  }
}

/// A wrapper around a native element inside of a View.
///
/// An `ElementRef` is backed by a render-specific element. In the browser, this
/// is usually a DOM element.
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here, i.e.
// users have to ask for what they need. With that, we can build better analysis
// tools and could do better codegen in the future.
class ElementRef {
  /// The underlying native element.
  ///
  /// Use with caution: Use this API as the last resort when direct access to
  /// DOM is needed. Use templating and data-binding provided by Angular
  /// instead.
  final dynamic nativeElement;
  ElementRef(this.nativeElement);
}

Make nativeElement final.
doc(ElementRef): cleanup.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=153537946