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

import 'dart:uri';
import 'dart:io';
import '../../../sdk/lib/_internal/compiler/compiler.dart' as api;
import '../../../sdk/lib/_internal/compiler/implementation/apiimpl.dart';
import '../../../sdk/lib/_internal/compiler/implementation/dart2jslib.dart'
    hide Compiler;
import '../../../sdk/lib/_internal/compiler/implementation/filenames.dart';
import '../../../sdk/lib/_internal/compiler/implementation/source_file_provider.dart';
import '../../../sdk/lib/_internal/libraries.dart';

class CollectingDiagnosticHandler extends FormattingDiagnosticHandler {
  bool hasWarnings = false;
  bool hasErrors = false;

  CollectingDiagnosticHandler(SourceFileProvider provider) : super(provider);

  void diagnosticHandler(Uri uri, int begin, int end, String message,
                         api.Diagnostic kind) {
    if (kind == api.Diagnostic.WARNING) {
      hasWarnings = true;
    }
    if (kind == api.Diagnostic.ERROR) {
      hasErrors = true;
    }
    super.diagnosticHandler(uri, begin, end, message, kind);
  }
}

void main() {
  Uri currentWorkingDirectory = getCurrentDirectory();
  var libraryRoot = currentWorkingDirectory.resolve('sdk/');
  var uriList = new List<Uri>();
  LIBRARIES.forEach((String name, LibraryInfo info) {
    if (info.documented) {
      uriList.add(new Uri.fromComponents(scheme: 'dart', path: name));
    }
  });
  var provider = new SourceFileProvider();
  var handler = new CollectingDiagnosticHandler(provider);
  var compiler = new Compiler(
      provider.readStringFromUri,
      handler.diagnosticHandler,
      libraryRoot, libraryRoot,
      <String>['--analyze-only']);
  compiler.librariesToAnalyzeWhenRun = uriList;
  compiler.run(null);
  Expect.isFalse(handler.hasWarnings);
  Expect.isFalse(handler.hasErrors);
}

Add dart2js unittest to analyze the API.

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

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

class Foo {
  var x;
  var y;
  var z;
  var v;
  Foo() : x = {}, y = <int>{}, z = const {}, v = const <int>{};
}

main() {
  Expect.equals("{}", new Foo().x.toString());
  Expect.equals("{}", new Foo().y.toString());
  Expect.equals("{}", new Foo().z.toString());
  Expect.equals("{}", new Foo().v.toString());
}

Fix bug in partial parsing of map literal.

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

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


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

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    // Target just past the endpoint, because the animation will stop once the
    // Spring gets within the epsilon, and we want to stop at the endpoint.
    double target = direction == Direction.reverse ?
        this.left - _kEpsilon : this.right + _kEpsilon;
    return new SpringSimulation(spring, position, target, velocity);
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

const double _kEpsilon = 0.001;

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

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  // We overshoot the target by this distance, but stop the simulation when
  // the spring gets within this distance (regardless of how fast it's moving).
  // This causes the spring to settle a bit faster than it otherwise would.
  static final Tolerance tolerance =
      new Tolerance(velocity: double.INFINITY, distance: 0.01);

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    double target = direction == Direction.reverse ?
        this.left - tolerance.distance : this.right + tolerance.distance;
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

Adjust the SpringForce tolerance, used by Drawer and Dismissable.

They settle much faster after you fling them now.


import 'package:build/build.dart';
import 'package:moor_generator/src/analyzer/runner/file_graph.dart';
import 'package:moor_generator/src/analyzer/runner/results.dart';
import 'package:moor_generator/src/analyzer/session.dart';
import 'package:test/test.dart';

import '../utils/test_backend.dart';

void main() {
  TestBackend backend;
  MoorSession session;

  setUpAll(() {
    backend = TestBackend({
      AssetId.parse('test_lib|lib/entry.dart'): r'''
import 'package:moor/moor.dart';

class Foos extends Table {
  IntColumn get id => integer().autoIncrement()();
}

@UseMoor(include: {'db.moor'}, tables: [Foos])
class Database {}
     ''',
      AssetId.parse('test_lib|lib/db.moor'): r'''
import 'entry.dart';

CREATE TABLE bars (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
);
      ''',
    });
    session = backend.session;
  });

  tearDownAll(() {
    backend.finish();
  });

  test('handles cyclic imports', () async {
    final backendTask =
        backend.startTask(Uri.parse('package:test_lib/entry.dart'));
    final task = session.startTask(backendTask);
    await task.runTask();

    final file = session.registerFile(Uri.parse('package:test_lib/entry.dart'));

    expect(file.state, FileState.analyzed);
    expect(file.errors.errors, isEmpty);

    final result = file.currentResult as ParsedDartFile;
    final database = result.declaredDatabases.single;

    expect(database.allTables.map((t) => t.sqlName),
        containsAll(['foos', 'bars']));
  });
}

Write another integration test with cyclic queries


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// VMOptions=--old_gen_heap_size=7
// Test that compaction does occur on repeated add/remove.

main() {
  var x = {};
  for (int i = 0; i < 1000000; i++) {
    x[i] = 10;
    x.remove(i);
  }
}

Add regression test for Map compaction issue.

Original fix for the issue:
https://code.google.com/p/dart/source/detail?r=44671

R=kustermann@google.com

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

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


import 'dart:async';
import 'dart:html';

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

test() async {
  var list = await window.navigator.mediaDevices.enumerateDevices();
  Expect.isTrue(list is List<dynamic>, "Expected list to be List<dynamic>");
}

void main() {
  asyncStart();
  test().then((_) => asyncEnd());
}

Add test to enumerate media devices

Add test to enumerate media devices

Bug: https://github.com/dart-lang/sdk/issues/39627

Enumerating media devices gives back a cast error in html_dart2js. This
test should fail and the cast should be fixed such that it passes.

Change-Id: Ie2502f265448d078578113cbea57dd81d20015c7
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/128104
Commit-Queue: Srujan Gaddam <4175f2f2dd3cde6c8ffb10fc9674dc09abf813fe@google.com>
Reviewed-by: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>


part of github.common;

/// The [UsersService] handles communication with authorizations related methods
/// of the GitHub API.
///
/// Note: You can only access this API via Basic Authentication using your
/// username and password, not tokens.
///
/// API docs: https://developer.github.com/v3/oauth_authorizations/
class AuthorizationsService extends Service {

  AuthorizationsService(GitHub github) : super(github);

  /// Lists all authorizations.
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations
  Stream<Authorization> listAuthorizations() {
    return new PaginationHelper(_github).objects("GET", "/authorizations",
        Authorization.fromJSON);
  }

  /// Fetches an authorization specified by [name].
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization
  Future<Authorization> getAuthorization(int id) {
    return _github.getJSON("/authorizations/${id}", statusCode: 200,
        convert: Authorization.fromJSON);
  }

  // TODO: Implement remaining API methods of authorizations:
  // See https://developer.github.com/v3/oauth_authorizations/
}

part of github.common;

/// The [AuthorizationsService] handles communication with authorizations related methods
/// of the GitHub API.
///
/// Note: You can only access this API via Basic Authentication using your
/// username and password, not tokens.
///
/// API docs: https://developer.github.com/v3/oauth_authorizations/
class AuthorizationsService extends Service {

  AuthorizationsService(GitHub github) : super(github);

  /// Lists all authorizations.
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations
  Stream<Authorization> listAuthorizations() {
    return new PaginationHelper(_github).objects("GET", "/authorizations",
        Authorization.fromJSON);
  }

  /// Fetches an authorization specified by [name].
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization
  Future<Authorization> getAuthorization(int id) {
    return _github.getJSON("/authorizations/${id}", statusCode: 200,
        convert: Authorization.fromJSON);
  }

  // TODO: Implement remaining API methods of authorizations:
  // See https://developer.github.com/v3/oauth_authorizations/
}

Fix Typo in Authorizations Service

Fix Typo in Authorizations Service


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

import 'dart:async';

import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer_plugin/plugin/plugin.dart';
import 'package:analyzer_plugin/protocol/protocol.dart';
import 'package:analyzer_plugin/protocol/protocol_generated.dart';
import 'package:analyzer_plugin/src/utilities/completion/completion_core.dart';
import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
import 'package:analyzer_plugin/utilities/generator.dart';

/**
 * A mixin that can be used when creating a subclass of [ServerPlugin] to
 * provide most of the implementation for handling code completion requests.
 *
 * Clients may not extend or implement this class, but are allowed to use it as
 * a mix-in when creating a subclass of [ServerPlugin].
 */
abstract class CompletionMixin implements ServerPlugin {
  /**
   * Return a list containing the completion contributors that should be used to
   * create completion suggestions when used in the context of the given
   * analysis [driver].
   */
  List<CompletionContributor> getCompletionContributors(
      covariant AnalysisDriverGeneric driver);

  /**
   * Return the result of using the given analysis [driver] to produce a fully
   * resolved AST for the file with the given [path].
   */
  Future<ResolveResult> getResolveResultForCompletion(
      covariant AnalysisDriverGeneric driver, String path);

  @override
  Future<CompletionGetSuggestionsResult> handleCompletionGetSuggestions(
      CompletionGetSuggestionsParams parameters) async {
    String path = parameters.file;
    ContextRoot contextRoot = contextRootContaining(path);
    if (contextRoot == null) {
      // Return an error from the request.
      throw new RequestFailure(
          RequestErrorFactory.pluginError('Failed to analyze $path', null));
    }
    AnalysisDriverGeneric driver = driverMap[contextRoot];
    ResolveResult analysisResult =
        await getResolveResultForCompletion(driver, path);
    CompletionRequestImpl request = new CompletionRequestImpl(
        resourceProvider, analysisResult, parameters.offset);
    CompletionGenerator generator =
        new CompletionGenerator(getCompletionContributors(driver));
    GeneratorResult result =
        await generator.generateCompletionResponse(request);
    result.sendNotifications(channel);
    return result.result;
  }
}

Add a mixing that handles most of the work for computing completions

R=maxkim@google.com

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


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

/**
 * This file contains code for collecting statistics about the use of fields in
 * a summary file.
 */
library analyzer.tool.summary.stats;

import 'dart:io';

import 'package:analyzer/src/summary/base.dart';
import 'package:analyzer/src/summary/idl.dart';

main(List<String> args) {
  if (args.length != 1) {
    _printUsage();
    exitCode = 1;
    return;
  }

  String inputFilePath = args[0];

  // Read the input.
  SdkBundle bundle =
      new SdkBundle.fromBuffer(new File(inputFilePath).readAsBytesSync());

  // Compute and output stats.
  Stats stats = new Stats();
  stats.record(bundle);
  stats.dump();
}

/**
 * The name of the stats tool.
 */
const String BINARY_NAME = "stats";

/**
 * Print information about how to use the stats tool.
 */
void _printUsage() {
  print('Usage: $BINARY_NAME input_file_path');
}

/**
 * An instance of [Stats] keeps track of statistics about the use of fields in
 * summary objects.
 */
class Stats {
  /**
   * Map from type to field name to a count of how often the field is used.
   */
  Map<Type, Map<String, int>> counts = <Type, Map<String, int>>{};

  /**
   * Print out statistics gathered so far.
   */
  void dump() {
    counts.forEach((Type type, Map<String, int> typeCounts) {
      print(type);
      List<String> keys = typeCounts.keys.toList();
      keys.sort((String a, String b) => typeCounts[b].compareTo(typeCounts[a]));
      for (String key in keys) {
        print('  $key: ${typeCounts[key]}');
      }
      print('');
    });
  }

  /**
   * Record statistics for [obj] and all objects it refers to.
   */
  void record(SummaryClass obj) {
    Map<String, int> typeCounts =
        counts.putIfAbsent(obj.runtimeType, () => <String, int>{});
    obj.toMap().forEach((String key, Object value) {
      if (value == null ||
          value == 0 ||
          value == false ||
          value == '' ||
          value is List && value.isEmpty) {
        return;
      }
      if (!typeCounts.containsKey(key)) {
        typeCounts[key] = 0;
      }
      typeCounts[key]++;
      if (value is SummaryClass) {
        record(value);
      } else if (value is List) {
        value.forEach((Object element) {
          if (element is SummaryClass) {
            record(element);
          }
        });
      }
    });
  }
}

Create a tool for collecting statistics about summary files.

In addition to exploring how the summary format is used, it should be a
nice micro-benchmark for FlatBuffer deserialization efficiency.

R=scheglov@google.com

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


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

// These tests are for an experimental feature that treats Dart primitive types
// (int, bool, double, etc.) as non-nullable. This file is not evidence for an
// intention to officially support non-nullable primitives in Dart (or general
// NNBD, for that matter) so don't get too crazy about it.

library analyzer.test.src.task.non_null_primitives.checker_test;

import '../../../reflective_tests.dart';
import '../strong/strong_test_helper.dart';

void main() {
  initStrongModeTests();
  runReflectiveTests(NonNullCheckerTest);
}

@reflectiveTest
class NonNullCheckerTest {
  // Tests simple usage of ints as iterators for a loop. Not directly related to
  // non-nullability, but if it is implemented this should be more efficient,
  // since languages.length will not be null-checked on every iteration.
  void test_forLoop() {
    checkFile('''
class MyList {
  int length;
  MyList() {
    length = 6;
  }
  String operator [](int i) {
    return <String>["Dart", "Java", "JS", "C", "C++", "C#"][i];
  }
}

main() {
  var languages = new MyList();
  for (int i = 0; i < languages.length; ++i) {
    print(languages[i]);
  }
}
''');
  }
}

Add test harness for experimental non-null option

non_null_checker_test.dart is closely following
../strong/checker_test.dart.  Currently it includes a single test which
is not directly related to nullability.

BUG=
R=jmesserly@google.com

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


library compare_to_golden;

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

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

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  expect(await input.readAsString(), await golden.readAsString());
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

library compare_to_golden;

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

import 'package:dart_style/src/dart_formatter.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  final formattedInput = _formatter.format(await input.readAsString());
  final formattedGolden = _formatter.format(await golden.readAsString());
  expect(formattedInput, formattedGolden);
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

final _formatter = new DartFormatter();

Format golden files during test.

Angular: Format golden files during test.

PiperOrigin-RevId: 160161091


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

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

class TranscodeDecisionIcon extends StatelessWidget {
  final String transcodeDecision;

  const TranscodeDecisionIcon({
    Key key,
    @required this.transcodeDecision,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _mapTranscodeDecisionToIcon(transcodeDecision);
  }
}

FaIcon _mapTranscodeDecisionToIcon(String transcodeDecision) {
  switch (transcodeDecision) {
    case ('transcode'):
      return FaIcon(
        FontAwesomeIcons.server,
        size: 15,
        color: TautulliColorPalette.not_white,
      );
    case ('copy'):
      return FaIcon(
        FontAwesomeIcons.stream,
        size: 18,
        color: TautulliColorPalette.not_white,
      );
    case ('direct play'):
      return FaIcon(
        FontAwesomeIcons.playCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
    default:
      return FaIcon(
        FontAwesomeIcons.questionCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
  }
}

Add core transcode decision icon widget.