repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/wrappers.dart
// 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:collection'; import 'dart:math' as math; import 'unmodifiable_wrappers.dart'; /// A base class for delegating iterables. /// /// Subclasses can provide a [_base] that should be delegated to. Unlike /// [DelegatingIterable], this allows the base to be created on demand. abstract class _DelegatingIterableBase<E> implements Iterable<E> { Iterable<E> get _base; const _DelegatingIterableBase(); @override bool any(bool Function(E) test) => _base.any(test); @override Iterable<T> cast<T>() => _base.cast<T>(); @override bool contains(Object element) => _base.contains(element); @override E elementAt(int index) => _base.elementAt(index); @override bool every(bool Function(E) test) => _base.every(test); @override Iterable<T> expand<T>(Iterable<T> Function(E) f) => _base.expand(f); @override E get first => _base.first; @override E firstWhere(bool Function(E) test, {E Function() orElse}) => _base.firstWhere(test, orElse: orElse); @override T fold<T>(T initialValue, T Function(T previousValue, E element) combine) => _base.fold(initialValue, combine); @override Iterable<E> followedBy(Iterable<E> other) => _base.followedBy(other); @override void forEach(void Function(E) f) => _base.forEach(f); @override bool get isEmpty => _base.isEmpty; @override bool get isNotEmpty => _base.isNotEmpty; @override Iterator<E> get iterator => _base.iterator; @override String join([String separator = '']) => _base.join(separator); @override E get last => _base.last; @override E lastWhere(bool Function(E) test, {E Function() orElse}) => _base.lastWhere(test, orElse: orElse); @override int get length => _base.length; @override Iterable<T> map<T>(T Function(E) f) => _base.map(f); @override E reduce(E Function(E value, E element) combine) => _base.reduce(combine); @deprecated Iterable<T> retype<T>() => cast<T>(); @override E get single => _base.single; @override E singleWhere(bool Function(E) test, {E Function() orElse}) { return _base.singleWhere(test, orElse: orElse); } @override Iterable<E> skip(int n) => _base.skip(n); @override Iterable<E> skipWhile(bool Function(E) test) => _base.skipWhile(test); @override Iterable<E> take(int n) => _base.take(n); @override Iterable<E> takeWhile(bool Function(E) test) => _base.takeWhile(test); @override List<E> toList({bool growable = true}) => _base.toList(growable: growable); @override Set<E> toSet() => _base.toSet(); @override Iterable<E> where(bool Function(E) test) => _base.where(test); @override Iterable<T> whereType<T>() => _base.whereType<T>(); @override String toString() => _base.toString(); } /// An [Iterable] that delegates all operations to a base iterable. /// /// This class can be used to hide non-`Iterable` methods of an iterable object, /// or it can be extended to add extra functionality on top of an existing /// iterable object. class DelegatingIterable<E> extends _DelegatingIterableBase<E> { @override final Iterable<E> _base; /// Creates a wrapper that forwards operations to [base]. const DelegatingIterable(Iterable<E> base) : _base = base; /// Creates a wrapper that asserts the types of values in [base]. /// /// This soundly converts an [Iterable] without a generic type to an /// `Iterable<E>` by asserting that its elements are instances of `E` whenever /// they're accessed. If they're not, it throws a [CastError]. /// /// This forwards all operations to [base], so any changes in [base] will be /// reflected in [this]. If [base] is already an `Iterable<E>`, it's returned /// unmodified. @Deprecated('Use iterable.cast<E> instead.') static Iterable<E> typed<E>(Iterable base) => base.cast<E>(); } /// A [List] that delegates all operations to a base list. /// /// This class can be used to hide non-`List` methods of a list object, or it /// can be extended to add extra functionality on top of an existing list /// object. class DelegatingList<E> extends DelegatingIterable<E> implements List<E> { const DelegatingList(List<E> base) : super(base); /// Creates a wrapper that asserts the types of values in [base]. /// /// This soundly converts a [List] without a generic type to a `List<E>` by /// asserting that its elements are instances of `E` whenever they're /// accessed. If they're not, it throws a [CastError]. Note that even if an /// operation throws a [CastError], it may still mutate the underlying /// collection. /// /// This forwards all operations to [base], so any changes in [base] will be /// reflected in [this]. If [base] is already a `List<E>`, it's returned /// unmodified. @Deprecated('Use list.cast<E> instead.') static List<E> typed<E>(List base) => base.cast<E>(); List<E> get _listBase => _base; @override E operator [](int index) => _listBase[index]; @override void operator []=(int index, E value) { _listBase[index] = value; } @override List<E> operator +(List<E> other) => _listBase + other; @override void add(E value) { _listBase.add(value); } @override void addAll(Iterable<E> iterable) { _listBase.addAll(iterable); } @override Map<int, E> asMap() => _listBase.asMap(); @override List<T> cast<T>() => _listBase.cast<T>(); @override void clear() { _listBase.clear(); } @override void fillRange(int start, int end, [E fillValue]) { _listBase.fillRange(start, end, fillValue); } @override set first(E value) { if (isEmpty) throw RangeError.index(0, this); this[0] = value; } @override Iterable<E> getRange(int start, int end) => _listBase.getRange(start, end); @override int indexOf(E element, [int start = 0]) => _listBase.indexOf(element, start); @override int indexWhere(bool Function(E) test, [int start = 0]) => _listBase.indexWhere(test, start); @override void insert(int index, E element) { _listBase.insert(index, element); } @override void insertAll(int index, Iterable<E> iterable) { _listBase.insertAll(index, iterable); } @override set last(E value) { if (isEmpty) throw RangeError.index(0, this); this[length - 1] = value; } @override int lastIndexOf(E element, [int start]) => _listBase.lastIndexOf(element, start); @override int lastIndexWhere(bool Function(E) test, [int start]) => _listBase.lastIndexWhere(test, start); @override set length(int newLength) { _listBase.length = newLength; } @override bool remove(Object value) => _listBase.remove(value); @override E removeAt(int index) => _listBase.removeAt(index); @override E removeLast() => _listBase.removeLast(); @override void removeRange(int start, int end) { _listBase.removeRange(start, end); } @override void removeWhere(bool Function(E) test) { _listBase.removeWhere(test); } @override void replaceRange(int start, int end, Iterable<E> iterable) { _listBase.replaceRange(start, end, iterable); } @override void retainWhere(bool Function(E) test) { _listBase.retainWhere(test); } @deprecated @override List<T> retype<T>() => cast<T>(); @override Iterable<E> get reversed => _listBase.reversed; @override void setAll(int index, Iterable<E> iterable) { _listBase.setAll(index, iterable); } @override void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) { _listBase.setRange(start, end, iterable, skipCount); } @override void shuffle([math.Random random]) { _listBase.shuffle(random); } @override void sort([int Function(E, E) compare]) { _listBase.sort(compare); } @override List<E> sublist(int start, [int end]) => _listBase.sublist(start, end); } /// A [Set] that delegates all operations to a base set. /// /// This class can be used to hide non-`Set` methods of a set object, or it can /// be extended to add extra functionality on top of an existing set object. class DelegatingSet<E> extends DelegatingIterable<E> implements Set<E> { const DelegatingSet(Set<E> base) : super(base); /// Creates a wrapper that asserts the types of values in [base]. /// /// This soundly converts a [Set] without a generic type to a `Set<E>` by /// asserting that its elements are instances of `E` whenever they're /// accessed. If they're not, it throws a [CastError]. Note that even if an /// operation throws a [CastError], it may still mutate the underlying /// collection. /// /// This forwards all operations to [base], so any changes in [base] will be /// reflected in [this]. If [base] is already a `Set<E>`, it's returned /// unmodified. @Deprecated('Use set.cast<E> instead.') static Set<E> typed<E>(Set base) => base.cast<E>(); Set<E> get _setBase => _base; @override bool add(E value) => _setBase.add(value); @override void addAll(Iterable<E> elements) { _setBase.addAll(elements); } @override Set<T> cast<T>() => _setBase.cast<T>(); @override void clear() { _setBase.clear(); } @override bool containsAll(Iterable<Object> other) => _setBase.containsAll(other); @override Set<E> difference(Set<Object> other) => _setBase.difference(other); @override Set<E> intersection(Set<Object> other) => _setBase.intersection(other); @override E lookup(Object element) => _setBase.lookup(element); @override bool remove(Object value) => _setBase.remove(value); @override void removeAll(Iterable<Object> elements) { _setBase.removeAll(elements); } @override void removeWhere(bool Function(E) test) { _setBase.removeWhere(test); } @override void retainAll(Iterable<Object> elements) { _setBase.retainAll(elements); } @deprecated @override Set<T> retype<T>() => cast<T>(); @override void retainWhere(bool Function(E) test) { _setBase.retainWhere(test); } @override Set<E> union(Set<E> other) => _setBase.union(other); @override Set<E> toSet() => DelegatingSet<E>(_setBase.toSet()); } /// A [Queue] that delegates all operations to a base queue. /// /// This class can be used to hide non-`Queue` methods of a queue object, or it /// can be extended to add extra functionality on top of an existing queue /// object. class DelegatingQueue<E> extends DelegatingIterable<E> implements Queue<E> { const DelegatingQueue(Queue<E> queue) : super(queue); /// Creates a wrapper that asserts the types of values in [base]. /// /// This soundly converts a [Queue] without a generic type to a `Queue<E>` by /// asserting that its elements are instances of `E` whenever they're /// accessed. If they're not, it throws a [CastError]. Note that even if an /// operation throws a [CastError], it may still mutate the underlying /// collection. /// /// This forwards all operations to [base], so any changes in [base] will be /// reflected in [this]. If [base] is already a `Queue<E>`, it's returned /// unmodified. @Deprecated('Use queue.cast<E> instead.') static Queue<E> typed<E>(Queue base) => base.cast<E>(); Queue<E> get _baseQueue => _base; @override void add(E value) { _baseQueue.add(value); } @override void addAll(Iterable<E> iterable) { _baseQueue.addAll(iterable); } @override void addFirst(E value) { _baseQueue.addFirst(value); } @override void addLast(E value) { _baseQueue.addLast(value); } @override Queue<T> cast<T>() => _baseQueue.cast<T>(); @override void clear() { _baseQueue.clear(); } @override bool remove(Object object) => _baseQueue.remove(object); @override void removeWhere(bool Function(E) test) { _baseQueue.removeWhere(test); } @override void retainWhere(bool Function(E) test) { _baseQueue.retainWhere(test); } @deprecated @override Queue<T> retype<T>() => cast<T>(); @override E removeFirst() => _baseQueue.removeFirst(); @override E removeLast() => _baseQueue.removeLast(); } /// A [Map] that delegates all operations to a base map. /// /// This class can be used to hide non-`Map` methods of an object that extends /// `Map`, or it can be extended to add extra functionality on top of an /// existing map object. class DelegatingMap<K, V> implements Map<K, V> { final Map<K, V> _base; const DelegatingMap(Map<K, V> base) : _base = base; /// Creates a wrapper that asserts the types of keys and values in [base]. /// /// This soundly converts a [Map] without generic types to a `Map<K, V>` by /// asserting that its keys are instances of `E` and its values are instances /// of `V` whenever they're accessed. If they're not, it throws a [CastError]. /// Note that even if an operation throws a [CastError], it may still mutate /// the underlying collection. /// /// This forwards all operations to [base], so any changes in [base] will be /// reflected in [this]. If [base] is already a `Map<K, V>`, it's returned /// unmodified. @Deprecated('Use map.cast<K, V> instead.') static Map<K, V> typed<K, V>(Map base) => base.cast<K, V>(); @override V operator [](Object key) => _base[key]; @override void operator []=(K key, V value) { _base[key] = value; } @override void addAll(Map<K, V> other) { _base.addAll(other); } @override void addEntries(Iterable<MapEntry<K, V>> entries) { _base.addEntries(entries); } @override void clear() { _base.clear(); } @override Map<K2, V2> cast<K2, V2>() => _base.cast<K2, V2>(); @override bool containsKey(Object key) => _base.containsKey(key); @override bool containsValue(Object value) => _base.containsValue(value); @override Iterable<MapEntry<K, V>> get entries => _base.entries; @override void forEach(void Function(K, V) f) { _base.forEach(f); } @override bool get isEmpty => _base.isEmpty; @override bool get isNotEmpty => _base.isNotEmpty; @override Iterable<K> get keys => _base.keys; @override int get length => _base.length; @override Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> Function(K, V) transform) => _base.map(transform); @override V putIfAbsent(K key, V Function() ifAbsent) => _base.putIfAbsent(key, ifAbsent); @override V remove(Object key) => _base.remove(key); @override void removeWhere(bool Function(K, V) test) => _base.removeWhere(test); @deprecated Map<K2, V2> retype<K2, V2>() => cast<K2, V2>(); @override Iterable<V> get values => _base.values; @override String toString() => _base.toString(); @override V update(K key, V Function(V) update, {V Function() ifAbsent}) => _base.update(key, update, ifAbsent: ifAbsent); @override void updateAll(V Function(K, V) update) => _base.updateAll(update); } /// An unmodifiable [Set] view of the keys of a [Map]. /// /// The set delegates all operations to the underlying map. /// /// A `Map` can only contain each key once, so its keys can always /// be viewed as a `Set` without any loss, even if the [Map.keys] /// getter only shows an [Iterable] view of the keys. /// /// Note that [lookup] is not supported for this set. class MapKeySet<E> extends _DelegatingIterableBase<E> with UnmodifiableSetMixin<E> { final Map<E, dynamic> _baseMap; MapKeySet(Map<E, dynamic> base) : _baseMap = base; @override Iterable<E> get _base => _baseMap.keys; @override Set<T> cast<T>() { if (this is MapKeySet<T>) { return this as MapKeySet<T>; } return Set.castFrom<E, T>(this); } @override bool contains(Object element) => _baseMap.containsKey(element); @override bool get isEmpty => _baseMap.isEmpty; @override bool get isNotEmpty => _baseMap.isNotEmpty; @override int get length => _baseMap.length; @override String toString() => "{${_base.join(', ')}}"; @override bool containsAll(Iterable<Object> other) => other.every(contains); /// Returns a new set with the the elements of [this] that are not in [other]. /// /// That is, the returned set contains all the elements of this [Set] that are /// not elements of [other] according to `other.contains`. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<E> difference(Set<Object> other) => where((element) => !other.contains(element)).toSet(); /// Returns a new set which is the intersection between [this] and [other]. /// /// That is, the returned set contains all the elements of this [Set] that are /// also elements of [other] according to `other.contains`. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<E> intersection(Set<Object> other) => where(other.contains).toSet(); /// Throws an [UnsupportedError] since there's no corresponding method for /// [Map]s. @override E lookup(Object element) => throw UnsupportedError("MapKeySet doesn't support lookup()."); @deprecated @override Set<T> retype<T>() => Set.castFrom<E, T>(this); /// Returns a new set which contains all the elements of [this] and [other]. /// /// That is, the returned set contains all the elements of this [Set] and all /// the elements of [other]. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<E> union(Set<E> other) => toSet()..addAll(other); } /// Creates a modifiable [Set] view of the values of a [Map]. /// /// The `Set` view assumes that the keys of the `Map` can be uniquely determined /// from the values. The `keyForValue` function passed to the constructor finds /// the key for a single value. The `keyForValue` function should be consistent /// with equality. If `value1 == value2` then `keyForValue(value1)` and /// `keyForValue(value2)` should be considered equal keys by the underlying map, /// and vice versa. /// /// Modifying the set will modify the underlying map based on the key returned /// by `keyForValue`. /// /// If the `Map` contents are not compatible with the `keyForValue` function, /// the set will not work consistently, and may give meaningless responses or do /// inconsistent updates. /// /// This set can, for example, be used on a map from database record IDs to the /// records. It exposes the records as a set, and allows for writing both /// `recordSet.add(databaseRecord)` and `recordMap[id]`. /// /// Effectively, the map will act as a kind of index for the set. class MapValueSet<K, V> extends _DelegatingIterableBase<V> implements Set<V> { final Map<K, V> _baseMap; final K Function(V) _keyForValue; /// Creates a new [MapValueSet] based on [base]. /// /// [keyForValue] returns the key in the map that should be associated with /// the given value. The set's notion of equality is identical to the equality /// of the return values of [keyForValue]. MapValueSet(Map<K, V> base, K Function(V) keyForValue) : _baseMap = base, _keyForValue = keyForValue; @override Iterable<V> get _base => _baseMap.values; @override Set<T> cast<T>() { if (this is Set<T>) { return this as Set<T>; } return Set.castFrom<V, T>(this); } @override bool contains(Object element) { if (element != null && element is! V) return false; var key = _keyForValue(element as V); return _baseMap.containsKey(key); } @override bool get isEmpty => _baseMap.isEmpty; @override bool get isNotEmpty => _baseMap.isNotEmpty; @override int get length => _baseMap.length; @override String toString() => toSet().toString(); @override bool add(V value) { var key = _keyForValue(value); var result = false; _baseMap.putIfAbsent(key, () { result = true; return value; }); return result; } @override void addAll(Iterable<V> elements) => elements.forEach(add); @override void clear() => _baseMap.clear(); @override bool containsAll(Iterable<Object> other) => other.every(contains); /// Returns a new set with the the elements of [this] that are not in [other]. /// /// That is, the returned set contains all the elements of this [Set] that are /// not elements of [other] according to `other.contains`. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<V> difference(Set<Object> other) => where((element) => !other.contains(element)).toSet(); /// Returns a new set which is the intersection between [this] and [other]. /// /// That is, the returned set contains all the elements of this [Set] that are /// also elements of [other] according to `other.contains`. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<V> intersection(Set<Object> other) => where(other.contains).toSet(); @override V lookup(Object element) { if (element != null && element is! V) return null; var key = _keyForValue(element as V); return _baseMap[key]; } @override bool remove(Object element) { if (element != null && element is! V) return false; var key = _keyForValue(element as V); if (!_baseMap.containsKey(key)) return false; _baseMap.remove(key); return true; } @override void removeAll(Iterable<Object> elements) => elements.forEach(remove); @override void removeWhere(bool Function(V) test) { var toRemove = []; _baseMap.forEach((key, value) { if (test(value)) toRemove.add(key); }); toRemove.forEach(_baseMap.remove); } @override void retainAll(Iterable<Object> elements) { var valuesToRetain = Set<V>.identity(); for (var element in elements) { if (element != null && element is! V) continue; var key = _keyForValue(element as V); if (!_baseMap.containsKey(key)) continue; valuesToRetain.add(_baseMap[key]); } var keysToRemove = []; _baseMap.forEach((k, v) { if (!valuesToRetain.contains(v)) keysToRemove.add(k); }); keysToRemove.forEach(_baseMap.remove); } @override void retainWhere(bool Function(V) test) => removeWhere((element) => !test(element)); @deprecated @override Set<T> retype<T>() => Set.castFrom<V, T>(this); /// Returns a new set which contains all the elements of [this] and [other]. /// /// That is, the returned set contains all the elements of this [Set] and all /// the elements of [other]. /// /// Note that the returned set will use the default equality operation, which /// may be different than the equality operation [this] uses. @override Set<V> union(Set<V> other) => toSet()..addAll(other); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/unmodifiable_wrappers.dart
// 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 'empty_unmodifiable_set.dart'; import 'wrappers.dart'; export 'dart:collection' show UnmodifiableListView, UnmodifiableMapView; /// A fixed-length list. /// /// A `NonGrowableListView` contains a [List] object and ensures that /// its length does not change. /// Methods that would change the length of the list, /// such as [add] and [remove], throw an [UnsupportedError]. /// All other methods work directly on the underlying list. /// /// This class _does_ allow changes to the contents of the wrapped list. /// You can, for example, [sort] the list. /// Permitted operations defer to the wrapped list. class NonGrowableListView<E> extends DelegatingList<E> with NonGrowableListMixin<E> { NonGrowableListView(List<E> listBase) : super(listBase); } /// Mixin class that implements a throwing version of all list operations that /// change the List's length. abstract class NonGrowableListMixin<E> implements List<E> { static T _throw<T>() { throw UnsupportedError('Cannot change the length of a fixed-length list'); } /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override set length(int newLength) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override bool add(E value) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void addAll(Iterable<E> iterable) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void insert(int index, E element) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void insertAll(int index, Iterable<E> iterable) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override bool remove(Object value) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override E removeAt(int index) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override E removeLast() => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void removeWhere(bool Function(E) test) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void retainWhere(bool Function(E) test) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void removeRange(int start, int end) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void replaceRange(int start, int end, Iterable<E> iterable) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the length of the list are disallowed. @override void clear() => _throw(); } /// An unmodifiable set. /// /// An UnmodifiableSetView contains a [Set] object and ensures /// that it does not change. /// Methods that would change the set, /// such as [add] and [remove], throw an [UnsupportedError]. /// Permitted operations defer to the wrapped set. class UnmodifiableSetView<E> extends DelegatingSet<E> with UnmodifiableSetMixin<E> { UnmodifiableSetView(Set<E> setBase) : super(setBase); /// An unmodifiable empty set. /// /// This is the same as `UnmodifiableSetView(Set())`, except that it /// can be used in const contexts. const factory UnmodifiableSetView.empty() = EmptyUnmodifiableSet<E>; } /// Mixin class that implements a throwing version of all set operations that /// change the Set. abstract class UnmodifiableSetMixin<E> implements Set<E> { static T _throw<T>() { throw UnsupportedError('Cannot modify an unmodifiable Set'); } /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override bool add(E value) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void addAll(Iterable<E> elements) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override bool remove(Object value) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void removeAll(Iterable elements) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void retainAll(Iterable elements) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void removeWhere(bool Function(E) test) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void retainWhere(bool Function(E) test) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the set are disallowed. @override void clear() => _throw(); } /// Mixin class that implements a throwing version of all map operations that /// change the Map. abstract class UnmodifiableMapMixin<K, V> implements Map<K, V> { static T _throw<T>() { throw UnsupportedError('Cannot modify an unmodifiable Map'); } /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. @override void operator []=(K key, V value) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. @override V putIfAbsent(K key, V Function() ifAbsent) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. @override void addAll(Map<K, V> other) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. @override V remove(Object key) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. @override void clear() => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. set first(_) => _throw(); /// Throws an [UnsupportedError]; /// operations that change the map are disallowed. set last(_) => _throw(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/equality_map.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'equality.dart'; import 'wrappers.dart'; /// A [Map] whose key equality is determined by an [Equality] object. class EqualityMap<K, V> extends DelegatingMap<K, V> { /// Creates a map with equality based on [equality]. EqualityMap(Equality<K> equality) : super(LinkedHashMap( equals: equality.equals, hashCode: equality.hash, isValidKey: equality.isValidKey)); /// Creates a map with equality based on [equality] that contains all /// key-value pairs of [other]. /// /// If [other] has multiple keys that are equivalent according to [equality], /// the last one reached during iteration takes precedence. EqualityMap.from(Equality<K> equality, Map<K, V> other) : super(LinkedHashMap( equals: equality.equals, hashCode: equality.hash, isValidKey: equality.isValidKey)) { addAll(other); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/union_set.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'unmodifiable_wrappers.dart'; /// A single set that provides a view of the union over a set of sets. /// /// Since this is just a view, it reflects all changes in the underlying sets. /// /// If an element is in multiple sets and the outer set is ordered, the version /// in the earliest inner set is preferred. Component sets are assumed to use /// `==` and `hashCode` for equality. class UnionSet<E> extends SetBase<E> with UnmodifiableSetMixin<E> { /// The set of sets that this provides a view of. final Set<Set<E>> _sets; /// Whether the sets in [_sets] are guaranteed to be disjoint. final bool _disjoint; /// Creates a new set that's a view of the union of all sets in [sets]. /// /// If any sets in [sets] change, this [UnionSet] reflects that change. If a /// new set is added to [sets], this [UnionSet] reflects that as well. /// /// If [disjoint] is `true`, then all component sets must be disjoint. That /// is, that they contain no elements in common. This makes many operations /// including [length] more efficient. If the component sets turn out not to /// be disjoint, some operations may behave inconsistently. UnionSet(this._sets, {bool disjoint = false}) : _disjoint = disjoint; /// Creates a new set that's a view of the union of all sets in [sets]. /// /// If any sets in [sets] change, this [UnionSet] reflects that change. /// However, unlike [new UnionSet], this creates a copy of its parameter, so /// changes in [sets] aren't reflected in this [UnionSet]. /// /// If [disjoint] is `true`, then all component sets must be disjoint. That /// is, that they contain no elements in common. This makes many operations /// including [length] more efficient. If the component sets turn out not to /// be disjoint, some operations may behave inconsistently. UnionSet.from(Iterable<Set<E>> sets, {bool disjoint = false}) : this(sets.toSet(), disjoint: disjoint); @override int get length => _disjoint ? _sets.fold(0, (length, set) => length + set.length) : _iterable.length; @override Iterator<E> get iterator => _iterable.iterator; /// An iterable over the contents of all [_sets]. /// /// If this is not a [_disjoint] union an extra set is used to deduplicate /// values. Iterable<E> get _iterable { var allElements = _sets.expand((set) => set); return _disjoint ? allElements : allElements.where(<E>{}.add); } @override bool contains(Object element) => _sets.any((set) => set.contains(element)); @override E lookup(Object element) { if (element == null) return null; return _sets .map((set) => set.lookup(element)) .firstWhere((result) => result != null, orElse: () => null); } @override Set<E> toSet() { var result = <E>{}; for (var set in _sets) { result.addAll(set); } return result; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/combined_wrappers/combined_list.dart
// 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:collection'; /// A view of several lists combined into a single list. /// /// All methods and accessors treat the [CombinedListView] list as if it were a /// single concatenated list, but the underlying implementation is based on /// lazily accessing individual list instances. This means that if the /// underlying lists change, the [CombinedListView] will reflect those changes. /// /// The index operator (`[]`) and [length] property of a [CombinedListView] are /// both `O(lists)` rather than `O(1)`. A [CombinedListView] is unmodifiable. class CombinedListView<T> extends ListBase<T> implements UnmodifiableListView<T> { static void _throw() { throw UnsupportedError('Cannot modify an unmodifiable List'); } /// The lists that this combines. final List<List<T>> _lists; /// Creates a combined view of [lists]. CombinedListView(this._lists); @override set length(int length) { _throw(); } @override int get length => _lists.fold(0, (length, list) => length + list.length); @override T operator [](int index) { var initialIndex = index; for (var i = 0; i < _lists.length; i++) { var list = _lists[i]; if (index < list.length) { return list[index]; } index -= list.length; } throw RangeError.index(initialIndex, this, 'index', null, length); } @override void operator []=(int index, T value) { _throw(); } @override void clear() { _throw(); } @override bool remove(Object element) { _throw(); return null; } @override void removeWhere(bool Function(T) test) { _throw(); } @override void retainWhere(bool Function(T) test) { _throw(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/combined_wrappers/combined_map.dart
// 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:collection'; import 'combined_iterable.dart'; /// Returns a new map that represents maps flattened into a single map. /// /// All methods and accessors treat the new map as-if it were a single /// concatenated map, but the underlying implementation is based on lazily /// accessing individual map instances. In the occasion where a key occurs in /// multiple maps the first value is returned. /// /// The resulting map has an index operator (`[]`) that is `O(maps)`, rather /// than `O(1)`, and the map is unmodifiable, but underlying changes to these /// maps are still accessible from the resulting map. /// /// The `length` getter is `O(M)` where M is the total number of entries in /// all maps, since it has to remove duplicate entries. class CombinedMapView<K, V> extends UnmodifiableMapBase<K, V> { final Iterable<Map<K, V>> _maps; /// Create a new combined view of multiple maps. /// /// The iterable is accessed lazily so it should be collection type like /// [List] or [Set] rather than a lazy iterable produced by `map()` et al. CombinedMapView(this._maps); @override V operator [](Object key) { for (var map in _maps) { // Avoid two hash lookups on a positive hit. var value = map[key]; if (value != null || map.containsKey(value)) { return value; } } return null; } /// The keys of [this]. /// /// The returned iterable has efficient `contains` operations, assuming the /// iterables returned by the wrapped maps have efficient `contains` operations /// for their `keys` iterables. /// /// The `length` must do deduplication and thus is not optimized. /// /// The order of iteration is defined by the individual `Map` implementations, /// but must be consistent between changes to the maps. /// /// Unlike most [Map] implementations, modifying an individual map while /// iterating the keys will _sometimes_ throw. This behavior may change in /// the future. @override Iterable<K> get keys => _DeduplicatingIterableView( CombinedIterableView(_maps.map((m) => m.keys))); } /// A view of an iterable that skips any duplicate entries. class _DeduplicatingIterableView<T> extends IterableBase<T> { final Iterable<T> _iterable; const _DeduplicatingIterableView(this._iterable); @override Iterator<T> get iterator => _DeduplicatingIterator(_iterable.iterator); // Special cased contains/isEmpty since many iterables have an efficient // implementation instead of running through the entire iterator. // // Note: We do not do this for `length` because we have to remove the // duplicates. @override bool contains(Object element) => _iterable.contains(element); @override bool get isEmpty => _iterable.isEmpty; } /// An iterator that wraps another iterator and skips duplicate values. class _DeduplicatingIterator<T> implements Iterator<T> { final Iterator<T> _iterator; final _emitted = HashSet<T>(); _DeduplicatingIterator(this._iterator); @override T get current => _iterator.current; @override bool moveNext() { while (_iterator.moveNext()) { if (_emitted.add(current)) { return true; } } return false; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/combined_wrappers/combined_iterable.dart
// 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:collection'; /// A view of several iterables combined sequentially into a single iterable. /// /// All methods and accessors treat the [CombinedIterableView] as if it were a /// single concatenated iterable, but the underlying implementation is based on /// lazily accessing individual iterable instances. This means that if the /// underlying iterables change, the [CombinedIterableView] will reflect those /// changes. class CombinedIterableView<T> extends IterableBase<T> { /// The iterables that this combines. final Iterable<Iterable<T>> _iterables; /// Creates a combined view of [iterables]. const CombinedIterableView(this._iterables); @override Iterator<T> get iterator => _CombinedIterator<T>(_iterables.map((i) => i.iterator).iterator); // Special cased contains/isEmpty/length since many iterables have an // efficient implementation instead of running through the entire iterator. @override bool contains(Object element) => _iterables.any((i) => i.contains(element)); @override bool get isEmpty => _iterables.every((i) => i.isEmpty); @override int get length => _iterables.fold(0, (length, i) => length + i.length); } /// The iterator for [CombinedIterableView]. /// /// This moves through each iterable's iterators in sequence. class _CombinedIterator<T> implements Iterator<T> { /// The iterators that this combines. /// /// Because this comes from a call to [Iterable.map], it's lazy and will /// avoid instantiating unnecessary iterators. final Iterator<Iterator<T>> _iterators; _CombinedIterator(this._iterators); @override T get current => _iterators.current?.current; @override bool moveNext() { var current = _iterators.current; if (current != null && current.moveNext()) { return true; } return _iterators.moveNext() && moveNext(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/dart_style.dart
// 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 dart_style; export 'src/dart_formatter.dart'; export 'src/exceptions.dart'; export 'src/style_fix.dart'; export 'src/source_code.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/call_chain_visitor.dart
// 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 dart_style.src.call_chain_visitor; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'argument_list_visitor.dart'; import 'rule/argument.dart'; import 'rule/rule.dart'; import 'source_visitor.dart'; /// Helper class for [SourceVisitor] that handles visiting and writing a /// chained series of "selectors": method invocations, property accesses, /// prefixed identifiers, index expressions, and null-assertion operators. /// /// In the AST, selectors are nested bottom up such that this expression: /// /// obj.a(1)[2].c(3) /// /// Is structured like: /// /// .c() /// / \ /// [] 3 /// / \ /// .a() 2 /// / \ /// obj 1 /// /// This means visiting the AST from top down visits the selectors from right /// to left. It's easier to format that if we organize them as a linear series /// of selectors from left to right. Further, we want to organize it into a /// two-tier hierarchy. We have an outer list of method calls and property /// accesses. Then each of those may have one or more postfix selectors /// attached: indexers, null-assertions, or invocations. This mirrors how they /// are formatted. class CallChainVisitor { final SourceVisitor _visitor; /// The initial target of the call chain. /// /// This may be any expression except [MethodInvocation], [PropertyAccess] or /// [PrefixedIdentifier]. final Expression _target; /// The list of dotted names ([PropertyAccess] and [PrefixedIdentifier]) at /// the start of the call chain. /// /// This will be empty if the [_target] is not a [SimpleIdentifier]. final List<_Selector> _properties; /// The mixed method calls and property accesses in the call chain in the /// order that they appear in the source reading from left to right. final List<_Selector> _calls; /// The method calls containing block function literals that break the method /// chain and escape its indentation. /// /// receiver.a().b().c(() { /// ; /// }).d(() { /// ; /// }).e(); /// /// Here, it will contain `c` and `d`. /// /// The block calls must be contiguous and must be a suffix of the list of /// calls (except for the one allowed hanging call). Otherwise, none of them /// are treated as block calls: /// /// receiver /// .a() /// .b(() { /// ; /// }) /// .c(() { /// ; /// }) /// .d() /// .e(); final List<_MethodSelector> _blockCalls; /// If there is one or more block calls and a single chained expression after /// that, this will be that expression. /// /// receiver.a().b().c(() { /// ; /// }).d(() { /// ; /// }).e(); /// /// We allow a single hanging call after the blocks because it will never /// need to split before its `.` and this accommodates the common pattern of /// a trailing `toList()` or `toSet()` after a series of higher-order methods /// on an iterable. final _Selector _hangingCall; /// Whether or not a [Rule] is currently active for the call chain. bool _ruleEnabled = false; /// Whether or not the span wrapping the call chain is currently active. bool _spanEnded = false; /// After the properties are visited (if there are any), this will be the /// rule used to split between them. PositionalRule _propertyRule; /// Creates a new call chain visitor for [visitor] for the method chain /// contained in [node]. /// /// The [node] is the outermost expression containing the chained "." /// operators and must be a [MethodInvocation], [PropertyAccess] or /// [PrefixedIdentifier]. factory CallChainVisitor(SourceVisitor visitor, Expression node) { // Flatten the call chain tree to a list of selectors with postfix // expressions. var calls = <_Selector>[]; var target = _unwrapTarget(node, calls); // An expression that starts with a series of dotted names gets treated a // little specially. We don't force leading properties to split with the // rest of the chain. Allows code like: // // address.street.number // .toString() // .length; var properties = <_Selector>[]; if (_unwrapNullAssertion(target) is SimpleIdentifier) { properties = calls.takeWhile((call) => call.isProperty).toList(); } calls.removeRange(0, properties.length); // Separate out the block calls, if there are any. List<_MethodSelector> blockCalls; _Selector hangingCall; var inBlockCalls = false; for (var call in calls) { if (call.isBlockCall(visitor)) { inBlockCalls = true; blockCalls ??= []; blockCalls.add(call); } else if (inBlockCalls) { // We found a non-block call after a block call. if (call == calls.last) { // It's the one allowed hanging one, so it's OK. hangingCall = call; break; } // Don't allow any of the calls to be block formatted. blockCalls = null; break; } } if (blockCalls != null) { for (var blockCall in blockCalls) { calls.remove(blockCall); } } if (hangingCall != null) { calls.remove(hangingCall); } return CallChainVisitor._( visitor, target, properties, calls, blockCalls, hangingCall); } CallChainVisitor._(this._visitor, this._target, this._properties, this._calls, this._blockCalls, this._hangingCall); /// Builds chunks for the call chain. /// /// If [unnest] is `false` than this will not close the expression nesting /// created for the call chain and the caller must end it. Used by cascades /// to force a cascade after a method chain to be more deeply nested than /// the methods. void visit({bool unnest}) { if (unnest == null) unnest = true; _visitor.builder.nestExpression(); // Try to keep the entire method invocation one line. _visitor.builder.startSpan(); // If a split in the target expression forces the first `.` to split, then // start the rule now so that it surrounds the target. var splitOnTarget = _forcesSplit(_target); if (splitOnTarget) { if (_properties.length > 1) { _propertyRule = PositionalRule(null, 0, 0); _visitor.builder.startLazyRule(_propertyRule); } else { _enableRule(lazy: true); } } _visitor.visit(_target); // Leading properties split like positional arguments: either not at all, // before one ".", or before all of them. if (_properties.length == 1) { _visitor.soloZeroSplit(); _properties.single.write(this); } else if (_properties.length > 1) { if (!splitOnTarget) { _propertyRule = PositionalRule(null, 0, 0); _visitor.builder.startRule(_propertyRule); } for (var property in _properties) { _propertyRule.beforeArgument(_visitor.zeroSplit()); property.write(this); } _visitor.builder.endRule(); } // Indent any block arguments in the chain that don't get special formatting // below. Only do this if there is more than one argument to avoid spurious // indentation in cases like: // // object.method(wrapper(() { // body; // }); // TODO(rnystrom): Come up with a less arbitrary way to express this? if (_calls.length > 1) _visitor.builder.startBlockArgumentNesting(); // The chain of calls splits atomically (either all or none). Any block // arguments inside them get indented to line up with the `.`. for (var call in _calls) { _enableRule(); _visitor.zeroSplit(); call.write(this); } if (_calls.length > 1) _visitor.builder.endBlockArgumentNesting(); // If there are block calls, end the chain and write those without any // extra indentation. if (_blockCalls != null) { _enableRule(); _visitor.zeroSplit(); _disableRule(); for (var blockCall in _blockCalls) { blockCall.write(this); } // If there is a hanging call after the last block, write it without any // split before the ".". _hangingCall?.write(this); } _disableRule(); _endSpan(); if (unnest) _visitor.builder.unnest(); } /// Returns `true` if the method chain should split if a split occurs inside /// [expression]. /// /// In most cases, splitting in a method chain's target forces the chain to /// split too: /// /// receiver(very, long, argument, /// list) // <-- Split here... /// .method(); // ...forces split here. /// /// However, if the target is a collection or function literal (or an /// argument list ending in one of those), we don't want to split: /// /// receiver(inner(() { /// ; /// }).method(); // <-- Unsplit. bool _forcesSplit(Expression expression) { // TODO(rnystrom): Other cases we may want to consider handling and // recursing into: // * The right operand in an infix operator call. // * The body of a `=>` function. // Unwrap parentheses. while (expression is ParenthesizedExpression) { expression = (expression as ParenthesizedExpression).expression; } // Don't split right after a collection literal. if (expression is ListLiteral) return false; if (expression is SetOrMapLiteral) return false; // Don't split right after a non-empty curly-bodied function. if (expression is FunctionExpression) { if (expression.body is! BlockFunctionBody) return false; return (expression.body as BlockFunctionBody).block.statements.isEmpty; } // If the expression ends in an argument list, base the splitting on the // last argument. ArgumentList argumentList; if (expression is MethodInvocation) { argumentList = expression.argumentList; } else if (expression is InstanceCreationExpression) { argumentList = expression.argumentList; } else if (expression is FunctionExpressionInvocation) { argumentList = expression.argumentList; } // Any other kind of expression always splits. if (argumentList == null) return true; if (argumentList.arguments.isEmpty) return true; var argument = argumentList.arguments.last; // If the argument list has a trailing comma, treat it like a collection. if (_visitor.hasCommaAfter(argument)) return false; if (argument is NamedExpression) { argument = (argument as NamedExpression).expression; } // TODO(rnystrom): This logic is similar (but not identical) to // ArgumentListVisitor.hasBlockArguments. They overlap conceptually and // both have their own peculiar heuristics. It would be good to unify and // rationalize them. return _forcesSplit(argument); } /// Called when a [_MethodSelector] has written its name and is about to /// write the argument list. void _beforeMethodArguments(_MethodSelector selector) { // If we don't have any block calls, stop the rule after the last method // call name, but before its arguments. This allows unsplit chains where // the last argument list wraps, like: // // foo().bar().baz( // argument, list); if (_blockCalls == null && _calls.isNotEmpty && selector == _calls.last) { _disableRule(); } // For a single method call on an identifier, stop the span before the // arguments to make it easier to keep the call name with the target. In // other words, prefer: // // target.method( // argument, list); // // Over: // // target // .method(argument, list); // // Alternatively, the way to think of this is try to avoid splitting on the // "." when calling a single method on a single name. This is especially // important because the identifier is often a library prefix, and splitting // there looks really odd. if (_properties.isEmpty && _calls.length == 1 && _blockCalls == null && _target is SimpleIdentifier) { _endSpan(); } } /// If a [Rule] for the method chain is currently active, ends it. void _disableRule() { if (_ruleEnabled == false) return; _visitor.builder.endRule(); _ruleEnabled = false; } /// Creates a new method chain [Rule] if one is not already active. void _enableRule({bool lazy = false}) { if (_ruleEnabled) return; // If the properties split, force the calls to split too. var rule = Rule(); if (_propertyRule != null) _propertyRule.setNamedArgsRule(rule); if (lazy) { _visitor.builder.startLazyRule(rule); } else { _visitor.builder.startRule(rule); } _ruleEnabled = true; } /// Ends the span wrapping the call chain if it hasn't ended already. void _endSpan() { if (_spanEnded) return; _visitor.builder.endSpan(); _spanEnded = true; } } /// One "selector" in a method call chain. /// /// Each selector is a method call or property access. It may be followed by /// one or more postfix expressions, which can be index expressions or /// null-assertion operators. These are not treated like their own selectors /// because the formatter attaches them to the previous method call or property /// access: /// /// receiver /// .method(arg)[index] /// .another()! /// .third(); abstract class _Selector { /// The series of index and/or null-assertion postfix selectors that follow /// and are attached to this one. /// /// Elements in this list will either be [IndexExpression] or /// [PostfixExpression]. final List<Expression> _postfixes = []; /// Whether this selector is a property access as opposed to a method call. bool get isProperty => true; /// Whether this selector is a method call whose arguments are block /// formatted. bool isBlockCall(SourceVisitor visitor) => false; /// Write the selector portion of the expression wrapped by this [_Selector] /// using [visitor], followed by any postfix selectors. void write(CallChainVisitor visitor) { writeSelector(visitor); // Write any trailing index and null-assertion operators. visitor._visitor.builder.nestExpression(); for (var postfix in _postfixes) { if (postfix is FunctionExpressionInvocation) { // Allow splitting between the invocations if needed. visitor._visitor.soloZeroSplit(); visitor._visitor.visit(postfix.typeArguments); visitor._visitor.visitArgumentList(postfix.argumentList); } else if (postfix is IndexExpression) { visitor._visitor.finishIndexExpression(postfix); } else if (postfix is PostfixExpression) { assert(postfix.operator.type == TokenType.BANG); visitor._visitor.token(postfix.operator); } else { // Unexpected type. assert(false); } } visitor._visitor.builder.unnest(); } /// Subclasses implement this to write their selector. void writeSelector(CallChainVisitor visitor); } class _MethodSelector extends _Selector { final MethodInvocation _node; _MethodSelector(this._node); bool get isProperty => false; bool isBlockCall(SourceVisitor visitor) => ArgumentListVisitor(visitor, _node.argumentList).hasBlockArguments; void writeSelector(CallChainVisitor visitor) { visitor._visitor.token(_node.operator); visitor._visitor.token(_node.methodName.token); visitor._beforeMethodArguments(this); visitor._visitor.builder.nestExpression(); visitor._visitor.visit(_node.typeArguments); visitor._visitor .visitArgumentList(_node.argumentList, nestExpression: false); visitor._visitor.builder.unnest(); } } class _PrefixedSelector extends _Selector { final PrefixedIdentifier _node; _PrefixedSelector(this._node); void writeSelector(CallChainVisitor visitor) { visitor._visitor.token(_node.period); visitor._visitor.visit(_node.identifier); } } class _PropertySelector extends _Selector { final PropertyAccess _node; _PropertySelector(this._node); void writeSelector(CallChainVisitor visitor) { visitor._visitor.token(_node.operator); visitor._visitor.visit(_node.propertyName); } } /// If [expression] is a null-assertion operator, returns its operand. Expression _unwrapNullAssertion(Expression expression) { if (expression is PostfixExpression && expression.operator.type == TokenType.BANG) { return expression.operand; } return expression; } /// Given [node], which is the outermost expression for some call chain, /// recursively traverses the selectors to fill in the list of [calls]. /// /// Returns the remaining target expression that precedes the method chain. /// For example, given: /// /// foo.bar()!.baz[0][1].bang() /// /// This returns `foo` and fills calls with: /// /// selector postfixes /// -------- --------- /// .bar() ! /// .baz [0], [1] /// .bang() Expression _unwrapTarget(Expression node, List<_Selector> calls) { // Don't include things that look like static method or constructor // calls in the call chain because that tends to split up named // constructors from their class. if (SourceVisitor.looksLikeStaticCall(node)) return node; // Selectors. if (node is MethodInvocation && node.target != null) { return _unwrapSelector(node.target, _MethodSelector(node), calls); } if (node is PropertyAccess && node.target != null) { return _unwrapSelector(node.target, _PropertySelector(node), calls); } if (node is PrefixedIdentifier) { return _unwrapSelector(node.prefix, _PrefixedSelector(node), calls); } // Postfix expressions. if (node is IndexExpression) { return _unwrapPostfix(node, node.target, calls); } if (node is FunctionExpressionInvocation) { return _unwrapPostfix(node, node.function, calls); } if (node is PostfixExpression && node.operator.type == TokenType.BANG) { return _unwrapPostfix(node, node.operand, calls); } // Otherwise, it isn't a selector so we're done. return node; } Expression _unwrapPostfix( Expression node, Expression target, List<_Selector> calls) { target = _unwrapTarget(target, calls); // If we don't have a preceding selector to hang the postfix expression off // of, don't unwrap it and leave it attached to the target expression. For // example: // // (list + another)[index] if (calls.isEmpty) return node; calls.last._postfixes.add(node); return target; } Expression _unwrapSelector( Expression target, _Selector selector, List<_Selector> calls) { target = _unwrapTarget(target, calls); calls.add(selector); return target; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/exceptions.dart
// 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 dart_style.src.formatter_exception; import 'package:analyzer/error/error.dart'; import 'package:source_span/source_span.dart'; /// Thrown when one or more errors occurs while parsing the code to be /// formatted. class FormatterException implements Exception { /// The [AnalysisError]s that occurred. final List<AnalysisError> errors; /// Creates a new FormatterException with an optional error [message]. const FormatterException(this.errors); /// Creates a human-friendly representation of the analysis errors. String message({bool color}) { var buffer = StringBuffer(); buffer.writeln("Could not format because the source could not be parsed:"); // In case we get a huge series of cascaded errors, just show the first few. var shownErrors = errors; if (errors.length > 10) shownErrors = errors.take(10).toList(); for (var error in shownErrors) { var source = error.source.contents.data; // If the parse error is for something missing from the end of the file, // the error position will go past the end of the source. In that case, // just pad the source with spaces so we can report it nicely. if (error.offset + error.length > source.length) { source += " " * (error.offset + error.length - source.length); } var file = SourceFile.fromString(source, url: error.source.fullName); var span = file.span(error.offset, error.offset + error.length); if (buffer.isNotEmpty) buffer.writeln(); buffer.write(span.message(error.message, color: color)); } if (shownErrors.length != errors.length) { buffer.writeln(); buffer.write("(${errors.length - shownErrors.length} more errors...)"); } return buffer.toString(); } String toString() => message(); } /// Exception thrown when the internal sanity check that only whitespace /// changes are made fails. class UnexpectedOutputException implements Exception { /// The source being formatted. final String _input; /// The resulting output. final String _output; UnexpectedOutputException(this._input, this._output); String toString() { return """The formatter produced unexpected output. Input was: $_input Which formatted to: $_output"""; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/error_listener.dart
// 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 dart_style.src.error_listener; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'exceptions.dart'; /// A simple [AnalysisErrorListener] that just collects the reported errors. class ErrorListener implements AnalysisErrorListener { final _errors = <AnalysisError>[]; void onError(AnalysisError error) { // Fasta produces some semantic errors, which we want to ignore so that // users can format code containing static errors. if (error.errorCode.type != ErrorType.SYNTACTIC_ERROR) return; _errors.add(error); } /// Throws a [FormatterException] if any errors have been reported. void throwIfErrors() { if (_errors.isEmpty) return; throw FormatterException(_errors); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/source_code.dart
// 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 dart_style.src.source_code; /// Describes a chunk of source code that is to be formatted or has been /// formatted. class SourceCode { /// The [uri] where the source code is from. /// /// Used in error messages if the code cannot be parsed. final String uri; /// The Dart source code text. final String text; /// Whether the source is a compilation unit or a bare statement. final bool isCompilationUnit; /// The offset in [text] where the selection begins, or `null` if there is /// no selection. final int selectionStart; /// The number of selected characters or `null` if there is no selection. final int selectionLength; /// Gets the source code before the beginning of the selection. /// /// If there is no selection, returns [text]. String get textBeforeSelection { if (selectionStart == null) return text; return text.substring(0, selectionStart); } /// Gets the selected source code, if any. /// /// If there is no selection, returns an empty string. String get selectedText { if (selectionStart == null) return ""; return text.substring(selectionStart, selectionStart + selectionLength); } /// Gets the source code following the selection. /// /// If there is no selection, returns an empty string. String get textAfterSelection { if (selectionStart == null) return ""; return text.substring(selectionStart + selectionLength); } SourceCode(this.text, {this.uri, this.isCompilationUnit = true, this.selectionStart, this.selectionLength}) { // Must either provide both selection bounds or neither. if ((selectionStart == null) != (selectionLength == null)) { throw ArgumentError( "Is selectionStart is provided, selectionLength must be too."); } if (selectionStart != null) { if (selectionStart < 0) { throw ArgumentError("selectionStart must be non-negative."); } if (selectionStart > text.length) { throw ArgumentError("selectionStart must be within text."); } } if (selectionLength != null) { if (selectionLength < 0) { throw ArgumentError("selectionLength must be non-negative."); } if (selectionStart + selectionLength > text.length) { throw ArgumentError("selectionLength must end within text."); } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/debug.dart
// 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. /// Internal debugging utilities. library dart_style.src.debug; import 'dart:math' as math; import 'chunk.dart'; import 'line_splitting/rule_set.dart'; /// Set this to `true` to turn on diagnostic output while building chunks. bool traceChunkBuilder = false; /// Set this to `true` to turn on diagnostic output while writing lines. bool traceLineWriter = false; /// Set this to `true` to turn on diagnostic output while line splitting. bool traceSplitter = false; bool useAnsiColors = false; const unicodeSection = "\u00a7"; const unicodeMidDot = "\u00b7"; /// The whitespace prefixing each line of output. String _indent = ""; void indent() { _indent = " $_indent"; } void unindent() { _indent = _indent.substring(2); } /// Constants for ANSI color escape codes. final _gray = _color("\u001b[1;30m"); final _green = _color("\u001b[32m"); final _none = _color("\u001b[0m"); final _bold = _color("\u001b[1m"); /// Prints [message] to stdout with each line correctly indented. void log([message]) { if (message == null) { print(""); return; } print(_indent + message.toString().replaceAll("\n", "\n$_indent")); } /// Wraps [message] in gray ANSI escape codes if enabled. String gray(message) => "$_gray$message$_none"; /// Wraps [message] in green ANSI escape codes if enabled. String green(message) => "$_green$message$_none"; /// Wraps [message] in bold ANSI escape codes if enabled. String bold(message) => "$_bold$message$_none"; /// Prints [chunks] to stdout, one chunk per line, with detailed information /// about each chunk. void dumpChunks(int start, List<Chunk> chunks) { if (chunks.skip(start).isEmpty) return; // Show the spans as vertical bands over their range (unless there are too // many). var spanSet = Set<Span>(); addSpans(List<Chunk> chunks) { for (var chunk in chunks) { spanSet.addAll(chunk.spans); if (chunk.isBlock) addSpans(chunk.block.chunks); } } addSpans(chunks); var spans = spanSet.toList(); var rules = chunks.map((chunk) => chunk.rule).where((rule) => rule != null).toSet(); var rows = <List<String>>[]; addChunk(List<Chunk> chunks, String prefix, int index) { var row = <String>[]; row.add("$prefix$index:"); var chunk = chunks[index]; if (chunk.text.length > 70) { row.add(chunk.text.substring(0, 70)); } else { row.add(chunk.text); } if (spans.length <= 20) { var spanBars = ""; for (var span in spans) { if (chunk.spans.contains(span)) { if (index == 0 || !chunks[index - 1].spans.contains(span)) { if (span.cost == 1) { spanBars += "╖"; } else { spanBars += span.cost.toString(); } } else { spanBars += "║"; } } else { if (index > 0 && chunks[index - 1].spans.contains(span)) { spanBars += "╜"; } else { spanBars += " "; } } } row.add(spanBars); } writeIf(predicate, String callback()) { if (predicate) { row.add(callback()); } else { row.add(""); } } if (chunk.rule == null) { row.add(""); row.add("(no rule)"); row.add(""); } else { writeIf(chunk.rule.cost != 0, () => "\$${chunk.rule.cost}"); var ruleString = chunk.rule.toString(); if (chunk.rule.isHardened) ruleString += "!"; row.add(ruleString); var constrainedRules = chunk.rule.constrainedRules.toSet().intersection(rules); writeIf(constrainedRules.isNotEmpty, () => "-> ${constrainedRules.join(" ")}"); } writeIf(chunk.indent != null && chunk.indent != 0, () => "indent ${chunk.indent}"); writeIf(chunk.nesting != null && chunk.nesting.indent != 0, () => "nest ${chunk.nesting}"); writeIf(chunk.flushLeft != null && chunk.flushLeft, () => "flush"); writeIf(chunk.canDivide, () => "divide"); rows.add(row); if (chunk.isBlock) { for (var j = 0; j < chunk.block.chunks.length; j++) { addChunk(chunk.block.chunks, "$prefix$index.", j); } } } for (var i = start; i < chunks.length; i++) { addChunk(chunks, "", i); } var rowWidths = List.filled(rows.first.length, 0); for (var row in rows) { for (var i = 0; i < row.length; i++) { rowWidths[i] = math.max(rowWidths[i], row[i].length); } } var buffer = StringBuffer(); for (var row in rows) { for (var i = 0; i < row.length; i++) { var cell = row[i].padRight(rowWidths[i]); if (i != 1) cell = gray(cell); buffer.write(cell); buffer.write(" "); } buffer.writeln(); } print(buffer.toString()); } /// Shows all of the constraints between the rules used by [chunks]. void dumpConstraints(List<Chunk> chunks) { var rules = chunks.map((chunk) => chunk.rule).where((rule) => rule != null).toSet(); for (var rule in rules) { var constrainedValues = []; for (var value = 0; value < rule.numValues; value++) { var constraints = []; for (var other in rules) { if (rule == other) continue; var constraint = rule.constrain(value, other); if (constraint != null) { constraints.add("$other->$constraint"); } } if (constraints.isNotEmpty) { constrainedValues.add("$value:(${constraints.join(' ')})"); } } log("$rule ${constrainedValues.join(' ')}"); } } /// Convert the line to a [String] representation. /// /// It will determine how best to split it into multiple lines of output and /// return a single string that may contain one or more newline characters. void dumpLines(List<Chunk> chunks, int firstLineIndent, SplitSet splits) { var buffer = StringBuffer(); writeIndent(indent) => buffer.write(gray("| " * (indent ~/ 2))); writeChunksUnsplit(List<Chunk> chunks) { for (var chunk in chunks) { buffer.write(chunk.text); if (chunk.spaceWhenUnsplit) buffer.write(" "); // Recurse into the block. if (chunk.isBlock) writeChunksUnsplit(chunk.block.chunks); } } writeIndent(firstLineIndent); for (var i = 0; i < chunks.length - 1; i++) { var chunk = chunks[i]; buffer.write(chunk.text); if (splits.shouldSplitAt(i)) { for (var j = 0; j < (chunk.isDouble ? 2 : 1); j++) { buffer.writeln(); writeIndent(splits.getColumn(i)); } } else { if (chunk.isBlock) writeChunksUnsplit(chunk.block.chunks); if (chunk.spaceWhenUnsplit) buffer.write(" "); } } buffer.write(chunks.last.text); log(buffer); } String _color(String ansiEscape) => useAnsiColors ? ansiEscape : "";
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/whitespace.dart
// 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 dart_style.src.whitespace; /// Constants for the number of spaces for various kinds of indentation. class Indent { /// The number of spaces in a block or collection body. static const block = 2; /// How much wrapped cascade sections indent. static const cascade = 2; /// The number of spaces in a single level of expression nesting. static const expression = 4; /// The ":" on a wrapped constructor initialization list. static const constructorInitializer = 4; } /// The kind of pending whitespace that has been "written", but not actually /// physically output yet. /// /// We defer actually writing whitespace until a non-whitespace token is /// encountered to avoid trailing whitespace. class Whitespace { /// No whitespace. static const none = Whitespace._("none"); /// A single non-breaking space. static const space = Whitespace._("space"); /// A single newline. static const newline = Whitespace._("newline"); /// A single newline that takes into account the current expression nesting /// for the next line. static const nestedNewline = Whitespace._("nestedNewline"); /// A single newline with all indentation eliminated at the beginning of the /// next line. /// /// Used for subsequent lines in a multiline string. static const newlineFlushLeft = Whitespace._("newlineFlushLeft"); /// Two newlines, a single blank line of separation. static const twoNewlines = Whitespace._("twoNewlines"); /// A split or newline should be output based on whether the current token is /// on the same line as the previous one or not. /// /// In general, we like to avoid using this because it makes the formatter /// less prescriptive over the user's whitespace. static const splitOrNewline = Whitespace._("splitOrNewline"); /// A split or blank line (two newlines) should be output based on whether /// the current token is on the same line as the previous one or not. /// /// This is used between enum cases, which will collapse if possible but /// also allow a blank line to be preserved between cases. /// /// In general, we like to avoid using this because it makes the formatter /// less prescriptive over the user's whitespace. static const splitOrTwoNewlines = Whitespace._("splitOrTwoNewlines"); /// One or two newlines should be output based on how many newlines are /// present between the next token and the previous one. /// /// In general, we like to avoid using this because it makes the formatter /// less prescriptive over the user's whitespace. static const oneOrTwoNewlines = Whitespace._("oneOrTwoNewlines"); final String name; /// Gets the minimum number of newlines contained in this whitespace. int get minimumLines { switch (this) { case Whitespace.newline: case Whitespace.nestedNewline: case Whitespace.newlineFlushLeft: case Whitespace.oneOrTwoNewlines: return 1; case Whitespace.twoNewlines: return 2; default: return 0; } } const Whitespace._(this.name); String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/chunk.dart
// 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 dart_style.src.chunk; import 'fast_hash.dart'; import 'nesting_level.dart'; import 'rule/rule.dart'; /// Tracks where a selection start or end point may appear in some piece of /// text. abstract class Selection { /// The chunk of text. String get text; /// The offset from the beginning of [text] where the selection starts, or /// `null` if the selection does not start within this chunk. int get selectionStart => _selectionStart; int _selectionStart; /// The offset from the beginning of [text] where the selection ends, or /// `null` if the selection does not start within this chunk. int get selectionEnd => _selectionEnd; int _selectionEnd; /// Sets [selectionStart] to be [start] characters into [text]. void startSelection(int start) { _selectionStart = start; } /// Sets [selectionStart] to be [fromEnd] characters from the end of [text]. void startSelectionFromEnd(int fromEnd) { _selectionStart = text.length - fromEnd; } /// Sets [selectionEnd] to be [end] characters into [text]. void endSelection(int end) { _selectionEnd = end; } /// Sets [selectionEnd] to be [fromEnd] characters from the end of [text]. void endSelectionFromEnd(int fromEnd) { _selectionEnd = text.length - fromEnd; } } /// A chunk of non-breaking output text terminated by a hard or soft newline. /// /// Chunks are created by [LineWriter] and fed into [LineSplitter]. Each /// contains some text, along with the data needed to tell how the next line /// should be formatted and how desireable it is to split after the chunk. /// /// Line splitting after chunks comes in a few different forms. /// /// * A "hard" split is a mandatory newline. The formatted output will contain /// at least one newline after the chunk's text. /// * A "soft" split is a discretionary newline. If a line doesn't fit within /// the page width, one or more soft splits may be turned into newlines to /// wrap the line to fit within the bounds. If a soft split is not turned /// into a newline, it may instead appear as a space or zero-length string /// in the output, depending on [spaceWhenUnsplit]. /// * A "double" split expands to two newlines. In other words, it leaves a /// blank line in the output. Hard or soft splits may be doubled. This is /// determined by [isDouble]. /// /// A split controls the leading spacing of the subsequent line, both /// block-based [indent] and expression-wrapping-based [nesting]. class Chunk extends Selection { /// The literal text output for the chunk. String get text => _text; String _text; /// The number of characters of indentation from the left edge of the block /// that contains this chunk. /// /// For top level chunks that are not inside any block, this also includes /// leading indentation. int get indent => _indent; int _indent; /// The expression nesting level following this chunk. /// /// This is used to determine how much to increase the indentation when a /// line starts after this chunk. A single statement may be indented multiple /// times if the splits occur in more deeply nested expressions, for example: /// /// // 40 columns | /// someFunctionName(argument, argument, /// argument, anotherFunction(argument, /// argument)); NestingLevel get nesting => _nesting; NestingLevel _nesting; /// If this chunk marks the beginning of a block, this contains the child /// chunks and other data about that nested block. ChunkBlock get block => _block; ChunkBlock _block; /// Whether this chunk has a [block]. bool get isBlock => _block != null; /// Whether it's valid to add more text to this chunk or not. /// /// Chunks are built up by adding text and then "capped off" by having their /// split information set by calling [handleSplit]. Once the latter has been /// called, no more text should be added to the chunk since it would appear /// *before* the split. bool get canAddText => _rule == null; /// The [Rule] that controls when a split should occur after this chunk. /// /// Multiple splits may share a [Rule]. Rule get rule => _rule; Rule _rule; /// Whether or not an extra blank line should be output after this chunk if /// it's split. /// /// Internally, this can be either `true`, `false`, or `null`. The latter is /// an indeterminate state that lets later modifications to the split decide /// whether it should be double or not. /// /// However, this getter does not expose that. It will return `false` if the /// chunk is still indeterminate. bool get isDouble => _isDouble != null ? _isDouble : false; bool _isDouble; /// If `true`, then the line after this chunk should always be at column /// zero regardless of any indentation or expression nesting. /// /// Used for multi-line strings and commented out code. bool get flushLeft => _flushLeft; bool _flushLeft = false; /// If `true`, then the line after this chunk and its contained block should /// be flush left. bool get flushLeftAfter { if (!isBlock) return _flushLeft; return _block.chunks.last.flushLeftAfter; } /// Whether this chunk should append an extra space if it does not split. /// /// This is `true`, for example, in a chunk that ends with a ",". bool get spaceWhenUnsplit => _spaceWhenUnsplit; bool _spaceWhenUnsplit = false; /// Whether this chunk marks the end of a range of chunks that can be line /// split independently of the following chunks. bool get canDivide { // Have to call markDivide() before accessing this. assert(_canDivide != null); return _canDivide; } bool _canDivide; /// The number of characters in this chunk when unsplit. int get length => _text.length + (spaceWhenUnsplit ? 1 : 0); /// The unsplit length of all of this chunk's block contents. /// /// Does not include this chunk's own length, just the length of its child /// block chunks (recursively). int get unsplitBlockLength { if (_block == null) return 0; var length = 0; for (var chunk in _block.chunks) { length += chunk.length + chunk.unsplitBlockLength; } return length; } /// The [Span]s that contain this chunk. final spans = <Span>[]; /// Creates a new chunk starting with [_text]. Chunk(this._text); /// Discard the split for the chunk and put it back into the state where more /// text can be appended. void allowText() { _rule = null; } /// Append [text] to the end of the split's text. void appendText(String text) { assert(canAddText); _text += text; } /// Finishes off this chunk with the given [rule] and split information. /// /// This may be called multiple times on the same split since the splits /// produced by walking the source and the splits coming from comments and /// preserved whitespace often overlap. When that happens, this has logic to /// combine that information into a single split. void applySplit(Rule rule, int indent, NestingLevel nesting, {bool flushLeft, bool isDouble, bool space}) { if (flushLeft == null) flushLeft = false; if (space == null) space = false; if (rule.isHardened) { // A hard split always wins. _rule = rule; } else if (_rule == null) { // If the chunk hasn't been initialized yet, just inherit the rule. _rule = rule; } // Last split settings win. _flushLeft = flushLeft; _nesting = nesting; _indent = indent; _spaceWhenUnsplit = space; // Pin down the double state, if given and we haven't already. if (_isDouble == null) _isDouble = isDouble; } /// Turns this chunk into one that can contain a block of child chunks. void makeBlock(Chunk blockArgument) { assert(_block == null); _block = ChunkBlock(blockArgument); } /// Returns `true` if the block body owned by this chunk should be expression /// indented given a set of rule values provided by [getValue]. bool indentBlock(int getValue(Rule rule)) { if (_block == null) return false; if (_block.argument == null) return false; return _block.argument.rule .isSplit(getValue(_block.argument.rule), _block.argument); } // Mark whether this chunk can divide the range of chunks. void markDivide(canDivide) { // Should only do this once. assert(_canDivide == null); _canDivide = canDivide; } String toString() { var parts = []; if (text.isNotEmpty) parts.add(text); if (_indent != null) parts.add("indent:$_indent"); if (spaceWhenUnsplit == true) parts.add("space"); if (_isDouble == true) parts.add("double"); if (_flushLeft == true) parts.add("flush"); if (_rule == null) { parts.add("(no split)"); } else { parts.add(rule.toString()); if (rule.isHardened) parts.add("(hard)"); if (_rule.constrainedRules.isNotEmpty) { parts.add("-> ${_rule.constrainedRules.join(' ')}"); } } return parts.join(" "); } } /// The child chunks owned by a chunk that begins a "block" -- an actual block /// statement, function expression, or collection literal. class ChunkBlock { /// If this block is for a collection literal in an argument list, this will /// be the chunk preceding this literal argument. /// /// That chunk is owned by the argument list and if it splits, this collection /// may need extra expression-level indentation. final Chunk argument; /// The child chunks in this block. final List<Chunk> chunks = []; ChunkBlock(this.argument); } /// Constants for the cost heuristics used to determine which set of splits is /// most desirable. class Cost { /// The cost of splitting after the `=>` in a lambda or arrow-bodied member. /// /// We make this zero because there is already a span around the entire body /// and we generally do prefer splitting after the `=>` over other places. static const arrow = 0; /// The default cost. /// /// This isn't zero because we want to ensure all splitting has *some* cost, /// otherwise, the formatter won't try to keep things on one line at all. /// Most splits and spans use this. Greater costs tend to come from a greater /// number of nested spans. static const normal = 1; /// Splitting after a "=". static const assign = 1; /// Splitting after a "=" when the right-hand side is a collection or cascade. static const assignBlock = 2; /// Splitting before the first argument when it happens to be a function /// expression with a block body. static const firstBlockArgument = 2; /// The series of positional arguments. static const positionalArguments = 2; /// Splitting inside the brackets of a list with only one element. static const singleElementList = 2; /// Splitting the internals of block arguments. /// /// Used to prefer splitting at the argument boundary over splitting the block /// contents. static const splitBlocks = 2; /// Splitting on the "." in a named constructor. static const constructorName = 4; /// Splitting a `[...]` index operator. static const index = 4; /// Splitting before a type argument or type parameter. static const typeArgument = 4; /// Split between a formal parameter name and its type. static const parameterType = 4; } /// The in-progress state for a [Span] that has been started but has not yet /// been completed. class OpenSpan { /// Index of the first chunk contained in this span. int get start => _start; int _start; /// The cost applied when the span is split across multiple lines or `null` /// if the span is for a multisplit. final int cost; OpenSpan(this._start, this.cost); String toString() => "OpenSpan($start, \$$cost)"; } /// Delimits a range of chunks that must end up on the same line to avoid an /// additional cost. /// /// These are used to encourage the line splitter to try to keep things /// together, like parameter lists and binary operator expressions. /// /// This is a wrapper around the cost so that spans have unique identities. /// This way we can correctly avoid paying the cost multiple times if the same /// span is split by multiple chunks. class Span extends FastHash { /// The cost applied when the span is split across multiple lines or `null` /// if the span is for a multisplit. final int cost; Span(this.cost); String toString() => "$id\$$cost"; } /// A comment in the source, with a bit of information about the surrounding /// whitespace. class SourceComment extends Selection { /// The text of the comment, including `//`, `/*`, and `*/`. final String text; /// The number of newlines between the comment or token preceding this comment /// and the beginning of this one. /// /// Will be zero if the comment is a trailing one. int linesBefore; /// Whether this comment is a line comment. final bool isLineComment; /// Whether this comment starts at column one in the source. /// /// Comments that start at the start of the line will not be indented in the /// output. This way, commented out chunks of code do not get erroneously /// re-indented. final bool flushLeft; /// Whether this comment is an inline block comment. bool get isInline => linesBefore == 0 && !isLineComment; SourceComment(this.text, this.linesBefore, {this.isLineComment, this.flushLeft}); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/argument_list_visitor.dart
// 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 dart_style.src.argument_list_visitor; import 'dart:math' as math; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'chunk.dart'; import 'rule/argument.dart'; import 'rule/rule.dart'; import 'source_visitor.dart'; /// Helper class for [SourceVisitor] that handles visiting and writing an /// [ArgumentList], including all of the special code needed to handle /// block-formatted arguments. class ArgumentListVisitor { final SourceVisitor _visitor; /// The "(" before the argument list. final Token _leftParenthesis; /// The ")" after the argument list. final Token _rightParenthesis; /// All of the arguments, positional, named, and functions, in the argument /// list. final List<Expression> _allArguments; /// The normal arguments preceding any block function arguments. final ArgumentSublist _arguments; /// The contiguous list of block function arguments, if any. /// /// Otherwise, this is `null`. final List<Expression> _functions; /// If there are block function arguments, this is the arguments after them. /// /// Otherwise, this is `null`. final ArgumentSublist _argumentsAfterFunctions; /// Returns `true` if there is only a single positional argument. bool get _isSingle => _allArguments.length == 1 && _allArguments.single is! NamedExpression; /// Whether this argument list has any arguments that should be formatted as /// blocks. // TODO(rnystrom): Returning true based on collections is non-optimal. It // forces a method chain to break into two but the result collection may not // actually split which can lead to a method chain that's allowed to break // where it shouldn't. bool get hasBlockArguments => _arguments._blocks.isNotEmpty || _functions != null; factory ArgumentListVisitor(SourceVisitor visitor, ArgumentList node) { return ArgumentListVisitor.forArguments( visitor, node.leftParenthesis, node.rightParenthesis, node.arguments); } factory ArgumentListVisitor.forArguments( SourceVisitor visitor, Token leftParenthesis, Token rightParenthesis, List<Expression> arguments) { // Look for a single contiguous range of block function arguments. var functionsStart; var functionsEnd; for (var i = 0; i < arguments.length; i++) { var argument = arguments[i]; if (_isBlockFunction(argument)) { if (functionsStart == null) functionsStart = i; // The functions must be one contiguous section. if (functionsEnd != null && functionsEnd != i) { functionsStart = null; functionsEnd = null; break; } functionsEnd = i + 1; } } // Edge case: If all of the arguments are named, but they aren't all // functions, then don't handle the functions specially. A function with a // bunch of named arguments tends to look best when they are all lined up, // even the function ones (unless they are all functions). // // Prefers: // // function( // named: () { // something(); // }, // another: argument); // // Over: // // function(named: () { // something(); // }, // another: argument); if (functionsStart != null && arguments[0] is NamedExpression && (functionsStart > 0 || functionsEnd < arguments.length)) { functionsStart = null; } // Edge case: If all of the function arguments are named and there are // other named arguments that are "=>" functions, then don't treat the // block-bodied functions specially. In a mixture of the two function // styles, it looks cleaner to treat them all like normal expressions so // that the named arguments line up. if (functionsStart != null && arguments[functionsStart] is NamedExpression) { bool isArrow(NamedExpression named) { var expression = named.expression; if (expression is FunctionExpression) { return expression.body is ExpressionFunctionBody; } return false; } for (var i = 0; i < functionsStart; i++) { if (arguments[i] is! NamedExpression) continue; if (isArrow(arguments[i])) { functionsStart = null; break; } } for (var i = functionsEnd; i < arguments.length; i++) { if (isArrow(arguments[i])) { functionsStart = null; break; } } } if (functionsStart == null) { // No functions, so there is just a single argument list. return ArgumentListVisitor._(visitor, leftParenthesis, rightParenthesis, arguments, ArgumentSublist(arguments, arguments), null, null); } // Split the arguments into two independent argument lists with the // functions in the middle. var argumentsBefore = arguments.take(functionsStart).toList(); var functions = arguments.sublist(functionsStart, functionsEnd); var argumentsAfter = arguments.skip(functionsEnd).toList(); return ArgumentListVisitor._( visitor, leftParenthesis, rightParenthesis, arguments, ArgumentSublist(arguments, argumentsBefore), functions, ArgumentSublist(arguments, argumentsAfter)); } ArgumentListVisitor._( this._visitor, this._leftParenthesis, this._rightParenthesis, this._allArguments, this._arguments, this._functions, this._argumentsAfterFunctions); /// Builds chunks for the argument list. void visit() { // If there is just one positional argument, it tends to look weird to // split before it, so try not to. if (_isSingle) _visitor.builder.startSpan(); _visitor.builder.startSpan(); _visitor.token(_leftParenthesis); _arguments.visit(_visitor); _visitor.builder.endSpan(); if (_functions != null) { // TODO(rnystrom): It might look better to treat the parameter list of the // first function as if it were an argument in the preceding argument list // instead of just having this little solo split here. That would try to // keep the parameter list with other arguments when possible, and, I // think, generally look nicer. if (_functions.first == _allArguments.first) { _visitor.soloZeroSplit(); } else { _visitor.soloSplit(); } for (var argument in _functions) { if (argument != _functions.first) _visitor.space(); _visitor.visit(argument); // Write the following comma. if (_visitor.hasCommaAfter(argument)) { _visitor.token(argument.endToken.next); } } _visitor.builder.startSpan(); _argumentsAfterFunctions.visit(_visitor); _visitor.builder.endSpan(); } _visitor.token(_rightParenthesis); if (_isSingle) _visitor.builder.endSpan(); } /// Returns `true` if [expression] is a [FunctionExpression] with a non-empty /// block body. static bool _isBlockFunction(Expression expression) { if (expression is NamedExpression) { expression = (expression as NamedExpression).expression; } // Allow functions wrapped in dotted method calls like "a.b.c(() { ... })". if (expression is MethodInvocation) { if (!_isValidWrappingTarget(expression.target)) return false; if (expression.argumentList.arguments.length != 1) return false; return _isBlockFunction(expression.argumentList.arguments.single); } if (expression is InstanceCreationExpression) { if (expression.argumentList.arguments.length != 1) return false; return _isBlockFunction(expression.argumentList.arguments.single); } // Allow immediately-invoked functions like "() { ... }()". if (expression is FunctionExpressionInvocation) { var invocation = expression as FunctionExpressionInvocation; if (invocation.argumentList.arguments.isNotEmpty) return false; expression = invocation.function; } // Unwrap parenthesized expressions. while (expression is ParenthesizedExpression) { expression = (expression as ParenthesizedExpression).expression; } // Must be a function. if (expression is! FunctionExpression) return false; // With a curly body. var function = expression as FunctionExpression; if (function.body is! BlockFunctionBody) return false; // That isn't empty. var body = function.body as BlockFunctionBody; return body.block.statements.isNotEmpty || body.block.rightBracket.precedingComments != null; } /// Returns `true` if [expression] is a valid method invocation target for /// an invocation that wraps a function literal argument. static bool _isValidWrappingTarget(Expression expression) { // Allow bare function calls. if (expression == null) return true; // Allow property accesses. while (expression is PropertyAccess) { expression = (expression as PropertyAccess).target; } if (expression is PrefixedIdentifier) return true; if (expression is SimpleIdentifier) return true; return false; } } /// A range of arguments from a complete argument list. /// /// One of these typically covers all of the arguments in an invocation. But, /// when an argument list has block functions in the middle, the arguments /// before and after the functions are treated as separate independent lists. /// In that case, there will be two of these. class ArgumentSublist { /// The full argument list from the AST. final List<Expression> _allArguments; /// The positional arguments, in order. final List<Expression> _positional; /// The named arguments, in order. final List<Expression> _named; /// Maps each block argument, excluding functions, to the first token for that /// argument. final Map<Expression, Token> _blocks; /// The number of leading block arguments, excluding functions. /// /// If all arguments are blocks, this counts them. final int _leadingBlocks; /// The number of trailing blocks arguments. /// /// If all arguments are blocks, this is zero. final int _trailingBlocks; /// The rule used to split the bodies of all block arguments. Rule get blockRule => _blockRule; Rule _blockRule; /// The most recent chunk that split before an argument. Chunk get previousSplit => _previousSplit; Chunk _previousSplit; factory ArgumentSublist( List<Expression> allArguments, List<Expression> arguments) { // Assumes named arguments follow all positional ones. var positional = arguments.takeWhile((arg) => arg is! NamedExpression).toList(); var named = arguments.skip(positional.length).toList(); var blocks = <Expression, Token>{}; for (var argument in arguments) { var bracket = _blockToken(argument); if (bracket != null) blocks[argument] = bracket; } // Count the leading arguments that are blocks. var leadingBlocks = 0; for (var argument in arguments) { if (!blocks.containsKey(argument)) break; leadingBlocks++; } // Count the trailing arguments that are blocks. var trailingBlocks = 0; if (leadingBlocks != arguments.length) { for (var argument in arguments.reversed) { if (!blocks.containsKey(argument)) break; trailingBlocks++; } } // Blocks must all be a prefix or suffix of the argument list (and not // both). if (leadingBlocks != blocks.length) leadingBlocks = 0; if (trailingBlocks != blocks.length) trailingBlocks = 0; // Ignore any blocks in the middle of the argument list. if (leadingBlocks == 0 && trailingBlocks == 0) { blocks.clear(); } return ArgumentSublist._( allArguments, positional, named, blocks, leadingBlocks, trailingBlocks); } ArgumentSublist._(this._allArguments, this._positional, this._named, this._blocks, this._leadingBlocks, this._trailingBlocks); void visit(SourceVisitor visitor) { if (_blocks.isNotEmpty) { _blockRule = Rule(Cost.splitBlocks); } var rule = _visitPositional(visitor); _visitNamed(visitor, rule); } /// Writes the positional arguments, if any. PositionalRule _visitPositional(SourceVisitor visitor) { if (_positional.isEmpty) return null; // Allow splitting after "(". // Only count the blocks in the positional rule. var leadingBlocks = math.min(_leadingBlocks, _positional.length); var trailingBlocks = math.max(_trailingBlocks - _named.length, 0); var rule = PositionalRule(_blockRule, leadingBlocks, trailingBlocks); _visitArguments(visitor, _positional, rule); return rule; } /// Writes the named arguments, if any. void _visitNamed(SourceVisitor visitor, PositionalRule positionalRule) { if (_named.isEmpty) return; // Only count the blocks in the named rule. var leadingBlocks = math.max(_leadingBlocks - _positional.length, 0); var trailingBlocks = math.min(_trailingBlocks, _named.length); var namedRule = NamedRule(_blockRule, leadingBlocks, trailingBlocks); // Let the positional args force the named ones to split. if (positionalRule != null) { positionalRule.setNamedArgsRule(namedRule); } _visitArguments(visitor, _named, namedRule); } void _visitArguments( SourceVisitor visitor, List<Expression> arguments, ArgumentRule rule) { visitor.builder.startRule(rule); // Split before the first argument. _previousSplit = visitor.builder.split(space: arguments.first != _allArguments.first); rule.beforeArgument(_previousSplit); // Try to not split the positional arguments. if (arguments == _positional) { visitor.builder.startSpan(Cost.positionalArguments); } for (var argument in arguments) { _visitArgument(visitor, rule, argument); // Write the split. if (argument != arguments.last) { _previousSplit = visitor.split(); rule.beforeArgument(_previousSplit); } } if (arguments == _positional) visitor.builder.endSpan(); visitor.builder.endRule(); } void _visitArgument( SourceVisitor visitor, ArgumentRule rule, Expression argument) { // If we're about to write a block argument, handle it specially. if (_blocks.containsKey(argument)) { rule.disableSplitOnInnerRules(); // Tell it to use the rule we've already created. visitor.beforeBlock(_blocks[argument], blockRule, previousSplit); } else if (_allArguments.length > 1) { // Edge case: Only bump the nesting if there are multiple arguments. This // lets us avoid spurious indentation in cases like: // // function(function(() { // body; // })); visitor.builder.startBlockArgumentNesting(); } else if (argument is! NamedExpression) { // Edge case: Likewise, don't force the argument to split if there is // only a single positional one, like: // // outer(inner( // longArgument)); rule.disableSplitOnInnerRules(); } if (argument is NamedExpression) { visitor.visitNamedArgument(argument, rule as NamedRule); } else { visitor.visit(argument); } if (_blocks.containsKey(argument)) { rule.enableSplitOnInnerRules(); } else if (_allArguments.length > 1) { visitor.builder.endBlockArgumentNesting(); } else if (argument is! NamedExpression) { rule.enableSplitOnInnerRules(); } // Write the following comma. if (visitor.hasCommaAfter(argument)) { visitor.token(argument.endToken.next); } } /// If [expression] can be formatted as a block, returns the token that opens /// the block, such as a collection's bracket. /// /// Block-formatted arguments can get special indentation to make them look /// more statement-like. static Token _blockToken(Expression expression) { if (expression is NamedExpression) { expression = (expression as NamedExpression).expression; } // TODO(rnystrom): Should we step into parenthesized expressions? if (expression is ListLiteral) return expression.leftBracket; if (expression is SetOrMapLiteral) return expression.leftBracket; if (expression is SingleStringLiteral && expression.isMultiline) { return expression.beginToken; } // Not a collection literal. return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/line_writer.dart
// 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 dart_style.src.line_writer; import 'chunk.dart'; import 'dart_formatter.dart'; import 'debug.dart' as debug; import 'line_splitting/line_splitter.dart'; import 'whitespace.dart'; /// Given a series of chunks, splits them into lines and writes the result to /// a buffer. class LineWriter { final _buffer = StringBuffer(); final List<Chunk> _chunks; final String _lineEnding; /// The number of characters allowed in a single line. final int pageWidth; /// The number of characters of additional indentation to apply to each line. /// /// This is used when formatting blocks to get the output into the right /// column based on where the block appears. final int _blockIndentation; /// The cache of blocks that have already been formatted. final Map<_BlockKey, FormatResult> _blockCache; /// The offset in [_buffer] where the selection starts in the formatted code. /// /// This will be `null` if there is no selection or the writer hasn't reached /// the beginning of the selection yet. int _selectionStart; /// The offset in [_buffer] where the selection ends in the formatted code. /// /// This will be `null` if there is no selection or the writer hasn't reached /// the end of the selection yet. int _selectionEnd; /// The number of characters that have been written to the output. int get length => _buffer.length; LineWriter(DartFormatter formatter, this._chunks) : _lineEnding = formatter.lineEnding, pageWidth = formatter.pageWidth, _blockIndentation = 0, _blockCache = {}; /// Creates a line writer for a block. LineWriter._(this._chunks, this._lineEnding, this.pageWidth, this._blockIndentation, this._blockCache) { // There is always a newline after the opening delimiter. _buffer.write(_lineEnding); } /// Gets the results of formatting the child block of [chunk] at with /// starting [column]. /// /// If that block has already been formatted, reuses the results. /// /// The column is the column for the delimiters. The contents of the block /// are always implicitly one level deeper than that. /// /// main() { /// function(() { /// block; /// }); /// } /// /// When we format the anonymous lambda, [column] will be 2, not 4. FormatResult formatBlock(Chunk chunk, int column) { var key = _BlockKey(chunk, column); // Use the cached one if we have it. var cached = _blockCache[key]; if (cached != null) return cached; var writer = LineWriter._( chunk.block.chunks, _lineEnding, pageWidth, column, _blockCache); // TODO(rnystrom): Passing in an initial indent here is hacky. The // LineWriter ensures all but the first chunk have a block indent, and this // handles the first chunk. Do something cleaner. var result = writer.writeLines(Indent.block, flushLeft: chunk.flushLeft); return _blockCache[key] = result; } /// Takes all of the chunks and divides them into sublists and line splits /// each list. /// /// Since this is linear and line splitting is worse it's good to feed the /// line splitter smaller lists of chunks when possible. FormatResult writeLines(int firstLineIndent, {bool isCompilationUnit = false, bool flushLeft = false}) { // Now that we know what hard splits there will be, break the chunks into // independently splittable lines. var newlines = 0; var indent = firstLineIndent; var totalCost = 0; var start = 0; for (var i = 0; i < _chunks.length; i++) { var chunk = _chunks[i]; if (!chunk.canDivide) continue; totalCost += _completeLine(newlines, indent, start, i + 1, flushLeft: flushLeft); // Get ready for the next line. newlines = chunk.isDouble ? 2 : 1; indent = chunk.indent; flushLeft = chunk.flushLeft; start = i + 1; } if (start < _chunks.length) { totalCost += _completeLine(newlines, indent, start, _chunks.length, flushLeft: flushLeft); } // Be a good citizen, end with a newline. if (isCompilationUnit) _buffer.write(_lineEnding); return FormatResult( _buffer.toString(), totalCost, _selectionStart, _selectionEnd); } /// Takes the chunks from [start] to [end] with leading [indent], removes /// them, and runs the [LineSplitter] on them. int _completeLine(int newlines, int indent, int start, int end, {bool flushLeft}) { // Write the newlines required by the previous line. for (var j = 0; j < newlines; j++) { _buffer.write(_lineEnding); } var chunks = _chunks.sublist(start, end); if (debug.traceLineWriter) { debug.log(debug.green("\nWriting:")); debug.dumpChunks(0, chunks); debug.log(); } // Run the line splitter. var splitter = LineSplitter(this, chunks, _blockIndentation, indent, flushLeft: flushLeft); var splits = splitter.apply(); // Write the indentation of the first line. if (!flushLeft) { _buffer.write(" " * (indent + _blockIndentation)); } // Write each chunk with the appropriate splits between them. for (var i = 0; i < chunks.length; i++) { var chunk = chunks[i]; _writeChunk(chunk); if (chunk.isBlock) { if (!splits.shouldSplitAt(i)) { // This block didn't split (which implies none of the child blocks // of that block split either, recursively), so write them all inline. _writeChunksUnsplit(chunk); } else { // Include the formatted block contents. var block = formatBlock(chunk, splits.getColumn(i)); // If this block contains one of the selection markers, tell the // writer where it ended up in the final output. if (block.selectionStart != null) { _selectionStart = length + block.selectionStart; } if (block.selectionEnd != null) { _selectionEnd = length + block.selectionEnd; } _buffer.write(block.text); } } if (i == chunks.length - 1) { // Don't write trailing whitespace after the last chunk. } else if (splits.shouldSplitAt(i)) { _buffer.write(_lineEnding); if (chunk.isDouble) _buffer.write(_lineEnding); _buffer.write(" " * (splits.getColumn(i))); } else { if (chunk.spaceWhenUnsplit) _buffer.write(" "); } } return splits.cost; } /// Writes the block chunks of [chunk] (and any child chunks of them, /// recursively) without any splitting. void _writeChunksUnsplit(Chunk chunk) { if (!chunk.isBlock) return; for (var blockChunk in chunk.block.chunks) { _writeChunk(blockChunk); if (blockChunk.spaceWhenUnsplit) _buffer.write(" "); // Recurse into the block. _writeChunksUnsplit(blockChunk); } } /// Writes [chunk] to the output and updates the selection if the chunk /// contains a selection marker. void _writeChunk(Chunk chunk) { if (chunk.selectionStart != null) { _selectionStart = length + chunk.selectionStart; } if (chunk.selectionEnd != null) { _selectionEnd = length + chunk.selectionEnd; } _buffer.write(chunk.text); } } /// Key type for the formatted block cache. /// /// To cache formatted blocks, we just need to know which block it is (the /// index of its parent chunk) and how far it was indented when we formatted it /// (the starting column). class _BlockKey { /// The index of the chunk in the surrounding chunk list that contains this /// block. final Chunk chunk; /// The absolute zero-based column number where the block starts. final int column; _BlockKey(this.chunk, this.column); bool operator ==(other) { if (other is! _BlockKey) return false; return chunk == other.chunk && column == other.column; } int get hashCode => chunk.hashCode ^ column.hashCode; } /// The result of formatting a series of chunks. class FormatResult { /// The resulting formatted text, including newlines and leading whitespace /// to reach the proper column. final String text; /// The numeric cost of the chosen solution. final int cost; /// Where in the resulting buffer the selection starting point should appear /// if it was contained within this split list of chunks. /// /// Otherwise, this is `null`. final int selectionStart; /// Where in the resulting buffer the selection end point should appear if it /// was contained within this split list of chunks. /// /// Otherwise, this is `null`. final int selectionEnd; FormatResult(this.text, this.cost, this.selectionStart, this.selectionEnd); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/nesting_level.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.nesting_level; import 'fast_hash.dart'; /// A single level of expression nesting. /// /// When a line is split in the middle of an expression, this tracks the /// context of where in the expression that split occurs. It ensures that the /// [LineSplitter] obeys the expression nesting when deciding what column to /// start lines at when split inside an expression. /// /// Each instance of this represents a single level of expression nesting. If we /// split at to chunks with different levels of nesting, the splitter ensures /// they each get assigned to different columns. /// /// In addition, each level has an indent. This is the number of spaces it is /// indented relative to the outer expression. It's almost always /// [Indent.expression], but cascades are special magic snowflakes and use /// [Indent.cascade]. class NestingLevel extends FastHash { /// The nesting level surrounding this one, or `null` if this is represents /// top level code in a block. NestingLevel get parent => _parent; NestingLevel _parent; /// The number of characters that this nesting level is indented relative to /// the containing level. /// /// Normally, this is [Indent.expression], but cascades use [Indent.cascade]. final int indent; /// The total number of characters of indentation from this level and all of /// its parents, after determining which nesting levels are actually used. /// /// This is only valid during line splitting. int get totalUsedIndent => _totalUsedIndent; int _totalUsedIndent; bool get isNested => _parent != null; NestingLevel() : indent = 0; NestingLevel._(this._parent, this.indent); /// Creates a new deeper level of nesting indented [spaces] more characters /// that the outer level. NestingLevel nest(int spaces) => NestingLevel._(this, spaces); /// Clears the previously calculated total indent of this nesting level. void clearTotalUsedIndent() { _totalUsedIndent = null; if (_parent != null) _parent.clearTotalUsedIndent(); } /// Calculates the total amount of indentation from this nesting level and /// all of its parents assuming only [usedNesting] levels are in use. void refreshTotalUsedIndent(Set<NestingLevel> usedNesting) { if (_totalUsedIndent != null) return; _totalUsedIndent = 0; if (_parent != null) { _parent.refreshTotalUsedIndent(usedNesting); _totalUsedIndent += _parent.totalUsedIndent; } if (usedNesting.contains(this)) _totalUsedIndent += indent; } String toString() { if (_parent == null) return indent.toString(); return "$parent:$indent"; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/fast_hash.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.fast_hash; /// A mixin for classes with identity equality that need to be frequently /// hashed. abstract class FastHash { static int _nextId = 0; /// A semi-unique numeric indentifier for the object. /// /// This is useful for debugging and also speeds up using the object in hash /// sets. Ids are *semi*-unique because they may wrap around in long running /// processes. Since objects are equal based on their identity, this is /// innocuous and prevents ids from growing without bound. final int id = _nextId = (_nextId + 1) & 0x0fffffff; int get hashCode => id; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/formatter_options.dart
// 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 dart_style.src.formatter_options; import 'dart:convert'; import 'dart:io'; import 'source_code.dart'; import 'style_fix.dart'; /// Global options that affect how the formatter produces and uses its outputs. class FormatterOptions { /// The [OutputReporter] used to show the formatting results. final OutputReporter reporter; /// The number of spaces of indentation to prefix the output with. final int indent; /// The number of columns that formatted output should be constrained to fit /// within. final int pageWidth; /// Whether symlinks should be traversed when formatting a directory. final bool followLinks; /// The style fixes to apply while formatting. final Iterable<StyleFix> fixes; FormatterOptions(this.reporter, {this.indent = 0, this.pageWidth = 80, this.followLinks = false, this.fixes}); } /// How the formatter reports the results it produces. abstract class OutputReporter { /// Prints only the names of files whose contents are different from their /// formatted version. static final OutputReporter dryRun = _DryRunReporter(); /// Prints the formatted results of each file to stdout. static final OutputReporter print = _PrintReporter(); /// Prints the formatted result and selection info of each file to stdout as /// a JSON map. static final OutputReporter printJson = _PrintJsonReporter(); /// Overwrites each file with its formatted result. static final OutputReporter overwrite = _OverwriteReporter(); /// Describe the directory whose contents are about to be processed. void showDirectory(String path) {} /// Describe the symlink at [path] that wasn't followed. void showSkippedLink(String path) {} /// Describe the hidden [path] that wasn't processed. void showHiddenPath(String path) {} /// Called when [file] is about to be formatted. void beforeFile(File file, String label) {} /// Describe the processed file at [path] whose formatted result is [output]. /// /// If the contents of the file are the same as the formatted output, /// [changed] will be false. void afterFile(File file, String label, SourceCode output, {bool changed}); } /// Prints only the names of files whose contents are different from their /// formatted version. class _DryRunReporter extends OutputReporter { void afterFile(File file, String label, SourceCode output, {bool changed}) { // Only show the changed files. if (changed) print(label); } } /// Prints the formatted results of each file to stdout. class _PrintReporter extends OutputReporter { void showDirectory(String path) { print("Formatting directory $path:"); } void showSkippedLink(String path) { print("Skipping link $path"); } void showHiddenPath(String path) { print("Skipping hidden path $path"); } void afterFile(File file, String label, SourceCode output, {bool changed}) { // Don't add an extra newline. stdout.write(output.text); } } /// Prints the formatted result and selection info of each file to stdout as a /// JSON map. class _PrintJsonReporter extends OutputReporter { void afterFile(File file, String label, SourceCode output, {bool changed}) { // TODO(rnystrom): Put an empty selection in here to remain compatible with // the old formatter. Since there's no way to pass a selection on the // command line, this will never be used, which is why it's hard-coded to // -1, -1. If we add support for passing in a selection, put the real // result here. print(jsonEncode({ "path": label, "source": output.text, "selection": { "offset": output.selectionStart != null ? output.selectionStart : -1, "length": output.selectionLength != null ? output.selectionLength : -1 } })); } } /// Overwrites each file with its formatted result. class _OverwriteReporter extends _PrintReporter { void afterFile(File file, String label, SourceCode output, {bool changed}) { if (changed) { try { file.writeAsStringSync(output.text); print("Formatted $label"); } on FileSystemException catch (err) { stderr.writeln("Could not overwrite $label: " "${err.osError.message} (error code ${err.osError.errorCode})"); } } else { print("Unchanged $label"); } } } /// Base clase for a reporter that decorates an inner reporter. abstract class _ReporterDecorator implements OutputReporter { final OutputReporter _inner; _ReporterDecorator(this._inner); void showDirectory(String path) { _inner.showDirectory(path); } void showSkippedLink(String path) { _inner.showSkippedLink(path); } void showHiddenPath(String path) { _inner.showHiddenPath(path); } void beforeFile(File file, String label) { _inner.beforeFile(file, label); } void afterFile(File file, String label, SourceCode output, {bool changed}) { _inner.afterFile(file, label, output, changed: changed); } } /// A decorating reporter that reports how long it took for format each file. class ProfileReporter extends _ReporterDecorator { /// The files that have been started but have not completed yet. /// /// Maps a file label to the time that it started being formatted. final Map<String, DateTime> _ongoing = {}; /// The elapsed time it took to format each completed file. final Map<String, Duration> _elapsed = {}; /// The number of files that completed so fast that they aren't worth /// tracking. int _elided = 0; ProfileReporter(OutputReporter inner) : super(inner); /// Show the times for the slowest files to format. void showProfile() { // Everything should be done. assert(_ongoing.isEmpty); var files = _elapsed.keys.toList(); files.sort((a, b) => _elapsed[b].compareTo(_elapsed[a])); for (var file in files) { print("${_elapsed[file]}: $file"); } if (_elided >= 1) { var s = _elided > 1 ? 's' : ''; print("...$_elided more file$s each took less than 10ms."); } } /// Called when [file] is about to be formatted. void beforeFile(File file, String label) { super.beforeFile(file, label); _ongoing[label] = DateTime.now(); } /// Describe the processed file at [path] whose formatted result is [output]. /// /// If the contents of the file are the same as the formatted output, /// [changed] will be false. void afterFile(File file, String label, SourceCode output, {bool changed}) { var elapsed = DateTime.now().difference(_ongoing.remove(label)); if (elapsed.inMilliseconds >= 10) { _elapsed[label] = elapsed; } else { _elided++; } super.afterFile(file, label, output, changed: changed); } } /// A decorating reporter that sets the exit code to 1 if any changes are made. class SetExitReporter extends _ReporterDecorator { SetExitReporter(OutputReporter inner) : super(inner); /// Describe the processed file at [path] whose formatted result is [output]. /// /// If the contents of the file are the same as the formatted output, /// [changed] will be false. void afterFile(File file, String label, SourceCode output, {bool changed}) { if (changed) exitCode = 1; super.afterFile(file, label, output, changed: changed); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/string_compare.dart
library dart_style.src.string_compare; /// Returns `true` if [c] represents a whitespace code unit allowed in Dart /// source code. bool _isWhitespace(int c) => (c <= 0x000D && c >= 0x0009) || c == 0x0020; /// Returns the index of the next non-whitespace character. /// /// Returns `true` if current contains a non-whitespace character. /// Returns `false` if no characters are left. int _moveNextNonWhitespace(String str, int len, int i) { while (i < len && _isWhitespace(str.codeUnitAt(i))) { i++; } return i; } /// Returns `true` if the strings are equal ignoring whitespace characters. bool equalIgnoringWhitespace(String str1, String str2) { // Benchmarks showed about a 20% regression in formatter performance when // when we use the simpler to implement solution of stripping all // whitespace characters and checking string equality. This solution is // faster due to lower memory usage and poor performance concatting strings // together one rune at a time. var len1 = str1.length; var len2 = str2.length; var i1 = 0; var i2 = 0; while (true) { i1 = _moveNextNonWhitespace(str1, len1, i1); i2 = _moveNextNonWhitespace(str2, len2, i2); if (i1 >= len1 || i2 >= len2) { return (i1 >= len1) == (i2 >= len2); } if (str1[i1] != str2[i2]) return false; i1++; i2++; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/chunk_builder.dart
// 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 dart_style.src.chunk_builder; import 'chunk.dart'; import 'dart_formatter.dart'; import 'debug.dart' as debug; import 'line_writer.dart'; import 'nesting_builder.dart'; import 'nesting_level.dart'; import 'rule/rule.dart'; import 'source_code.dart'; import 'style_fix.dart'; import 'whitespace.dart'; /// Matches if the last character of a string is an identifier character. final _trailingIdentifierChar = RegExp(r"[a-zA-Z0-9_]$"); /// Matches a JavaDoc-style doc comment that starts with "/**" and ends with /// "*/" or "**/". final _javaDocComment = RegExp(r"^/\*\*([^*/][\s\S]*?)\*?\*/$"); /// Matches the leading "*" in a line in the middle of a JavaDoc-style comment. var _javaDocLine = RegExp(r"^\s*\*(.*)"); /// Takes the incremental serialized output of [SourceVisitor]--the source text /// along with any comments and preserved whitespace--and produces a coherent /// tree of [Chunk]s which can then be split into physical lines. /// /// Keeps track of leading indentation, expression nesting, and all of the hairy /// code required to seamlessly integrate existing comments into the pure /// output produced by [SourceVisitor]. class ChunkBuilder { final DartFormatter _formatter; /// The builder for the code surrounding the block that this writer is for, or /// `null` if this is writing the top-level code. final ChunkBuilder _parent; final SourceCode _source; final List<Chunk> _chunks; /// The whitespace that should be written to [_chunks] before the next /// non-whitespace token. /// /// This ensures that changes to indentation and nesting also apply to the /// most recent split, even if the visitor "creates" the split before changing /// indentation or nesting. Whitespace _pendingWhitespace = Whitespace.none; /// The nested stack of rules that are currently in use. /// /// New chunks are implicitly split by the innermost rule when the chunk is /// ended. final _rules = <Rule>[]; /// The set of rules known to contain hard splits that will in turn force /// these rules to harden. /// /// This is accumulated lazily while chunks are being built. Then, once they /// are all done, the rules are all hardened. We do this later because some /// rules may not have all of their constraints fully wired up until after /// the hard split appears. For example, a hard split in a positional /// argument list needs to force the named arguments to split too, but we /// don't create that rule until after the positional arguments are done. final _hardSplitRules = Set<Rule>(); /// The list of rules that are waiting until the next whitespace has been /// written before they start. final _lazyRules = <Rule>[]; /// The nested stack of spans that are currently being written. final _openSpans = <OpenSpan>[]; /// The current state. final _nesting = NestingBuilder(); /// The stack of nesting levels where block arguments may start. /// /// A block argument's contents will nest at the last level in this stack. final _blockArgumentNesting = <NestingLevel>[]; /// The index of the "current" chunk being written. /// /// If the last chunk is still being appended to, this is its index. /// Otherwise, it is the index of the next chunk which will be created. int get _currentChunkIndex { if (_chunks.isEmpty) return 0; if (_chunks.last.canAddText) return _chunks.length - 1; return _chunks.length; } /// Whether or not there was a leading comment that was flush left before any /// other content was written. /// /// This is used when writing child blocks to make the parent chunk have the /// right flush left value when a comment appears immediately inside the /// block. bool _firstFlushLeft = false; /// The number of calls to [preventSplit()] that have not been ended by a /// call to [endPreventSplit()]. /// /// Splitting is completely disabled inside string interpolation. We do want /// to fix the whitespace inside interpolation, though, so we still format /// them. This tracks whether we're inside an interpolation. We can't use a /// simple bool because interpolation can nest. /// /// When this is non-zero, splits are ignored. int _preventSplitNesting = 0; /// Whether there is pending whitespace that depends on the number of /// newlines in the source. /// /// This is used to avoid calculating the newlines between tokens unless /// actually needed since doing so is slow when done between every single /// token pair. bool get needsToPreserveNewlines => _pendingWhitespace == Whitespace.oneOrTwoNewlines || _pendingWhitespace == Whitespace.splitOrTwoNewlines || _pendingWhitespace == Whitespace.splitOrNewline; /// The number of characters of code that can fit in a single line. int get pageWidth => _formatter.pageWidth; /// The current innermost rule. Rule get rule => _rules.last; ChunkBuilder(this._formatter, this._source) : _parent = null, _chunks = [] { indent(_formatter.indent); startBlockArgumentNesting(); } ChunkBuilder._(this._parent, this._formatter, this._source, this._chunks) { startBlockArgumentNesting(); } /// Writes [string], the text for a single token, to the output. /// /// By default, this also implicitly adds one level of nesting if we aren't /// currently nested at all. We do this here so that if a comment appears /// after any token within a statement or top-level form and that comment /// leads to splitting, we correctly nest. Even pathological cases like: /// /// /// import // comment /// "this_gets_nested.dart"; /// /// If we didn't do this here, we'd have to call [nestExpression] after the /// first token of practically every grammar production. void write(String string) { _emitPendingWhitespace(); _writeText(string); _lazyRules.forEach(_activateRule); _lazyRules.clear(); _nesting.commitNesting(); } /// Writes a [WhitespaceChunk] of [type]. void writeWhitespace(Whitespace type) { _pendingWhitespace = type; } /// Write a split owned by the current innermost rule. /// /// If [flushLeft] is `true`, then forces the next line to start at column /// one regardless of any indentation or nesting. /// /// If [isDouble] is passed, forces the split to either be a single or double /// newline. Otherwise, leaves it indeterminate. /// /// If [nest] is `false`, ignores any current expression nesting. Otherwise, /// uses the current nesting level. If unsplit, it expands to a space if /// [space] is `true`. Chunk split({bool flushLeft, bool isDouble, bool nest, bool space}) { space ??= false; // If we are not allowed to split at all, don't. Returning null for the // chunk is safe since the rule that uses the chunk will itself get // discarded because no chunk references it. if (_preventSplitNesting > 0) { if (space) _pendingWhitespace = Whitespace.space; return null; } return _writeSplit(_rules.last, flushLeft: flushLeft, isDouble: isDouble, nest: nest, space: space); } /// Outputs the series of [comments] and associated whitespace that appear /// before [token] (which is not written by this). /// /// The list contains each comment as it appeared in the source between the /// last token written and the next one that's about to be written. /// /// [linesBeforeToken] is the number of lines between the last comment (or /// previous token if there are no comments) and the next token. void writeComments( List<SourceComment> comments, int linesBeforeToken, String token) { // Edge case: if we require a blank line, but there exists one between // some of the comments, or after the last one, then we don't need to // enforce one before the first comment. Example: // // library foo; // // comment // // class Bar {} // // Normally, a blank line is required after `library`, but since there is // one after the comment, we don't need one before it. This is mainly so // that commented out directives stick with their preceding group. if (_pendingWhitespace == Whitespace.twoNewlines && comments.first.linesBefore < 2) { if (linesBeforeToken > 1) { _pendingWhitespace = Whitespace.newline; } else { for (var i = 1; i < comments.length; i++) { if (comments[i].linesBefore > 1) { _pendingWhitespace = Whitespace.newline; break; } } } } // Edge case: if the previous output was also from a call to // [writeComments()] which ended with a line comment, force a newline. // Normally, comments are strictly interleaved with tokens and you never // get two sequences of comments in a row. However, when applying a fix // that removes a token (like `new`), it's possible to get two sets of // comments in a row, as in: // // // a // new // b // Foo(); // // When that happens, we need to make sure the preserve the split at the // end of the first sequence of comments if there is one. if (_pendingWhitespace == null) { comments.first.linesBefore = 1; _pendingWhitespace = Whitespace.none; } // Edge case: if the comments are completely inline (i.e. just a series of // block comments with no newlines before, after, or between them), then // they will eat any pending newlines. Make sure that doesn't happen by // putting the pending whitespace before the first comment and moving them // to their own line. Turns this: // // library foo; /* a */ /* b */ import 'a.dart'; // // into: // // library foo; // // /* a */ /* b */ // import 'a.dart'; if (linesBeforeToken == 0 && comments.every((comment) => comment.isInline) && _pendingWhitespace.minimumLines > 0) { comments.first.linesBefore = _pendingWhitespace.minimumLines; linesBeforeToken = 1; } // Write each comment and the whitespace between them. for (var i = 0; i < comments.length; i++) { var comment = comments[i]; preserveNewlines(comment.linesBefore); // Don't emit a space because we'll handle it below. If we emit it here, // we may get a trailing space if the comment needs a line before it. if (_pendingWhitespace == Whitespace.space) { _pendingWhitespace = Whitespace.none; } _emitPendingWhitespace(); if (comment.linesBefore == 0) { // If we're sitting on a split, move the comment before it to adhere it // to the preceding text. if (_shouldMoveCommentBeforeSplit(comment.text)) { _chunks.last.allowText(); } // The comment follows other text, so we need to decide if it gets a // space before it or not. if (_needsSpaceBeforeComment(comment)) _writeText(" "); } else { // The comment starts a line, so make sure it stays on its own line. _writeHardSplit( flushLeft: comment.flushLeft, isDouble: comment.linesBefore > 1, nest: true); } _writeCommentText(comment); if (comment.selectionStart != null) { startSelectionFromEnd(comment.text.length - comment.selectionStart); } if (comment.selectionEnd != null) { endSelectionFromEnd(comment.text.length - comment.selectionEnd); } // Make sure there is at least one newline after a line comment and allow // one or two after a block comment that has nothing after it. var linesAfter; if (i < comments.length - 1) { linesAfter = comments[i + 1].linesBefore; } else { linesAfter = linesBeforeToken; // Always force a newline after multi-line block comments. Prevents // mistakes like: // // /** // * Some doc comment. // */ someFunction() { ... } if (linesAfter == 0 && comments.last.text.contains("\n")) { linesAfter = 1; } } if (linesAfter > 0) _writeHardSplit(isDouble: linesAfter > 1, nest: true); } // If the comment has text following it (aside from a grouping character), // it needs a trailing space. if (_needsSpaceAfterLastComment(comments, token)) { _pendingWhitespace = Whitespace.space; } preserveNewlines(linesBeforeToken); } /// Writes the text of [comment]. /// /// If it's a JavaDoc comment that should be fixed to use `///`, fixes it. void _writeCommentText(SourceComment comment) { if (!_formatter.fixes.contains(StyleFix.docComments)) { _writeText(comment.text); return; } // See if it's a JavaDoc comment. var match = _javaDocComment.firstMatch(comment.text); if (match == null) { _writeText(comment.text); return; } // Remove a leading "*" from the middle lines. var lines = match.group(1).split("\n").toList(); for (var i = 1; i < lines.length - 1; i++) { var line = lines[i]; var match = _javaDocLine.firstMatch(line); if (match != null) { line = match.group(1); } else { // Note that this may remove deliberate leading whitespace. In tests on // a large corpus, though, I couldn't find examples of that. line = line.trimLeft(); } lines[i] = line; } // Trim the first and last lines if empty. if (lines.first.trim().isEmpty) lines.removeAt(0); if (lines.isNotEmpty && lines.last.trim().isEmpty) lines.removeLast(); // Don't completely eliminate an empty block comment. if (lines.isEmpty) lines.add(""); for (var line in lines) { if (line.isNotEmpty && !line.startsWith(" ")) line = " $line"; _writeText("///${line.trimRight()}"); _pendingWhitespace = Whitespace.newline; _emitPendingWhitespace(); } } /// If the current pending whitespace allows some source discretion, pins /// that down given that the source contains [numLines] newlines at that /// point. void preserveNewlines(int numLines) { // If we didn't know how many newlines the user authored between the last // token and this one, now we do. switch (_pendingWhitespace) { case Whitespace.splitOrNewline: if (numLines > 0) { _pendingWhitespace = Whitespace.nestedNewline; } else { _pendingWhitespace = Whitespace.none; split(space: true); } break; case Whitespace.splitOrTwoNewlines: if (numLines > 1) { _pendingWhitespace = Whitespace.twoNewlines; } else { _pendingWhitespace = Whitespace.none; split(space: true); } break; case Whitespace.oneOrTwoNewlines: if (numLines > 1) { _pendingWhitespace = Whitespace.twoNewlines; } else { _pendingWhitespace = Whitespace.newline; } break; } } /// Creates a new indentation level [spaces] deeper than the current one. /// /// If omitted, [spaces] defaults to [Indent.block]. void indent([int spaces]) { _nesting.indent(spaces); } /// Discards the most recent indentation level. void unindent() { _nesting.unindent(); } /// Starts a new span with [cost]. /// /// Each call to this needs a later matching call to [endSpan]. void startSpan([int cost = Cost.normal]) { _openSpans.add(OpenSpan(_currentChunkIndex, cost)); } /// Ends the innermost span. void endSpan() { var openSpan = _openSpans.removeLast(); // A span that just covers a single chunk can't be split anyway. var end = _currentChunkIndex; if (openSpan.start == end) return; // Add the span to every chunk that can split it. var span = Span(openSpan.cost); for (var i = openSpan.start; i < end; i++) { var chunk = _chunks[i]; if (!chunk.rule.isHardened) chunk.spans.add(span); } } /// Starts a new [Rule]. /// /// If omitted, defaults to a new [Rule]. void startRule([Rule rule]) { if (rule == null) rule = Rule(); // If there are any pending lazy rules, start them now so that the proper // stack ordering of rules is maintained. _lazyRules.forEach(_activateRule); _lazyRules.clear(); _activateRule(rule); } void _activateRule(Rule rule) { // See if any of the rules that contain this one care if it splits. _rules.forEach((outer) { if (!outer.splitsOnInnerRules) return; rule.imply(outer); }); _rules.add(rule); } /// Starts a new [Rule] that comes into play *after* the next whitespace /// (including comments) is written. /// /// This is used for operators who want to start a rule before the first /// operand but not get forced to split if a comment appears before the /// entire expression. /// /// If [rule] is omitted, defaults to a new [Rule]. void startLazyRule([Rule rule]) { if (rule == null) rule = Rule(); _lazyRules.add(rule); } /// Ends the innermost rule. void endRule() { if (_lazyRules.isNotEmpty) { _lazyRules.removeLast(); } else { _rules.removeLast(); } } /// Pre-emptively forces all of the current rules to become hard splits. /// /// This is called by [SourceVisitor] when it can determine that a rule will /// will always be split. Turning it (and the surrounding rules) into hard /// splits lets the writer break the output into smaller pieces for the line /// splitter, which helps performance and avoids failing on very large input. /// /// In particular, it's easy for the visitor to know that collections with a /// large number of items must split. Doing that early avoids crashing the /// splitter when it tries to recurse on huge collection literals. void forceRules() => _handleHardSplit(); /// Begins a new expression nesting level [indent] spaces deeper than the /// current one if it splits. /// /// If [indent] is omitted, defaults to [Indent.expression]. If [now] is /// `true`, commits the nesting change immediately instead of waiting until /// after the next chunk of text is written. void nestExpression({int indent, bool now}) { if (now == null) now = false; _nesting.nest(indent); if (now) _nesting.commitNesting(); } /// Discards the most recent level of expression nesting. /// /// Expressions that are more nested will get increased indentation when split /// if the previous line has a lower level of nesting. /// /// If [now] is `false`, does not commit the nesting change until after the /// next chunk of text is written. void unnest({bool now}) { if (now == null) now = true; _nesting.unnest(); if (now) _nesting.commitNesting(); } /// Marks the selection starting point as occurring [fromEnd] characters to /// the left of the end of what's currently been written. /// /// It counts backwards from the end because this is called *after* the chunk /// of text containing the selection has been output. void startSelectionFromEnd(int fromEnd) { assert(_chunks.isNotEmpty); _chunks.last.startSelectionFromEnd(fromEnd); } /// Marks the selection ending point as occurring [fromEnd] characters to the /// left of the end of what's currently been written. /// /// It counts backwards from the end because this is called *after* the chunk /// of text containing the selection has been output. void endSelectionFromEnd(int fromEnd) { assert(_chunks.isNotEmpty); _chunks.last.endSelectionFromEnd(fromEnd); } /// Captures the current nesting level as marking where subsequent block /// arguments should start. void startBlockArgumentNesting() { _blockArgumentNesting.add(_nesting.currentNesting); } /// Releases the last nesting level captured by [startBlockArgumentNesting]. void endBlockArgumentNesting() { _blockArgumentNesting.removeLast(); } /// Starts a new block as a child of the current chunk. /// /// Nested blocks are handled using their own independent [LineWriter]. ChunkBuilder startBlock(Chunk argumentChunk) { var chunk = _chunks.last; chunk.makeBlock(argumentChunk); var builder = ChunkBuilder._(this, _formatter, _source, chunk.block.chunks); // A block always starts off indented one level. builder.indent(); return builder; } /// Ends this [ChunkBuilder], which must have been created by [startBlock()]. /// /// Forces the chunk that owns the block to split if it can tell that the /// block contents will always split. It does that by looking for hard splits /// in the block. If [ignoredSplit] is given, that rule will be ignored /// when determining if a block contains a hard split. If [forceSplit] is /// `true`, the block is considered to always split. /// /// Returns the previous writer for the surrounding block. ChunkBuilder endBlock(Rule ignoredSplit, {bool forceSplit}) { _divideChunks(); // If we don't already know if the block is going to split, see if it // contains any hard splits or is longer than a page. if (!forceSplit) { var length = 0; for (var chunk in _chunks) { length += chunk.length + chunk.unsplitBlockLength; if (length > _formatter.pageWidth) { forceSplit = true; break; } if (chunk.rule != null && chunk.rule.isHardened && chunk.rule != ignoredSplit) { forceSplit = true; break; } } } _parent._endChildBlock( firstFlushLeft: _firstFlushLeft, forceSplit: forceSplit); return _parent; } /// Finishes off the last chunk in a child block of this parent. void _endChildBlock({bool firstFlushLeft, bool forceSplit}) { // If there is a hard newline within the block, force the surrounding rule // for it so that we apply that constraint. if (forceSplit) forceRules(); // Write the split for the block contents themselves. var chunk = _chunks.last; chunk.applySplit(rule, _nesting.indentation, _blockArgumentNesting.last, flushLeft: firstFlushLeft); if (chunk.rule.isHardened) _handleHardSplit(); } /// Finishes writing and returns a [SourceCode] containing the final output /// and updated selection, if any. SourceCode end() { _writeHardSplit(); _divideChunks(); if (debug.traceChunkBuilder) { debug.log(debug.green("\nBuilt:")); debug.dumpChunks(0, _chunks); debug.log(); } var writer = LineWriter(_formatter, _chunks); var result = writer.writeLines(_formatter.indent, isCompilationUnit: _source.isCompilationUnit); var selectionStart; var selectionLength; if (_source.selectionStart != null) { selectionStart = result.selectionStart; var selectionEnd = result.selectionEnd; // If we haven't hit the beginning and/or end of the selection yet, they // must be at the very end of the code. if (selectionStart == null) selectionStart = writer.length; if (selectionEnd == null) selectionEnd = writer.length; selectionLength = selectionEnd - selectionStart; } return SourceCode(result.text, uri: _source.uri, isCompilationUnit: _source.isCompilationUnit, selectionStart: selectionStart, selectionLength: selectionLength); } void preventSplit() { _preventSplitNesting++; } void endPreventSplit() { _preventSplitNesting--; assert(_preventSplitNesting >= 0, "Mismatched calls."); } /// Writes the current pending [Whitespace] to the output, if any. /// /// This should only be called after source lines have been preserved to turn /// any ambiguous whitespace into a concrete choice. void _emitPendingWhitespace() { // Output any pending whitespace first now that we know it won't be // trailing. switch (_pendingWhitespace) { case Whitespace.space: _writeText(" "); break; case Whitespace.newline: _writeHardSplit(); break; case Whitespace.nestedNewline: _writeHardSplit(nest: true); break; case Whitespace.newlineFlushLeft: _writeHardSplit(flushLeft: true, nest: true); break; case Whitespace.twoNewlines: _writeHardSplit(isDouble: true); break; case Whitespace.splitOrNewline: case Whitespace.splitOrTwoNewlines: case Whitespace.oneOrTwoNewlines: // We should have pinned these down before getting here. assert(false); break; } _pendingWhitespace = Whitespace.none; } /// Returns `true` if the last chunk is a split that should be moved after the /// comment that is about to be written. bool _shouldMoveCommentBeforeSplit(String comment) { // Not if there is nothing before it. if (_chunks.isEmpty) return false; // Multi-line comments are always pushed to the next line. if (comment.contains("\n")) return false; var text = _chunks.last.text; // A block comment following a comma probably refers to the following item. if (text.endsWith(",") && comment.startsWith("/*")) return false; // If the text before the split is an open grouping character, it looks // better to keep it with the elements than with the bracket itself. return !text.endsWith("(") && !text.endsWith("[") && !text.endsWith("{"); } /// Returns `true` if [comment] appears to be a magic generic method comment. /// /// Those get spaced a little differently to look more like real syntax: /// /// int f/*<S, T>*/(int x) => 3; bool _isGenericMethodComment(SourceComment comment) { return comment.text.startsWith("/*<") || comment.text.startsWith("/*="); } /// Returns `true` if a space should be output between the end of the current /// output and the subsequent comment which is about to be written. /// /// This is only called if the comment is trailing text in the unformatted /// source. In most cases, a space will be output to separate the comment /// from what precedes it. This returns false if: /// /// * This comment does begin the line in the output even if it didn't in /// the source. /// * The comment is a block comment immediately following a grouping /// character (`(`, `[`, or `{`). This is to allow `foo(/* comment */)`, /// et. al. bool _needsSpaceBeforeComment(SourceComment comment) { // Not at the start of the file. if (_chunks.isEmpty) return false; // Not at the start of a line. if (!_chunks.last.canAddText) return false; var text = _chunks.last.text; if (text.endsWith("\n")) return false; // Always put a space before line comments. if (comment.isLineComment) return true; // Magic generic method comments like "Foo/*<T>*/" don't get spaces. if (_isGenericMethodComment(comment) && _trailingIdentifierChar.hasMatch(text)) { return false; } // Block comments do not get a space if following a grouping character. return !text.endsWith("(") && !text.endsWith("[") && !text.endsWith("{"); } /// Returns `true` if a space should be output after the last comment which /// was just written and the token that will be written. bool _needsSpaceAfterLastComment(List<SourceComment> comments, String token) { // Not if there are no comments. if (comments.isEmpty) return false; // Not at the beginning of a line. if (!_chunks.last.canAddText) return false; // Magic generic method comments like "Foo/*<T>*/" don't get spaces. if (_isGenericMethodComment(comments.last) && token == "(") { return false; } // Otherwise, it gets a space if the following token is not a delimiter or // the empty string, for EOF. return token != ")" && token != "]" && token != "}" && token != "," && token != ";" && token != ""; } /// Appends a hard split with the current indentation and nesting (the latter /// only if [nest] is `true`). /// /// If [double] is `true` or `false`, forces a single or double line to be /// output. Otherwise, it is left indeterminate. /// /// If [flushLeft] is `true`, then the split will always cause the next line /// to be at column zero. Otherwise, it uses the normal indentation and /// nesting behavior. void _writeHardSplit({bool isDouble, bool flushLeft, bool nest = false}) { // A hard split overrides any other whitespace. _pendingWhitespace = null; _writeSplit(Rule.hard(), flushLeft: flushLeft, isDouble: isDouble, nest: nest); } /// Ends the current chunk (if any) with the given split information. /// /// Returns the chunk. Chunk _writeSplit(Rule rule, {bool flushLeft, bool isDouble, bool nest, bool space}) { nest ??= true; space ??= false; if (_chunks.isEmpty) { if (flushLeft != null) _firstFlushLeft = flushLeft; return null; } _chunks.last.applySplit( rule, _nesting.indentation, nest ? _nesting.nesting : NestingLevel(), flushLeft: flushLeft, isDouble: isDouble, space: space); if (_chunks.last.rule.isHardened) _handleHardSplit(); return _chunks.last; } /// Writes [text] to either the current chunk or a new one if the current /// chunk is complete. void _writeText(String text) { if (_chunks.isNotEmpty && _chunks.last.canAddText) { _chunks.last.appendText(text); } else { _chunks.add(Chunk(text)); } } /// Returns true if we can divide the chunks at [index] and line split the /// ones before and after that separately. bool _canDivideAt(int i) { // Don't divide after the last chunk. if (i == _chunks.length - 1) return false; var chunk = _chunks[i]; if (!chunk.rule.isHardened) return false; if (chunk.nesting.isNested) return false; if (chunk.isBlock) return false; return true; } /// Pre-processes the chunks after they are done being written by the visitor /// but before they are run through the line splitter. /// /// Marks ranges of chunks that can be line split independently to keep the /// batches we send to [LineSplitter] small. void _divideChunks() { // Harden all of the rules that we know get forced by containing hard // splits, along with all of the other rules they constrain. _hardenRules(); // Now that we know where all of the divided chunk sections are, mark the // chunks. for (var i = 0; i < _chunks.length; i++) { _chunks[i].markDivide(_canDivideAt(i)); } } /// Hardens the active rules when a hard split occurs within them. void _handleHardSplit() { if (_rules.isEmpty) return; // If the current rule doesn't care, it will "eat" the hard split and no // others will care either. if (!_rules.last.splitsOnInnerRules) return; // Start with the innermost rule. This will traverse the other rules it // constrains. _hardSplitRules.add(_rules.last); } /// Replaces all of the previously hardened rules with hard splits, along /// with every rule that those constrain to also split. /// /// This should only be called after all chunks have been written. void _hardenRules() { if (_hardSplitRules.isEmpty) return; walkConstraints(rule) { rule.harden(); // Follow this rule's constraints, recursively. for (var other in rule.constrainedRules) { if (other == rule) continue; if (!other.isHardened && rule.constrain(rule.fullySplitValue, other) == other.fullySplitValue) { walkConstraints(other); } } } for (var rule in _hardSplitRules) { walkConstraints(rule); } // Discard spans in hardened chunks since we know for certain they will // split anyway. for (var chunk in _chunks) { if (chunk.rule != null && chunk.rule.isHardened) { chunk.spans.clear(); } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/dart_formatter.dart
// 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 dart_style.src.dart_formatter; import 'dart:math' as math; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart'; import 'package:analyzer/src/generated/parser.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/string_source.dart'; import 'error_listener.dart'; import 'exceptions.dart'; import 'source_code.dart'; import 'source_visitor.dart'; import 'string_compare.dart' as string_compare; import 'style_fix.dart'; /// Dart source code formatter. class DartFormatter { /// The string that newlines should use. /// /// If not explicitly provided, this is inferred from the source text. If the /// first newline is `\r\n` (Windows), it will use that. Otherwise, it uses /// Unix-style line endings (`\n`). String lineEnding; /// The number of characters allowed in a single line. final int pageWidth; /// The number of characters of indentation to prefix the output lines with. final int indent; final Set<StyleFix> fixes = Set(); /// Creates a new formatter for Dart code. /// /// If [lineEnding] is given, that will be used for any newlines in the /// output. Otherwise, the line separator will be inferred from the line /// endings in the source file. /// /// If [indent] is given, that many levels of indentation will be prefixed /// before each resulting line in the output. /// /// While formatting, also applies any of the given [fixes]. DartFormatter( {this.lineEnding, int pageWidth, int indent, Iterable<StyleFix> fixes}) : pageWidth = pageWidth ?? 80, indent = indent ?? 0 { if (fixes != null) this.fixes.addAll(fixes); } /// Formats the given [source] string containing an entire Dart compilation /// unit. /// /// If [uri] is given, it is a [String] or [Uri] used to identify the file /// being formatted in error messages. String format(String source, {uri}) { if (uri == null) { // Do nothing. } else if (uri is Uri) { uri = uri.toString(); } else if (uri is String) { // Do nothing. } else { throw ArgumentError("uri must be `null`, a Uri, or a String."); } return formatSource(SourceCode(source, uri: uri, isCompilationUnit: true)) .text; } /// Formats the given [source] string containing a single Dart statement. String formatStatement(String source) { return formatSource(SourceCode(source, isCompilationUnit: false)).text; } /// Formats the given [source]. /// /// Returns a new [SourceCode] containing the formatted code and the resulting /// selection, if any. SourceCode formatSource(SourceCode source) { var errorListener = ErrorListener(); // Enable all features that are enabled by default in the current analyzer // version. // TODO(paulberry): consider plumbing in experiment enable flags from the // command line. var featureSet = FeatureSet.fromEnableFlags([ "extension-methods", "non-nullable", ]); // Tokenize the source. var reader = CharSequenceReader(source.text); var stringSource = StringSource(source.text, source.uri); var scanner = Scanner(stringSource, reader, errorListener); scanner.configureFeatures(featureSet); var startToken = scanner.tokenize(); var lineInfo = LineInfo(scanner.lineStarts); // Infer the line ending if not given one. Do it here since now we know // where the lines start. if (lineEnding == null) { // If the first newline is "\r\n", use that. Otherwise, use "\n". if (scanner.lineStarts.length > 1 && scanner.lineStarts[1] >= 2 && source.text[scanner.lineStarts[1] - 2] == '\r') { lineEnding = "\r\n"; } else { lineEnding = "\n"; } } errorListener.throwIfErrors(); // Parse it. var parser = Parser(stringSource, errorListener, featureSet: featureSet); parser.enableOptionalNewAndConst = true; parser.enableSetLiterals = true; AstNode node; if (source.isCompilationUnit) { node = parser.parseCompilationUnit(startToken); } else { node = parser.parseStatement(startToken); // Make sure we consumed all of the source. var token = node.endToken.next; if (token.type != TokenType.EOF) { var error = AnalysisError( stringSource, token.offset, math.max(token.length, 1), ParserErrorCode.UNEXPECTED_TOKEN, [token.lexeme]); throw FormatterException([error]); } } errorListener.throwIfErrors(); // Format it. var visitor = SourceVisitor(this, lineInfo, source); var output = visitor.run(node); // Sanity check that only whitespace was changed if that's all we expect. if (fixes.isEmpty && !string_compare.equalIgnoringWhitespace(source.text, output.text)) { throw UnexpectedOutputException(source.text, output.text); } return output; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/source_visitor.dart
// 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 dart_style.src.source_visitor; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/src/generated/source.dart'; import 'argument_list_visitor.dart'; import 'call_chain_visitor.dart'; import 'chunk.dart'; import 'chunk_builder.dart'; import 'dart_formatter.dart'; import 'rule/argument.dart'; import 'rule/combinator.dart'; import 'rule/metadata.dart'; import 'rule/rule.dart'; import 'rule/type_argument.dart'; import 'source_code.dart'; import 'style_fix.dart'; import 'whitespace.dart'; /// Visits every token of the AST and passes all of the relevant bits to a /// [ChunkBuilder]. class SourceVisitor extends ThrowingAstVisitor { /// Returns `true` if [node] is a method invocation that looks like it might /// be a static method or constructor call without a `new` keyword. /// /// With optional `new`, we can no longer reliably identify constructor calls /// statically, but we still don't want to mix named constructor calls into /// a call chain like: /// /// Iterable /// .generate(...) /// .toList(); /// /// And instead prefer: /// /// Iterable.generate(...) /// .toList(); /// /// So we try to identify these calls syntactically. The heuristic we use is /// that a target that's a capitalized name (possibly prefixed by "_") is /// assumed to be a class. /// /// This has the effect of also keeping static method calls with the class, /// but that tends to look pretty good too, and is certainly better than /// splitting up named constructors. static bool looksLikeStaticCall(Expression node) { if (node is! MethodInvocation) return false; var invocation = node as MethodInvocation; if (invocation.target == null) return false; // A prefixed unnamed constructor call: // // prefix.Foo(); if (invocation.target is SimpleIdentifier && _looksLikeClassName(invocation.methodName.name)) { return true; } // A prefixed or unprefixed named constructor call: // // Foo.named(); // prefix.Foo.named(); var target = invocation.target; if (target is PrefixedIdentifier) { target = (target as PrefixedIdentifier).identifier; } return target is SimpleIdentifier && _looksLikeClassName(target.name); } /// Whether [name] appears to be a type name. /// /// Type names begin with a capital letter and contain at least one lowercase /// letter (so that we can distinguish them from SCREAMING_CAPS constants). static bool _looksLikeClassName(String name) { // Handle the weird lowercase corelib names. if (name == "bool") return true; if (name == "double") return true; if (name == "int") return true; if (name == "num") return true; // TODO(rnystrom): A simpler implementation is to test against the regex // "_?[A-Z].*?[a-z]". However, that currently has much worse performance on // AOT: https://github.com/dart-lang/sdk/issues/37785. const underscore = 95; const capitalA = 65; const capitalZ = 90; const lowerA = 97; const lowerZ = 122; var start = 0; var firstChar = name.codeUnitAt(start++); // It can be private. if (firstChar == underscore) { if (name.length == 1) return false; firstChar = name.codeUnitAt(start++); } // It must start with a capital letter. if (firstChar < capitalA || firstChar > capitalZ) return false; // And have at least one lowercase letter in it. Otherwise it could be a // SCREAMING_CAPS constant. for (var i = start; i < name.length; i++) { var char = name.codeUnitAt(i); if (char >= lowerA && char <= lowerZ) return true; } return false; } /// The builder for the block that is currently being visited. ChunkBuilder builder; final DartFormatter _formatter; /// Cached line info for calculating blank lines. LineInfo _lineInfo; /// The source being formatted. final SourceCode _source; /// `true` if the visitor has written past the beginning of the selection in /// the original source text. bool _passedSelectionStart = false; /// `true` if the visitor has written past the end of the selection in the /// original source text. bool _passedSelectionEnd = false; /// The character offset of the end of the selection, if there is a selection. /// /// This is calculated and cached by [_findSelectionEnd]. int _selectionEnd; /// How many levels deep inside a constant context the visitor currently is. int _constNesting = 0; /// Whether we are currently fixing a typedef declaration. /// /// Set to `true` while traversing the parameters of a typedef being converted /// to the new syntax. The new syntax does not allow `int foo()` as a /// parameter declaration, so it needs to be converted to `int Function() foo` /// as part of the fix. bool _insideNewTypedefFix = false; /// A stack that tracks forcing nested collections to split. /// /// Each entry corresponds to a collection currently being visited and the /// value is whether or not it should be forced to split. Every time a /// collection is entered, it sets all of the existing elements to `true` /// then it pushes `false` for itself. /// /// When done visiting the elements, it removes its value. If it was set to /// `true`, we know we visited a nested collection so we force this one to /// split. final List<bool> _collectionSplits = []; /// The stack of current rules for handling parameter metadata. /// /// Each time a parameter (or type parameter) list is begun, a single rule /// for all of the metadata annotations on parameters in that list is pushed /// onto this stack. We reuse this rule for all annotations so that they split /// in unison. final List<MetadataRule> _metadataRules = []; /// The mapping for blocks that are managed by the argument list that contains /// them. /// /// When a block expression, such as a collection literal or a multiline /// string, appears inside an [ArgumentSublist], the argument list provides a /// rule for the body to split to ensure that all blocks split in unison. It /// also tracks the chunk before the argument that determines whether or not /// the block body is indented like an expression or a statement. /// /// Before a block argument is visited, [ArgumentSublist] binds itself to the /// beginning token of each block it controls. When we later visit that /// literal, we use the token to find that association. /// /// This mapping is also used for spread collection literals that appear /// inside control flow elements to ensure that when a "then" collection /// splits, the corresponding "else" one does too. final Map<Token, Rule> _blockRules = {}; final Map<Token, Chunk> _blockPreviousChunks = {}; /// Initialize a newly created visitor to write source code representing /// the visited nodes to the given [writer]. SourceVisitor(this._formatter, this._lineInfo, this._source) { builder = ChunkBuilder(_formatter, _source); } /// Runs the visitor on [node], formatting its contents. /// /// Returns a [SourceCode] containing the resulting formatted source and /// updated selection, if any. /// /// This is the only method that should be called externally. Everything else /// is effectively private. SourceCode run(AstNode node) { visit(node); // Output trailing comments. writePrecedingCommentsAndNewlines(node.endToken.next); assert(_constNesting == 0, "Should have exited all const contexts."); // Finish writing and return the complete result. return builder.end(); } visitAdjacentStrings(AdjacentStrings node) { // We generally want to indent adjacent strings because it can be confusing // otherwise when they appear in a list of expressions, like: // // [ // "one", // "two" // "three", // "four" // ] // // Especially when these stings are longer, it can be hard to tell that // "three" is a continuation of the previous argument. // // However, the indentation is distracting in argument lists that don't // suffer from this ambiguity: // // test( // "A very long test description..." // "this indentation looks bad.", () { ... }); // // To balance these, we omit the indentation when an adjacent string // expression is the only string in an argument list. var shouldNest = true; var parent = node.parent; if (parent is ArgumentList) { shouldNest = false; for (var argument in parent.arguments) { if (argument == node) continue; if (argument is StringLiteral) { shouldNest = true; break; } } } else if (parent is Assertion) { // Treat asserts like argument lists. shouldNest = false; if (parent.condition != node && parent.condition is StringLiteral) { shouldNest = true; } if (parent.message != node && parent.message is StringLiteral) { shouldNest = true; } } else if (parent is VariableDeclaration || parent is AssignmentExpression && parent.rightHandSide == node && parent.parent is ExpressionStatement) { // Don't add extra indentation in a variable initializer or assignment: // // var variable = // "no extra" // "indent"; shouldNest = false; } else if (parent is NamedExpression || parent is ExpressionFunctionBody) { shouldNest = false; } builder.startSpan(); builder.startRule(); if (shouldNest) builder.nestExpression(); visitNodes(node.strings, between: splitOrNewline); if (shouldNest) builder.unnest(); builder.endRule(); builder.endSpan(); } visitAnnotation(Annotation node) { token(node.atSign); visit(node.name); token(node.period); visit(node.constructorName); // Metadata annotations are always const contexts. _constNesting++; visit(node.arguments); _constNesting--; } /// Visits an argument list. /// /// This is a bit complex to handle the rules for formatting positional and /// named arguments. The goals, in rough order of descending priority are: /// /// 1. Keep everything on the first line. /// 2. Keep the named arguments together on the next line. /// 3. Keep everything together on the second line. /// 4. Split between one or more positional arguments, trying to keep as many /// on earlier lines as possible. /// 5. Split the named arguments each onto their own line. visitArgumentList(ArgumentList node, {bool nestExpression = true}) { // Corner case: handle empty argument lists. if (node.arguments.isEmpty) { token(node.leftParenthesis); // If there is a comment inside the parens, do allow splitting before it. if (node.rightParenthesis.precedingComments != null) soloZeroSplit(); token(node.rightParenthesis); return; } // If the argument list has a trailing comma, format it like a collection // literal where each argument goes on its own line, they are indented +2, // and the ")" ends up on its own line. if (hasCommaAfter(node.arguments.last)) { _visitCollectionLiteral( null, node.leftParenthesis, node.arguments, node.rightParenthesis); return; } if (nestExpression) builder.nestExpression(); ArgumentListVisitor(this, node).visit(); if (nestExpression) builder.unnest(); } visitAsExpression(AsExpression node) { builder.startSpan(); builder.nestExpression(); visit(node.expression); soloSplit(); token(node.asOperator); space(); visit(node.type); builder.unnest(); builder.endSpan(); } visitAssertInitializer(AssertInitializer node) { token(node.assertKeyword); var arguments = <Expression>[node.condition]; if (node.message != null) arguments.add(node.message); // If the argument list has a trailing comma, format it like a collection // literal where each argument goes on its own line, they are indented +2, // and the ")" ends up on its own line. if (hasCommaAfter(arguments.last)) { _visitCollectionLiteral( null, node.leftParenthesis, arguments, node.rightParenthesis); return; } builder.nestExpression(); var visitor = ArgumentListVisitor.forArguments( this, node.leftParenthesis, node.rightParenthesis, arguments); visitor.visit(); builder.unnest(); } visitAssertStatement(AssertStatement node) { _simpleStatement(node, () { token(node.assertKeyword); var arguments = [node.condition]; if (node.message != null) arguments.add(node.message); // If the argument list has a trailing comma, format it like a collection // literal where each argument goes on its own line, they are indented +2, // and the ")" ends up on its own line. if (hasCommaAfter(arguments.last)) { _visitCollectionLiteral( null, node.leftParenthesis, arguments, node.rightParenthesis); return; } var visitor = ArgumentListVisitor.forArguments( this, node.leftParenthesis, node.rightParenthesis, arguments); visitor.visit(); }); } visitAssignmentExpression(AssignmentExpression node) { builder.nestExpression(); visit(node.leftHandSide); _visitAssignment(node.operator, node.rightHandSide); builder.unnest(); } visitAwaitExpression(AwaitExpression node) { token(node.awaitKeyword); space(); visit(node.expression); } visitBinaryExpression(BinaryExpression node) { builder.startSpan(); // If a binary operator sequence appears immediately after a `=>`, don't // add an extra level of nesting. Instead, let the subsequent operands line // up with the first, as in: // // method() => // argument && // argument && // argument; var isArrowBody = node.parent is ExpressionFunctionBody; if (!isArrowBody) builder.nestExpression(); // Start lazily so we don't force the operator to split if a line comment // appears before the first operand. builder.startLazyRule(); // Flatten out a tree/chain of the same precedence. If we split on this // precedence level, we will break all of them. var precedence = node.operator.type.precedence; traverse(Expression e) { if (e is BinaryExpression && e.operator.type.precedence == precedence) { traverse(e.leftOperand); space(); token(e.operator); split(); traverse(e.rightOperand); } else { visit(e); } } // Blocks as operands to infix operators should always nest like regular // operands. (Granted, this case is exceedingly rare in real code.) builder.startBlockArgumentNesting(); traverse(node); builder.endBlockArgumentNesting(); if (!isArrowBody) builder.unnest(); builder.endSpan(); builder.endRule(); } visitBlock(Block node) { // Treat empty blocks specially. In most cases, they are not allowed to // split. However, an empty block as the then statement of an if with an // else is always split. if (_isEmptyCollection(node.statements, node.rightBracket)) { token(node.leftBracket); // Force a split when used as the then body of an if with an else: // // if (condition) { // } else ... if (node.parent is IfStatement) { var ifStatement = node.parent as IfStatement; if (ifStatement.elseStatement != null && ifStatement.thenStatement == node) { newline(); } } token(node.rightBracket); return; } // If the block is a function body, it may get expression-level indentation, // so handle it specially. Otherwise, just bump the indentation and keep it // in the current block. if (node.parent is BlockFunctionBody) { _startLiteralBody(node.leftBracket); } else { _beginBody(node.leftBracket); } var needsDouble = true; for (var statement in node.statements) { if (needsDouble) { twoNewlines(); } else { oneOrTwoNewlines(); } visit(statement); needsDouble = false; if (statement is FunctionDeclarationStatement) { // Add a blank line after non-empty block functions. var body = statement.functionDeclaration.functionExpression.body; if (body is BlockFunctionBody) { needsDouble = body.block.statements.isNotEmpty; } } } if (node.statements.isNotEmpty) newline(); if (node.parent is BlockFunctionBody) { _endLiteralBody(node.rightBracket, forceSplit: node.statements.isNotEmpty); } else { _endBody(node.rightBracket); } } visitBlockFunctionBody(BlockFunctionBody node) { // Space after the parameter list. space(); // The "async" or "sync" keyword. token(node.keyword); // The "*" in "async*" or "sync*". token(node.star); if (node.keyword != null) space(); visit(node.block); } visitBooleanLiteral(BooleanLiteral node) { token(node.literal); } visitBreakStatement(BreakStatement node) { _simpleStatement(node, () { token(node.breakKeyword); visit(node.label, before: space); }); } visitCascadeExpression(CascadeExpression node) { var splitIfOperandsSplit = node.cascadeSections.length > 1 || _isCollectionLike(node.target); // If the cascade sections have consistent names they can be broken // normally otherwise they always get their own line. if (splitIfOperandsSplit) { builder.startLazyRule(_allowInlineCascade(node) ? Rule() : Rule.hard()); } // If the target of the cascade is a method call (or chain of them), we // treat the nesting specially. Normally, you would end up with: // // receiver // .method() // .method() // ..cascade() // ..cascade(); // // This is logical, since the method chain is an operand of the cascade // expression, so it's more deeply nested. But it looks wrong, so we leave // the method chain's nesting active until after the cascade sections to // force the *cascades* to be deeper because it looks better: // // receiver // .method() // .method() // ..cascade() // ..cascade(); if (node.target is MethodInvocation) { CallChainVisitor(this, node.target).visit(unnest: false); } else { visit(node.target); } builder.nestExpression(indent: Indent.cascade, now: true); builder.startBlockArgumentNesting(); // If the cascade section shouldn't cause the cascade to split, end the // rule early so it isn't affected by it. if (!splitIfOperandsSplit) { builder.startRule(_allowInlineCascade(node) ? Rule() : Rule.hard()); } zeroSplit(); if (!splitIfOperandsSplit) { builder.endRule(); } visitNodes(node.cascadeSections, between: zeroSplit); if (splitIfOperandsSplit) { builder.endRule(); } builder.endBlockArgumentNesting(); builder.unnest(); if (node.target is MethodInvocation) builder.unnest(); } /// Whether [expression] is a collection literal, or a call with a trailing /// comma in an argument list. /// /// In that case, when the expression is a target of a cascade, we don't /// force a split before the ".." as eagerly to avoid ugly results like: /// /// [ /// 1, /// 2, /// ]..addAll(numbers); bool _isCollectionLike(Expression expression) { if (expression is ListLiteral) return false; if (expression is SetOrMapLiteral) return false; // If the target is a call with a trailing comma in the argument list, // treat it like a collection literal. ArgumentList arguments; if (expression is InvocationExpression) { arguments = expression.argumentList; } else if (expression is InstanceCreationExpression) { arguments = expression.argumentList; } // TODO(rnystrom): Do we want to allow an invocation where the last // argument is a collection literal? Like: // // foo(argument, [ // element // ])..cascade(); return arguments == null || arguments.arguments.isEmpty || !hasCommaAfter(arguments.arguments.last); } /// Whether a cascade should be allowed to be inline as opposed to one /// expression per line. bool _allowInlineCascade(CascadeExpression node) { // If the receiver is an expression that makes the cascade's very low // precedence confusing, force it to split. For example: // // a ? b : c..d(); // // Here, the cascade is applied to the result of the conditional, not "c". if (node.target is ConditionalExpression) return false; if (node.target is BinaryExpression) return false; if (node.target is PrefixExpression) return false; if (node.target is AwaitExpression) return false; if (node.cascadeSections.length < 2) return true; var name; // We could be more forgiving about what constitutes sections with // consistent names but for now we require all sections to have the same // method name. for (var expression in node.cascadeSections) { if (expression is MethodInvocation) { if (name == null) { name = expression.methodName.name; } else if (name != expression.methodName.name) { return false; } } else { return false; } } return true; } visitCatchClause(CatchClause node) { token(node.onKeyword, after: space); visit(node.exceptionType); if (node.catchKeyword != null) { if (node.exceptionType != null) { space(); } token(node.catchKeyword); space(); token(node.leftParenthesis); visit(node.exceptionParameter); token(node.comma, after: space); visit(node.stackTraceParameter); token(node.rightParenthesis); space(); } else { space(); } visit(node.body); } visitClassDeclaration(ClassDeclaration node) { visitMetadata(node.metadata); builder.nestExpression(); modifier(node.abstractKeyword); token(node.classKeyword); space(); visit(node.name); visit(node.typeParameters); visit(node.extendsClause); builder.startRule(CombinatorRule()); visit(node.withClause); visit(node.implementsClause); builder.endRule(); visit(node.nativeClause, before: space); space(); builder.unnest(); _beginBody(node.leftBracket); _visitMembers(node.members); _endBody(node.rightBracket); } visitClassTypeAlias(ClassTypeAlias node) { visitMetadata(node.metadata); _simpleStatement(node, () { modifier(node.abstractKeyword); token(node.typedefKeyword); space(); visit(node.name); visit(node.typeParameters); space(); token(node.equals); space(); visit(node.superclass); builder.startRule(CombinatorRule()); visit(node.withClause); visit(node.implementsClause); builder.endRule(); }); } visitComment(Comment node) => null; visitCommentReference(CommentReference node) => null; visitCompilationUnit(CompilationUnit node) { visit(node.scriptTag); // Put a blank line between the library tag and the other directives. Iterable<Directive> directives = node.directives; if (directives.isNotEmpty && directives.first is LibraryDirective) { visit(directives.first); twoNewlines(); directives = directives.skip(1); } visitNodes(directives, between: oneOrTwoNewlines); var needsDouble = true; for (var declaration in node.declarations) { var hasClassBody = declaration is ClassDeclaration || declaration is ExtensionDeclaration; // Add a blank line before declarations with class-like bodies. if (hasClassBody) needsDouble = true; if (needsDouble) { twoNewlines(); } else { // Variables and arrow-bodied members can be more tightly packed if // the user wants to group things together. oneOrTwoNewlines(); } visit(declaration); needsDouble = false; if (hasClassBody) { // Add a blank line after declarations with class-like bodies. needsDouble = true; } else if (declaration is FunctionDeclaration) { // Add a blank line after non-empty block functions. var body = declaration.functionExpression.body; if (body is BlockFunctionBody) { needsDouble = body.block.statements.isNotEmpty; } } } } visitConditionalExpression(ConditionalExpression node) { builder.nestExpression(); // Start lazily so we don't force the operator to split if a line comment // appears before the first operand. If we split after one clause in a // conditional, always split after both. builder.startLazyRule(); visit(node.condition); // Push any block arguments all the way past the leading "?" and ":". builder.nestExpression(indent: Indent.block, now: true); builder.startBlockArgumentNesting(); builder.unnest(); builder.startSpan(); split(); token(node.question); space(); builder.nestExpression(); visit(node.thenExpression); builder.unnest(); split(); token(node.colon); space(); visit(node.elseExpression); builder.endRule(); builder.endSpan(); builder.endBlockArgumentNesting(); builder.unnest(); } visitConfiguration(Configuration node) { token(node.ifKeyword); space(); token(node.leftParenthesis); visit(node.name); if (node.equalToken != null) { builder.nestExpression(); space(); token(node.equalToken); soloSplit(); visit(node.value); builder.unnest(); } token(node.rightParenthesis); space(); visit(node.uri); } visitConstructorDeclaration(ConstructorDeclaration node) { visitMetadata(node.metadata); modifier(node.externalKeyword); modifier(node.constKeyword); modifier(node.factoryKeyword); visit(node.returnType); token(node.period); visit(node.name); // Make the rule for the ":" span both the preceding parameter list and // the entire initialization list. This ensures that we split before the // ":" if the parameters and initialization list don't all fit on one line. builder.startRule(); // If the redirecting constructor happens to wrap, we want to make sure // the parameter list gets more deeply indented. if (node.redirectedConstructor != null) builder.nestExpression(); _visitBody(null, node.parameters, node.body, () { // Check for redirects or initializer lists. if (node.redirectedConstructor != null) { _visitConstructorRedirects(node); builder.unnest(); } else if (node.initializers.isNotEmpty) { _visitConstructorInitializers(node); } }); } void _visitConstructorRedirects(ConstructorDeclaration node) { token(node.separator /* = */, before: space); soloSplit(); visitCommaSeparatedNodes(node.initializers); visit(node.redirectedConstructor); } void _visitConstructorInitializers(ConstructorDeclaration node) { var hasTrailingComma = node.parameters.parameters.isNotEmpty && hasCommaAfter(node.parameters.parameters.last); if (hasTrailingComma) { // Since the ")", "])", or "})" on the preceding line doesn't take up // much space, it looks weird to move the ":" onto it's own line. Instead, // keep it and the first initializer on the current line but add enough // space before it to line it up with any subsequent initializers. // // Foo( // parameter, // ) : field = value, // super(); space(); if (node.initializers.length > 1) { _writeText(node.parameters.parameters.last.isOptional ? " " : " ", node.separator.offset); } // ":". token(node.separator); space(); builder.indent(6); } else { // Shift the itself ":" forward. builder.indent(Indent.constructorInitializer); // If the parameters or initializers split, put the ":" on its own line. split(); // ":". token(node.separator); space(); // Try to line up the initializers with the first one that follows the ":": // // Foo(notTrailing) // : initializer = value, // super(); // +2 from previous line. // // Foo( // trailing, // ) : initializer = value, // super(); // +4 from previous line. // // This doesn't work if there is a trailing comma in an optional parameter, // but we don't want to do a weird +5 alignment: // // Foo({ // trailing, // }) : initializer = value, // super(); // Doesn't quite line up. :( builder.indent(2); } for (var i = 0; i < node.initializers.length; i++) { if (i > 0) { // Preceding comma. token(node.initializers[i].beginToken.previous); newline(); } node.initializers[i].accept(this); } builder.unindent(); if (!hasTrailingComma) builder.unindent(); // End the rule for ":" after all of the initializers. builder.endRule(); } visitConstructorFieldInitializer(ConstructorFieldInitializer node) { builder.nestExpression(); token(node.thisKeyword); token(node.period); visit(node.fieldName); _visitAssignment(node.equals, node.expression); builder.unnest(); } visitConstructorName(ConstructorName node) { visit(node.type); token(node.period); visit(node.name); } visitContinueStatement(ContinueStatement node) { _simpleStatement(node, () { token(node.continueKeyword); visit(node.label, before: space); }); } visitDeclaredIdentifier(DeclaredIdentifier node) { modifier(node.keyword); visit(node.type, after: space); visit(node.identifier); } visitDefaultFormalParameter(DefaultFormalParameter node) { visit(node.parameter); if (node.separator != null) { builder.startSpan(); builder.nestExpression(); if (_formatter.fixes.contains(StyleFix.namedDefaultSeparator)) { // Change the separator to "=". space(); writePrecedingCommentsAndNewlines(node.separator); _writeText("=", node.separator.offset); } else { // The '=' separator is preceded by a space, ":" is not. if (node.separator.type == TokenType.EQ) space(); token(node.separator); } soloSplit(_assignmentCost(node.defaultValue)); visit(node.defaultValue); builder.unnest(); builder.endSpan(); } } visitDoStatement(DoStatement node) { builder.nestExpression(); token(node.doKeyword); space(); builder.unnest(now: false); visit(node.body); builder.nestExpression(); space(); token(node.whileKeyword); space(); token(node.leftParenthesis); soloZeroSplit(); visit(node.condition); token(node.rightParenthesis); token(node.semicolon); builder.unnest(); } visitDottedName(DottedName node) { for (var component in node.components) { // Write the preceding ".". if (component != node.components.first) { token(component.beginToken.previous); } visit(component); } } visitDoubleLiteral(DoubleLiteral node) { token(node.literal); } visitEmptyFunctionBody(EmptyFunctionBody node) { token(node.semicolon); } visitEmptyStatement(EmptyStatement node) { token(node.semicolon); } visitEnumConstantDeclaration(EnumConstantDeclaration node) { visitMetadata(node.metadata); visit(node.name); } visitEnumDeclaration(EnumDeclaration node) { visitMetadata(node.metadata); token(node.enumKeyword); space(); visit(node.name); space(); _beginBody(node.leftBracket, space: true); visitCommaSeparatedNodes(node.constants, between: splitOrTwoNewlines); // If there is a trailing comma, always force the constants to split. if (hasCommaAfter(node.constants.last)) { builder.forceRules(); } _endBody(node.rightBracket, space: true); } visitExportDirective(ExportDirective node) { _visitDirectiveMetadata(node); _simpleStatement(node, () { token(node.keyword); space(); visit(node.uri); _visitConfigurations(node.configurations); builder.startRule(CombinatorRule()); visitNodes(node.combinators); builder.endRule(); }); } visitExpressionFunctionBody(ExpressionFunctionBody node) { // Space after the parameter list. space(); // The "async" or "sync" keyword. token(node.keyword, after: space); // Try to keep the "(...) => " with the start of the body for anonymous // functions. if (_isInLambda(node)) builder.startSpan(); token(node.functionDefinition); // "=>". // Split after the "=>", using the rule created before the parameters // by _visitBody(). split(); // If the body is a binary operator expression, then we want to force the // split at `=>` if the operators split. See visitBinaryExpression(). if (node.expression is! BinaryExpression) builder.endRule(); if (_isInLambda(node)) builder.endSpan(); // If this function invocation appears in an argument list with trailing // comma, don't add extra nesting to preserve normal indentation. var isArgWithTrailingComma = false; var parent = node.parent; if (parent is FunctionExpression) { isArgWithTrailingComma = _isTrailingCommaArgument(parent); } if (!isArgWithTrailingComma) builder.startBlockArgumentNesting(); builder.startSpan(); visit(node.expression); builder.endSpan(); if (!isArgWithTrailingComma) builder.endBlockArgumentNesting(); if (node.expression is BinaryExpression) builder.endRule(); token(node.semicolon); } visitExpressionStatement(ExpressionStatement node) { _simpleStatement(node, () { visit(node.expression); }); } visitExtendsClause(ExtendsClause node) { soloSplit(); token(node.extendsKeyword); space(); visit(node.superclass); } void visitExtensionDeclaration(ExtensionDeclaration node) { visitMetadata(node.metadata); builder.nestExpression(); token(node.extensionKeyword); // Don't put a space after `extension` if the extension is unnamed. That // way, generic unnamed extensions format like `extension<T> on ...`. if (node.name != null) { space(); visit(node.name); } visit(node.typeParameters); soloSplit(); token(node.onKeyword); space(); visit(node.extendedType); space(); builder.unnest(); _beginBody(node.leftBracket); _visitMembers(node.members); _endBody(node.rightBracket); } visitFieldDeclaration(FieldDeclaration node) { visitMetadata(node.metadata); _simpleStatement(node, () { modifier(node.staticKeyword); modifier(node.covariantKeyword); visit(node.fields); }); } visitFieldFormalParameter(FieldFormalParameter node) { visitParameterMetadata(node.metadata, () { _beginFormalParameter(node); token(node.keyword, after: space); visit(node.type, after: split); token(node.thisKeyword); token(node.period); visit(node.identifier); visit(node.parameters); _endFormalParameter(node); }); } visitFormalParameterList(FormalParameterList node, {bool nestExpression = true}) { // Corner case: empty parameter lists. if (node.parameters.isEmpty) { token(node.leftParenthesis); // If there is a comment, do allow splitting before it. if (node.rightParenthesis.precedingComments != null) soloZeroSplit(); token(node.rightParenthesis); return; } // If the parameter list has a trailing comma, format it like a collection // literal where each parameter goes on its own line, they are indented +2, // and the ")" ends up on its own line. if (hasCommaAfter(node.parameters.last)) { _visitTrailingCommaParameterList(node); return; } var requiredParams = node.parameters .where((param) => param is! DefaultFormalParameter) .toList(); var optionalParams = node.parameters.whereType<DefaultFormalParameter>().toList(); if (nestExpression) builder.nestExpression(); token(node.leftParenthesis); _metadataRules.add(MetadataRule()); var rule; if (requiredParams.isNotEmpty) { rule = PositionalRule(null, 0, 0); _metadataRules.last.bindPositionalRule(rule); builder.startRule(rule); if (_isInLambda(node)) { // Don't allow splitting before the first argument (i.e. right after // the bare "(" in a lambda. Instead, just stuff a null chunk in there // to avoid confusing the arg rule. rule.beforeArgument(null); } else { // Split before the first argument. rule.beforeArgument(zeroSplit()); } builder.startSpan(); for (var param in requiredParams) { visit(param); _writeCommaAfter(param); if (param != requiredParams.last) rule.beforeArgument(split()); } builder.endSpan(); builder.endRule(); } if (optionalParams.isNotEmpty) { var namedRule = NamedRule(null, 0, 0); if (rule != null) rule.setNamedArgsRule(namedRule); _metadataRules.last.bindNamedRule(namedRule); builder.startRule(namedRule); // Make sure multi-line default values are indented. builder.startBlockArgumentNesting(); namedRule.beforeArgument(builder.split(space: requiredParams.isNotEmpty)); // "[" or "{" for optional parameters. token(node.leftDelimiter); for (var param in optionalParams) { visit(param); _writeCommaAfter(param); if (param != optionalParams.last) namedRule.beforeArgument(split()); } builder.endBlockArgumentNesting(); builder.endRule(); // "]" or "}" for optional parameters. token(node.rightDelimiter); } _metadataRules.removeLast(); token(node.rightParenthesis); if (nestExpression) builder.unnest(); } void visitForElement(ForElement node) { // Treat a spread of a collection literal like a block in a for statement // and don't split after the for parts. var isSpreadBody = _isSpreadCollection(node.body); builder.nestExpression(); token(node.awaitKeyword, after: space); token(node.forKeyword); space(); token(node.leftParenthesis); // Start the body rule so that if the parts split, the body does too. builder.startRule(); // The rule for the parts. builder.startRule(); visit(node.forLoopParts); token(node.rightParenthesis); builder.endRule(); builder.unnest(); builder.nestExpression(indent: 2, now: true); if (isSpreadBody) { space(); } else { split(); // If the body is a non-spread collection or lambda, indent it. builder.startBlockArgumentNesting(); } visit(node.body); if (!isSpreadBody) builder.endBlockArgumentNesting(); builder.unnest(); builder.endRule(); } visitForStatement(ForStatement node) { builder.nestExpression(); token(node.awaitKeyword, after: space); token(node.forKeyword); space(); token(node.leftParenthesis); builder.startRule(); visit(node.forLoopParts); token(node.rightParenthesis); builder.endRule(); builder.unnest(); _visitLoopBody(node.body); } visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { // TODO(rnystrom): The formatting logic here is slightly different from // how parameter metadata is handled and from how variable metadata is // handled. I think what it does works better in the context of a for-in // loop, but consider trying to unify this with one of the above. // // Metadata on class and variable declarations is *always* split: // // @foo // class Bar {} // // Metadata on parameters has some complex logic to handle multiple // parameters with metadata. It also indents the parameters farther than // the metadata when split: // // function( // @foo(long arg list...) // parameter1, // @foo // parameter2) {} // // For for-in variables, we allow it to not split, like parameters, but // don't indent the variable when it does split: // // for ( // @foo // @bar // var blah in stuff) {} // TODO(rnystrom): we used to call builder.startRule() here, but now we call // it from visitForStatement2 prior to the `(`. Is that ok? visitNodes(node.loopVariable.metadata, between: split, after: split); visit(node.loopVariable); // TODO(rnystrom): we used to call builder.endRule() here, but now we call // it from visitForStatement2 after the `)`. Is that ok? _visitForEachPartsFromIn(node); } void _visitForEachPartsFromIn(ForEachParts node) { soloSplit(); token(node.inKeyword); space(); visit(node.iterable); } visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) { visit(node.identifier); _visitForEachPartsFromIn(node); } visitForPartsWithDeclarations(ForPartsWithDeclarations node) { // Nest split variables more so they aren't at the same level // as the rest of the loop clauses. builder.nestExpression(); // Allow the variables to stay unsplit even if the clauses split. builder.startRule(); var declaration = node.variables; visitMetadata(declaration.metadata); modifier(declaration.keyword); visit(declaration.type, after: space); visitCommaSeparatedNodes(declaration.variables, between: () { split(); }); builder.endRule(); builder.unnest(); _visitForPartsFromLeftSeparator(node); } visitForPartsWithExpression(ForPartsWithExpression node) { visit(node.initialization); _visitForPartsFromLeftSeparator(node); } void _visitForPartsFromLeftSeparator(ForParts node) { token(node.leftSeparator); // The condition clause. if (node.condition != null) split(); visit(node.condition); token(node.rightSeparator); // The update clause. if (node.updaters.isNotEmpty) { split(); // Allow the updates to stay unsplit even if the clauses split. builder.startRule(); visitCommaSeparatedNodes(node.updaters, between: split); builder.endRule(); } } visitFunctionDeclaration(FunctionDeclaration node) { _visitMemberDeclaration(node, node.functionExpression); } visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { visit(node.functionDeclaration); } visitFunctionExpression(FunctionExpression node) { // Inside a function body is no longer in the surrounding const context. var oldConstNesting = _constNesting; _constNesting = 0; // TODO(rnystrom): This is working but not tested. As of 2016/11/29, the // latest version of analyzer on pub does not parse generic lambdas. When // a version of it that does is published, upgrade dart_style to use it and // then test it: // // >>> generic function expression // main() { // var generic = < T,S >(){}; // } // <<< // main() { // var generic = <T, S>() {}; // } _visitBody(node.typeParameters, node.parameters, node.body); _constNesting = oldConstNesting; } visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { // Try to keep the entire invocation one line. builder.startSpan(); builder.nestExpression(); visit(node.function); visit(node.typeArguments); visitArgumentList(node.argumentList, nestExpression: false); builder.unnest(); builder.endSpan(); } visitFunctionTypeAlias(FunctionTypeAlias node) { visitMetadata(node.metadata); if (_formatter.fixes.contains(StyleFix.functionTypedefs)) { _simpleStatement(node, () { // Inlined visitGenericTypeAlias _visitGenericTypeAliasHeader(node.typedefKeyword, node.name, node.typeParameters, null, (node.returnType ?? node.name).offset); space(); // Recursively convert function-arguments to Function syntax. _insideNewTypedefFix = true; _visitGenericFunctionType( node.returnType, null, node.name.offset, null, node.parameters); _insideNewTypedefFix = false; }); return; } _simpleStatement(node, () { token(node.typedefKeyword); space(); visit(node.returnType, after: space); visit(node.name); visit(node.typeParameters); visit(node.parameters); }); } visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { visitParameterMetadata(node.metadata, () { if (!_insideNewTypedefFix) { modifier(node.requiredKeyword); modifier(node.covariantKeyword); visit(node.returnType, after: space); // Try to keep the function's parameters with its name. builder.startSpan(); visit(node.identifier); _visitParameterSignature(node.typeParameters, node.parameters); token(node.question); builder.endSpan(); } else { _beginFormalParameter(node); _visitGenericFunctionType(node.returnType, null, node.identifier.offset, node.typeParameters, node.parameters); token(node.question); split(); visit(node.identifier); _endFormalParameter(node); } }); } visitGenericFunctionType(GenericFunctionType node) { _visitGenericFunctionType(node.returnType, node.functionKeyword, null, node.typeParameters, node.parameters); token(node.question); } visitGenericTypeAlias(GenericTypeAlias node) { visitNodes(node.metadata, between: newline, after: newline); _simpleStatement(node, () { _visitGenericTypeAliasHeader(node.typedefKeyword, node.name, node.typeParameters, node.equals, null); space(); visit(node.functionType); }); } visitHideCombinator(HideCombinator node) { _visitCombinator(node.keyword, node.hiddenNames); } void visitIfElement(IfElement node) { // Treat a chain of if-else elements as a single unit so that we don't // unnecessarily indent each subsequent section of the chain. var ifElements = [ for (CollectionElement thisNode = node; thisNode is IfElement; thisNode = (thisNode as IfElement).elseElement) thisNode as IfElement ]; // If the body of the then or else branch is a spread of a collection // literal, then we want to format those collections more like blocks than // like standalone objects. In particular, if both the then and else branch // are spread collection literals, we want to ensure that they both split // if either splits. So this: // // [ // if (condition) ...[ // thenClause // ] else ...[ // elseClause // ] // ] // // And not something like this: // // [ // if (condition) ...[ // thenClause // ] else ...[elseClause] // ] // // To do that, if we see that either clause is a spread collection, we // create a single rule and force both collections to use it. var spreadRule = Rule(); var spreadBrackets = <CollectionElement, Token>{}; for (var element in ifElements) { var spreadBracket = _findSpreadCollectionBracket(element.thenElement); if (spreadBracket != null) { spreadBrackets[element] = spreadBracket; beforeBlock(spreadBracket, spreadRule, null); } } var elseSpreadBracket = _findSpreadCollectionBracket(ifElements.last.elseElement); if (elseSpreadBracket != null) { spreadBrackets[ifElements.last.elseElement] = elseSpreadBracket; beforeBlock(elseSpreadBracket, spreadRule, null); } visitChild(CollectionElement element, CollectionElement child) { builder.nestExpression(indent: 2, now: true); // Treat a spread of a collection literal like a block in an if statement // and don't split after the "else". var isSpread = spreadBrackets.containsKey(element); if (isSpread) { space(); } else { split(); // If the then clause is a non-spread collection or lambda, make sure the // body is indented. builder.startBlockArgumentNesting(); } visit(child); if (!isSpread) builder.endBlockArgumentNesting(); builder.unnest(); } // Wrap the whole thing in a single rule. If a split happens inside the // condition or the then clause, we want the then and else clauses to split. builder.startRule(); for (var element in ifElements) { // The condition. token(element.ifKeyword); space(); token(element.leftParenthesis); visit(element.condition); token(element.rightParenthesis); visitChild(element, element.thenElement); // Handle this element's "else" keyword and prepare to write the element, // but don't write it. It will either be the next element in [ifElements] // or the final else element handled after the loop. if (element.elseElement != null) { if (spreadBrackets.containsKey(element)) { space(); } else { split(); } token(node.elseKeyword); // If there is another if element in the chain, put a space between // it and this "else". if (element != ifElements.last) space(); } } // Handle the final trailing else if there is one. var lastElse = ifElements.last.elseElement; if (lastElse != null) visitChild(lastElse, lastElse); builder.endRule(); } visitIfStatement(IfStatement node) { builder.nestExpression(); token(node.ifKeyword); space(); token(node.leftParenthesis); visit(node.condition); token(node.rightParenthesis); builder.unnest(); visitClause(Statement clause) { if (clause is Block || clause is IfStatement) { space(); visit(clause); } else { // Allow splitting in a statement-bodied if even though it's against // the style guide. Since we can't fix the code itself to follow the // style guide, we should at least format it as well as we can. builder.indent(); builder.startRule(); // If there is an else clause, always split before both the then and // else statements. if (node.elseStatement != null) { builder.writeWhitespace(Whitespace.newline); } else { builder.split(nest: false, space: true); } visit(clause); builder.endRule(); builder.unindent(); } } visitClause(node.thenStatement); if (node.elseStatement != null) { if (node.thenStatement is Block) { space(); } else { // Corner case where an else follows a single-statement then clause. // This is against the style guide, but we still need to handle it. If // it happens, put the else on the next line. newline(); } token(node.elseKeyword); visitClause(node.elseStatement); } } visitImplementsClause(ImplementsClause node) { _visitCombinator(node.implementsKeyword, node.interfaces); } visitImportDirective(ImportDirective node) { _visitDirectiveMetadata(node); _simpleStatement(node, () { token(node.keyword); space(); visit(node.uri); _visitConfigurations(node.configurations); if (node.asKeyword != null) { soloSplit(); token(node.deferredKeyword, after: space); token(node.asKeyword); space(); visit(node.prefix); } builder.startRule(CombinatorRule()); visitNodes(node.combinators); builder.endRule(); }); } visitIndexExpression(IndexExpression node) { builder.nestExpression(); if (node.isCascaded) { token(node.period); } else { visit(node.target); } finishIndexExpression(node); builder.unnest(); } /// Visit the index part of [node], excluding the target. /// /// Called by [CallChainVisitor] to handle index expressions in the middle of /// call chains. void finishIndexExpression(IndexExpression node) { if (node.target is IndexExpression) { // Edge case: On a chain of [] accesses, allow splitting between them. // Produces nicer output in cases like: // // someJson['property']['property']['property']['property']... soloZeroSplit(); } builder.startSpan(Cost.index); token(node.leftBracket); soloZeroSplit(); visit(node.index); token(node.rightBracket); builder.endSpan(); } visitInstanceCreationExpression(InstanceCreationExpression node) { builder.startSpan(); var includeKeyword = true; if (node.keyword != null) { if (node.keyword.keyword == Keyword.NEW && _formatter.fixes.contains(StyleFix.optionalNew)) { includeKeyword = false; } else if (node.keyword.keyword == Keyword.CONST && _formatter.fixes.contains(StyleFix.optionalConst) && _constNesting > 0) { includeKeyword = false; } } if (includeKeyword) { token(node.keyword, after: space); } else { // Don't lose comments before the discarded keyword, if any. writePrecedingCommentsAndNewlines(node.keyword); } builder.startSpan(Cost.constructorName); // Start the expression nesting for the argument list here, in case this // is a generic constructor with type arguments. If it is, we need the type // arguments to be nested too so they get indented past the arguments. builder.nestExpression(); visit(node.constructorName); _startPossibleConstContext(node.keyword); builder.endSpan(); visitArgumentList(node.argumentList, nestExpression: false); builder.endSpan(); _endPossibleConstContext(node.keyword); builder.unnest(); } visitIntegerLiteral(IntegerLiteral node) { token(node.literal); } visitInterpolationExpression(InterpolationExpression node) { builder.preventSplit(); token(node.leftBracket); builder.startSpan(); visit(node.expression); builder.endSpan(); token(node.rightBracket); builder.endPreventSplit(); } visitInterpolationString(InterpolationString node) { _writeStringLiteral(node.contents); } visitIsExpression(IsExpression node) { builder.startSpan(); builder.nestExpression(); visit(node.expression); soloSplit(); token(node.isOperator); token(node.notOperator); space(); visit(node.type); builder.unnest(); builder.endSpan(); } visitLabel(Label node) { visit(node.label); token(node.colon); } visitLabeledStatement(LabeledStatement node) { _visitLabels(node.labels); visit(node.statement); } visitLibraryDirective(LibraryDirective node) { _visitDirectiveMetadata(node); _simpleStatement(node, () { token(node.keyword); space(); visit(node.name); }); } visitLibraryIdentifier(LibraryIdentifier node) { visit(node.components.first); for (var component in node.components.skip(1)) { token(component.beginToken.previous); // "." visit(component); } } visitListLiteral(ListLiteral node) { // Corner case: Splitting inside a list looks bad if there's only one // element, so make those more costly. var cost = node.elements.length <= 1 ? Cost.singleElementList : Cost.normal; _visitCollectionLiteral( node, node.leftBracket, node.elements, node.rightBracket, cost); } visitMapLiteralEntry(MapLiteralEntry node) { builder.nestExpression(); visit(node.key); token(node.separator); soloSplit(); visit(node.value); builder.unnest(); } visitMethodDeclaration(MethodDeclaration node) { _visitMemberDeclaration(node, node); } visitMethodInvocation(MethodInvocation node) { // If there's no target, this is a "bare" function call like "foo(1, 2)", // or a section in a cascade. // // If it looks like a constructor or static call, we want to keep the // target and method together instead of including the method in the // subsequent method chain. When this happens, it's important that this // code here has the same rules as in [visitInstanceCreationExpression]. // // That ensures that the way some code is formatted is not affected by the // presence or absence of `new`/`const`. In particular, it means that if // they run `dartfmt --fix`, and then run `dartfmt` *again*, the second run // will not produce any additional changes. if (node.target == null || looksLikeStaticCall(node)) { // Try to keep the entire method invocation one line. builder.nestExpression(); builder.startSpan(); if (node.target != null) { builder.startSpan(Cost.constructorName); visit(node.target); soloZeroSplit(); } // If target is null, this will be `..` for a cascade. token(node.operator); visit(node.methodName); if (node.target != null) builder.endSpan(); // TODO(rnystrom): Currently, there are no constraints between a generic // method's type arguments and arguments. That can lead to some funny // splitting like: // // method<VeryLongType, // AnotherTypeArgument>(argument, // argument, argument, argument); // // The indentation is fine, but splitting in the middle of each argument // list looks kind of strange. If this ends up happening in real world // code, consider putting a constraint between them. builder.nestExpression(); visit(node.typeArguments); visitArgumentList(node.argumentList, nestExpression: false); builder.unnest(); builder.endSpan(); builder.unnest(); return; } CallChainVisitor(this, node).visit(); } visitMixinDeclaration(MixinDeclaration node) { visitMetadata(node.metadata); builder.nestExpression(); token(node.mixinKeyword); space(); visit(node.name); visit(node.typeParameters); // If there is only a single superclass constraint, format it like an // "extends" in a class. if (node.onClause != null && node.onClause.superclassConstraints.length == 1) { soloSplit(); token(node.onClause.onKeyword); space(); visit(node.onClause.superclassConstraints.single); } builder.startRule(CombinatorRule()); // If there are multiple superclass constraints, format them like the // "implements" clause. if (node.onClause != null && node.onClause.superclassConstraints.length > 1) { visit(node.onClause); } visit(node.implementsClause); builder.endRule(); space(); builder.unnest(); _beginBody(node.leftBracket); _visitMembers(node.members); _endBody(node.rightBracket); } visitNamedExpression(NamedExpression node) { visitNamedArgument(node); } visitNativeClause(NativeClause node) { token(node.nativeKeyword); visit(node.name, before: space); } visitNativeFunctionBody(NativeFunctionBody node) { _simpleStatement(node, () { builder.nestExpression(now: true); soloSplit(); token(node.nativeKeyword); visit(node.stringLiteral, before: space); builder.unnest(); }); } visitNullLiteral(NullLiteral node) { token(node.literal); } visitOnClause(OnClause node) { _visitCombinator(node.onKeyword, node.superclassConstraints); } visitParenthesizedExpression(ParenthesizedExpression node) { builder.nestExpression(); token(node.leftParenthesis); visit(node.expression); builder.unnest(); token(node.rightParenthesis); } visitPartDirective(PartDirective node) { _visitDirectiveMetadata(node); _simpleStatement(node, () { token(node.keyword); space(); visit(node.uri); }); } visitPartOfDirective(PartOfDirective node) { _visitDirectiveMetadata(node); _simpleStatement(node, () { token(node.keyword); space(); token(node.ofKeyword); space(); // Part-of may have either a name or a URI. Only one of these will be // non-null. We visit both since visit() ignores null. visit(node.libraryName); visit(node.uri); }); } visitPostfixExpression(PostfixExpression node) { visit(node.operand); token(node.operator); } visitPrefixedIdentifier(PrefixedIdentifier node) { CallChainVisitor(this, node).visit(); } visitPrefixExpression(PrefixExpression node) { token(node.operator); // Edge case: put a space after "-" if the operand is "-" or "--" so we // don't merge the operators. var operand = node.operand; if (operand is PrefixExpression && (operand.operator.lexeme == "-" || operand.operator.lexeme == "--")) { space(); } visit(node.operand); } visitPropertyAccess(PropertyAccess node) { if (node.isCascaded) { token(node.operator); visit(node.propertyName); return; } CallChainVisitor(this, node).visit(); } visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) { builder.startSpan(); token(node.thisKeyword); token(node.period); visit(node.constructorName); visit(node.argumentList); builder.endSpan(); } visitRethrowExpression(RethrowExpression node) { token(node.rethrowKeyword); } visitReturnStatement(ReturnStatement node) { _simpleStatement(node, () { token(node.returnKeyword); visit(node.expression, before: space); }); } visitScriptTag(ScriptTag node) { // The lexeme includes the trailing newline. Strip it off since the // formatter ensures it gets a newline after it. Since the script tag must // come at the top of the file, we don't have to worry about preceding // comments or whitespace. _writeText(node.scriptTag.lexeme.trim(), node.offset); newline(); } visitSetOrMapLiteral(SetOrMapLiteral node) { _visitCollectionLiteral( node, node.leftBracket, node.elements, node.rightBracket); } visitShowCombinator(ShowCombinator node) { _visitCombinator(node.keyword, node.shownNames); } visitSimpleFormalParameter(SimpleFormalParameter node) { visitParameterMetadata(node.metadata, () { _beginFormalParameter(node); modifier(node.keyword); var hasType = node.type != null; if (_insideNewTypedefFix && !hasType) { // In function declarations and the old typedef syntax, you can have a // parameter name without a type. In the new syntax, you can have a type // without a name. Add "dynamic" in that case. // Ensure comments on the identifier comes before the inserted type. token(node.identifier.token, before: () { _writeText("dynamic", node.identifier.offset); split(); }); } else { visit(node.type); if (hasType && node.identifier != null) split(); visit(node.identifier); } _endFormalParameter(node); }); } visitSimpleIdentifier(SimpleIdentifier node) { token(node.token); } visitSimpleStringLiteral(SimpleStringLiteral node) { _writeStringLiteral(node.literal); } visitSpreadElement(SpreadElement node) { token(node.spreadOperator); visit(node.expression); } visitStringInterpolation(StringInterpolation node) { for (var element in node.elements) { visit(element); } } visitSuperConstructorInvocation(SuperConstructorInvocation node) { builder.startSpan(); token(node.superKeyword); token(node.period); visit(node.constructorName); visit(node.argumentList); builder.endSpan(); } visitSuperExpression(SuperExpression node) { token(node.superKeyword); } visitSwitchCase(SwitchCase node) { _visitLabels(node.labels); token(node.keyword); space(); visit(node.expression); token(node.colon); builder.indent(); // TODO(rnystrom): Allow inline cases? newline(); visitNodes(node.statements, between: oneOrTwoNewlines); builder.unindent(); } visitSwitchDefault(SwitchDefault node) { _visitLabels(node.labels); token(node.keyword); token(node.colon); builder.indent(); // TODO(rnystrom): Allow inline cases? newline(); visitNodes(node.statements, between: oneOrTwoNewlines); builder.unindent(); } visitSwitchStatement(SwitchStatement node) { builder.nestExpression(); token(node.switchKeyword); space(); token(node.leftParenthesis); soloZeroSplit(); visit(node.expression); token(node.rightParenthesis); space(); token(node.leftBracket); builder.unnest(); builder.indent(); newline(); visitNodes(node.members, between: oneOrTwoNewlines, after: newline); token(node.rightBracket, before: () { builder.unindent(); newline(); }); } visitSymbolLiteral(SymbolLiteral node) { token(node.poundSign); var components = node.components; for (var component in components) { // The '.' separator if (component.previous.lexeme == '.') { token(component.previous); } token(component); } } visitThisExpression(ThisExpression node) { token(node.thisKeyword); } visitThrowExpression(ThrowExpression node) { token(node.throwKeyword); space(); visit(node.expression); } visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { visitMetadata(node.metadata); _simpleStatement(node, () { visit(node.variables); }); } visitTryStatement(TryStatement node) { token(node.tryKeyword); space(); visit(node.body); visitNodes(node.catchClauses, before: space, between: space); token(node.finallyKeyword, before: space, after: space); visit(node.finallyBlock); } visitTypeArgumentList(TypeArgumentList node) { _visitGenericList(node.leftBracket, node.rightBracket, node.arguments); } visitTypeName(TypeName node) { visit(node.name); visit(node.typeArguments); token(node.question); } visitTypeParameter(TypeParameter node) { visitParameterMetadata(node.metadata, () { visit(node.name); token(node.extendsKeyword, before: space, after: space); visit(node.bound); }); } visitTypeParameterList(TypeParameterList node) { _metadataRules.add(MetadataRule()); _visitGenericList(node.leftBracket, node.rightBracket, node.typeParameters); _metadataRules.removeLast(); } visitVariableDeclaration(VariableDeclaration node) { visit(node.name); if (node.initializer == null) return; // If there are multiple variables being declared, we want to nest the // initializers farther so they don't line up with the variables. Bad: // // var a = // aValue, // b = // bValue; // // Good: // // var a = // aValue, // b = // bValue; var hasMultipleVariables = (node.parent as VariableDeclarationList).variables.length > 1; _visitAssignment(node.equals, node.initializer, nest: hasMultipleVariables); } visitVariableDeclarationList(VariableDeclarationList node) { visitMetadata(node.metadata); // Allow but try to avoid splitting between the type and name. builder.startSpan(); modifier(node.lateKeyword); modifier(node.keyword); visit(node.type, after: soloSplit); builder.endSpan(); _startPossibleConstContext(node.keyword); // Use a single rule for all of the variables. If there are multiple // declarations, we will try to keep them all on one line. If that isn't // possible, we split after *every* declaration so that each is on its own // line. builder.startRule(); visitCommaSeparatedNodes(node.variables, between: split); builder.endRule(); _endPossibleConstContext(node.keyword); } visitVariableDeclarationStatement(VariableDeclarationStatement node) { _simpleStatement(node, () { visit(node.variables); }); } visitWhileStatement(WhileStatement node) { builder.nestExpression(); token(node.whileKeyword); space(); token(node.leftParenthesis); soloZeroSplit(); visit(node.condition); token(node.rightParenthesis); builder.unnest(); _visitLoopBody(node.body); } visitWithClause(WithClause node) { _visitCombinator(node.withKeyword, node.mixinTypes); } visitYieldStatement(YieldStatement node) { _simpleStatement(node, () { token(node.yieldKeyword); token(node.star); space(); visit(node.expression); }); } /// Visit a [node], and if not null, optionally preceded or followed by the /// specified functions. void visit(AstNode node, {void before(), void after()}) { if (node == null) return; if (before != null) before(); node.accept(this); if (after != null) after(); } /// Visit metadata annotations on declarations, and members. /// /// These always force the annotations to be on the previous line. void visitMetadata(NodeList<Annotation> metadata) { visitNodes(metadata, between: newline, after: newline); } /// Visit metadata annotations for a directive. /// /// Always force the annotations to be on a previous line. void _visitDirectiveMetadata(Directive directive) { // Preserve a blank line before the first directive since users (in // particular the test package) sometimes use that for metadata that // applies to the entire library and not the following directive itself. var isFirst = directive == (directive.parent as CompilationUnit).directives.first; visitNodes(directive.metadata, between: newline, after: isFirst ? oneOrTwoNewlines : newline); } /// Visits metadata annotations on parameters and type parameters. /// /// Unlike other annotations, these are allowed to stay on the same line as /// the parameter. void visitParameterMetadata( NodeList<Annotation> metadata, void visitParameter()) { if (metadata == null || metadata.isEmpty) { visitParameter(); return; } // Split before all of the annotations or none. builder.startLazyRule(_metadataRules.last); visitNodes(metadata, between: split, after: () { // Don't nest until right before the last metadata. Ensures we only // indent the parameter and not any of the metadata: // // function( // @LongAnnotation // @LongAnnotation // indentedParameter) {} builder.nestExpression(now: true); split(); }); visitParameter(); builder.unnest(); // Wrap the rule around the parameter too. If it splits, we want to force // the annotations to split as well. builder.endRule(); } /// Visits [node], which may be in an argument list controlled by [rule]. /// /// This is called directly by [ArgumentListVisitor] so that it can pass in /// the surrounding named argument rule. That way, this can ensure that a /// split between the name and argument forces the argument list to split /// too. void visitNamedArgument(NamedExpression node, [NamedRule rule]) { builder.nestExpression(); builder.startSpan(); visit(node.name); // Don't allow a split between a name and a collection. Instead, we want // the collection itself to split, or to split before the argument. if (node.expression is ListLiteral || node.expression is SetOrMapLiteral) { space(); } else { var split = soloSplit(); if (rule != null) split.imply(rule); } visit(node.expression); builder.endSpan(); builder.unnest(); } /// Visits the `=` and the following expression in any place where an `=` /// appears: /// /// * Assignment /// * Variable declaration /// * Constructor initialization /// /// If [nest] is true, an extra level of expression nesting is added after /// the "=". void _visitAssignment(Token equalsOperator, Expression rightHandSide, {bool nest = false}) { space(); token(equalsOperator); if (nest) builder.nestExpression(now: true); soloSplit(_assignmentCost(rightHandSide)); builder.startSpan(); visit(rightHandSide); builder.endSpan(); if (nest) builder.unnest(); } /// Visits a type parameter or type argument list. void _visitGenericList( Token leftBracket, Token rightBracket, List<AstNode> nodes) { var rule = TypeArgumentRule(); builder.startLazyRule(rule); builder.startSpan(); builder.nestExpression(); token(leftBracket); rule.beforeArgument(zeroSplit()); for (var node in nodes) { visit(node); // Write the trailing comma. if (node != nodes.last) { token(node.endToken.next); rule.beforeArgument(split()); } } token(rightBracket); builder.unnest(); builder.endSpan(); builder.endRule(); } /// Visits a sequence of labels before a statement or switch case. void _visitLabels(NodeList<Label> labels) { visitNodes(labels, between: newline, after: newline); } /// Visits the list of members in a class or mixin declaration. void _visitMembers(NodeList<ClassMember> members) { for (var member in members) { visit(member); if (member == members.last) { newline(); break; } // Add a blank line after non-empty block methods. var needsDouble = false; if (member is MethodDeclaration && member.body is BlockFunctionBody) { var body = member.body as BlockFunctionBody; needsDouble = body.block.statements.isNotEmpty; } if (needsDouble) { twoNewlines(); } else { // Variables and arrow-bodied members can be more tightly packed if // the user wants to group things together. oneOrTwoNewlines(); } } } /// Visits a top-level function or method declaration. /// /// The two AST node types are very similar but, alas, share no common /// interface type in analyzer, hence the dynamic typing. void _visitMemberDeclaration( /* FunctionDeclaration|MethodDeclaration */ node, /* FunctionExpression|MethodDeclaration */ function) { visitMetadata(node.metadata as NodeList<Annotation>); // Nest the signature in case we have to split between the return type and // name. builder.nestExpression(); builder.startSpan(); modifier(node.externalKeyword); if (node is MethodDeclaration) modifier(node.modifierKeyword); visit(node.returnType, after: soloSplit); modifier(node.propertyKeyword); if (node is MethodDeclaration) modifier(node.operatorKeyword); visit(node.name); builder.endSpan(); TypeParameterList typeParameters; if (node is FunctionDeclaration) { typeParameters = node.functionExpression.typeParameters; } else { typeParameters = (node as MethodDeclaration).typeParameters; } _visitBody(typeParameters, function.parameters, function.body, () { // If the body is a block, we need to exit nesting before we hit the body // indentation, but we do want to wrap it around the parameters. if (function.body is! ExpressionFunctionBody) builder.unnest(); }); // If it's an expression, we want to wrap the nesting around that so that // the body gets nested farther. if (function.body is ExpressionFunctionBody) builder.unnest(); } /// Visit the given function [parameters] followed by its [body], printing a /// space before it if it's not empty. /// /// If [beforeBody] is provided, it is invoked before the body is visited. void _visitBody(TypeParameterList typeParameters, FormalParameterList parameters, FunctionBody body, [beforeBody()]) { // If the body is "=>", add an extra level of indentation around the // parameters and a rule that spans the parameters and the "=>". This // ensures that if the parameters wrap, they wrap more deeply than the "=>" // does, as in: // // someFunction(parameter, // parameter, parameter) => // "the body"; // // Also, it ensures that if the parameters wrap, we split at the "=>" too // to avoid: // // someFunction(parameter, // parameter) => function( // argument); // // This is confusing because it looks like those two lines are at the same // level when they are actually unrelated. Splitting at "=>" forces: // // someFunction(parameter, // parameter) => // function( // argument); if (body is ExpressionFunctionBody) { builder.nestExpression(); // This rule is ended by visitExpressionFunctionBody(). builder.startLazyRule(Rule(Cost.arrow)); } _visitParameterSignature(typeParameters, parameters); if (beforeBody != null) beforeBody(); visit(body); if (body is ExpressionFunctionBody) builder.unnest(); } /// Visits the type parameters (if any) and formal parameters of a method /// declaration, function declaration, or generic function type. void _visitParameterSignature( TypeParameterList typeParameters, FormalParameterList parameters) { // Start the nesting for the parameters here, so they indent past the // type parameters too, if any. builder.nestExpression(); visit(typeParameters); if (parameters != null) { visitFormalParameterList(parameters, nestExpression: false); } builder.unnest(); } /// Visits the body statement of a `for`, `for in`, or `while` loop. void _visitLoopBody(Statement body) { if (body is EmptyStatement) { // No space before the ";". visit(body); } else if (body is Block) { space(); visit(body); } else { // Allow splitting in a statement-bodied loop even though it's against // the style guide. Since we can't fix the code itself to follow the // style guide, we should at least format it as well as we can. builder.indent(); builder.startRule(); builder.split(nest: false, space: true); visit(body); builder.endRule(); builder.unindent(); } } /// Visit a list of [nodes] if not null, optionally separated and/or preceded /// and followed by the given functions. void visitNodes(Iterable<AstNode> nodes, {before(), between(), after()}) { if (nodes == null || nodes.isEmpty) return; if (before != null) before(); visit(nodes.first); for (var node in nodes.skip(1)) { if (between != null) between(); visit(node); } if (after != null) after(); } /// Visit a comma-separated list of [nodes] if not null. void visitCommaSeparatedNodes(Iterable<AstNode> nodes, {between()}) { if (nodes == null || nodes.isEmpty) return; if (between == null) between = space; var first = true; for (var node in nodes) { if (!first) between(); first = false; visit(node); // The comma after the node. if (node.endToken.next.lexeme == ",") token(node.endToken.next); } } /// Visits the collection literal [node] whose body starts with [leftBracket], /// ends with [rightBracket] and contains [elements]. /// /// This is also used for argument lists with a trailing comma which are /// considered "collection-like". In that case, [node] is `null`. void _visitCollectionLiteral(TypedLiteral node, Token leftBracket, Iterable<AstNode> elements, Token rightBracket, [int cost]) { if (node != null) { // See if `const` should be removed. if (node.constKeyword != null && _constNesting > 0 && _formatter.fixes.contains(StyleFix.optionalConst)) { // Don't lose comments before the discarded keyword, if any. writePrecedingCommentsAndNewlines(node.constKeyword); } else { modifier(node.constKeyword); } visit(node.typeArguments); } // Don't allow splitting in an empty collection. if (_isEmptyCollection(elements, rightBracket)) { token(leftBracket); token(rightBracket); return; } // Force all of the surrounding collections to split. for (var i = 0; i < _collectionSplits.length; i++) { _collectionSplits[i] = true; } // Add this collection to the stack. _collectionSplits.add(false); _startLiteralBody(leftBracket); if (node != null) _startPossibleConstContext(node.constKeyword); // If a collection contains a line comment, we assume it's a big complex // blob of data with some documented structure. In that case, the user // probably broke the elements into lines deliberately, so preserve those. var preserveNewlines = _containsLineComments(elements, rightBracket); var rule; var lineRule; if (preserveNewlines) { // Newlines are significant, so we'll explicitly write those. Elements // on the same line all share an argument-list-like rule that allows // splitting between zero, one, or all of them. This is faster in long // lists than using individual splits after each element. lineRule = TypeArgumentRule(); builder.startLazyRule(lineRule); } else { // Newlines aren't significant, so use a hard rule to split the elements. // The parent chunk of the collection will handle the unsplit case, so // this only comes into play when the collection is split. rule = Rule.hard(); builder.startRule(rule); } for (var element in elements) { if (element != elements.first) { if (preserveNewlines) { // See if the next element is on the next line. if (_endLine(element.beginToken.previous) != _startLine(element.beginToken)) { oneOrTwoNewlines(); // Start a new rule for the new line. builder.endRule(); lineRule = TypeArgumentRule(); builder.startLazyRule(lineRule); } else { lineRule.beforeArgument(split()); } } else { builder.split(nest: false, space: true); } } visit(element); _writeCommaAfter(element); } builder.endRule(); // If there is a collection inside this one, it forces this one to split. var force = _collectionSplits.removeLast(); // If the collection has a trailing comma, the user must want it to split. if (elements.isNotEmpty && hasCommaAfter(elements.last)) force = true; if (node != null) _endPossibleConstContext(node.constKeyword); _endLiteralBody(rightBracket, ignoredRule: rule, forceSplit: force); } /// Writes [parameters], which is assumed to have a trailing comma after the /// last parameter. /// /// Parameter lists with trailing commas are formatted differently from /// regular parameter lists. They are treated more like collection literals. /// /// We don't reuse [_visitCollectionLiteral] here because there are enough /// weird differences around optional parameters that it's easiest just to /// give them their own method. void _visitTrailingCommaParameterList(FormalParameterList parameters) { // Can't have a trailing comma if there are no parameters. assert(parameters.parameters.isNotEmpty); _metadataRules.add(MetadataRule()); // Always split the parameters. builder.startRule(Rule.hard()); token(parameters.leftParenthesis); // Find the parameter immediately preceding the optional parameters (if // there are any). FormalParameter lastRequired; for (var i = 0; i < parameters.parameters.length; i++) { if (parameters.parameters[i] is DefaultFormalParameter) { if (i > 0) lastRequired = parameters.parameters[i - 1]; break; } } // If all parameters are optional, put the "[" or "{" right after "(". if (parameters.parameters.first is DefaultFormalParameter) { token(parameters.leftDelimiter); } // Process the parameters as a separate set of chunks. builder = builder.startBlock(null); for (var parameter in parameters.parameters) { visit(parameter); _writeCommaAfter(parameter); // If the optional parameters start after this one, put the delimiter // at the end of its line. if (parameter == lastRequired) { space(); token(parameters.leftDelimiter); lastRequired = null; } newline(); } // Put comments before the closing ")", "]", or "}" inside the block. var firstDelimiter = parameters.rightDelimiter ?? parameters.rightParenthesis; writePrecedingCommentsAndNewlines(firstDelimiter); builder = builder.endBlock(null, forceSplit: true); builder.endRule(); _metadataRules.removeLast(); // Now write the delimiter itself. _writeText(firstDelimiter.lexeme, firstDelimiter.offset); if (firstDelimiter != parameters.rightParenthesis) { token(parameters.rightParenthesis); } } /// Begins writing a formal parameter of any kind. void _beginFormalParameter(FormalParameter node) { builder.startLazyRule(Rule(Cost.parameterType)); builder.nestExpression(); modifier(node.requiredKeyword); modifier(node.covariantKeyword); } /// Ends writing a formal parameter of any kind. void _endFormalParameter(FormalParameter node) { builder.unnest(); builder.endRule(); } /// Writes a `Function` function type. /// /// Used also by a fix, so there may not be a [functionKeyword]. /// In that case [functionKeywordPosition] should be the source position /// used for the inserted "Function" text. void _visitGenericFunctionType( AstNode returnType, Token functionKeyword, int functionKeywordPosition, TypeParameterList typeParameters, FormalParameterList parameters) { builder.startLazyRule(); builder.nestExpression(); visit(returnType, after: split); if (functionKeyword != null) { token(functionKeyword); } else { _writeText("Function", functionKeywordPosition); } builder.unnest(); builder.endRule(); _visitParameterSignature(typeParameters, parameters); } /// Writes the header of a new-style typedef. /// /// Also used by a fix so there may not be an [equals] token. /// If [equals] is `null`, then [equalsPosition] must be a /// position to use for the inserted text "=". void _visitGenericTypeAliasHeader(Token typedefKeyword, AstNode name, AstNode typeParameters, Token equals, int equalsPosition) { token(typedefKeyword); space(); // If the typedef's type parameters split, split after the "=" too, // mainly to ensure the function's type parameters and parameters get // end up on successive lines with the same indentation. builder.startRule(); visit(name); visit(typeParameters); split(); if (equals != null) { token(equals); } else { _writeText("=", equalsPosition); } builder.endRule(); } /// Whether [node] is an argument in an argument list with a trailing comma. bool _isTrailingCommaArgument(Expression node) { var parent = node.parent; if (parent is NamedExpression) parent = parent.parent; return parent is ArgumentList && hasCommaAfter(parent.arguments.last); } /// Whether [node] is a spread of a collection literal. bool _isSpreadCollection(AstNode node) => _findSpreadCollectionBracket(node) != null; /// Whether the collection literal or block containing [nodes] and /// terminated by [rightBracket] is empty or not. /// /// An empty collection must have no elements or comments inside. Collections /// like that are treated specially because they cannot be split inside. bool _isEmptyCollection(Iterable<AstNode> nodes, Token rightBracket) => nodes.isEmpty && rightBracket.precedingComments == null; /// If [node] is a spread of a non-empty collection literal, then this /// returns the token for the opening bracket of the collection, as in: /// /// [ ...[a, list] ] /// // ^ /// /// Otherwise, returns `null`. Token _findSpreadCollectionBracket(AstNode node) { if (node is SpreadElement) { var expression = node.expression; if (expression is ListLiteral) { if (!_isEmptyCollection(expression.elements, expression.rightBracket)) { return expression.leftBracket; } } else if (expression is SetOrMapLiteral) { if (!_isEmptyCollection(expression.elements, expression.rightBracket)) { return expression.leftBracket; } } } return null; } /// Gets the cost to split at an assignment (or `:` in the case of a named /// default value) with the given [rightHandSide]. /// /// "Block-like" expressions (collections and cascades) bind a bit tighter /// because it looks better to have code like: /// /// var list = [ /// element, /// element, /// element /// ]; /// /// var builder = new SomeBuilderClass() /// ..method() /// ..method(); /// /// over: /// /// var list = /// [element, element, element]; /// /// var builder = /// new SomeBuilderClass()..method()..method(); int _assignmentCost(Expression rightHandSide) { if (rightHandSide is ListLiteral) return Cost.assignBlock; if (rightHandSide is SetOrMapLiteral) return Cost.assignBlock; if (rightHandSide is CascadeExpression) return Cost.assignBlock; return Cost.assign; } /// Returns `true` if the collection withs [elements] delimited by /// [rightBracket] contains any line comments. /// /// This only looks for comments at the element boundary. Comments within an /// element are ignored. bool _containsLineComments(Iterable<AstNode> elements, Token rightBracket) { hasLineCommentBefore(token) { var comment = token.precedingComments; for (; comment != null; comment = comment.next) { if (comment.type == TokenType.SINGLE_LINE_COMMENT) return true; } return false; } // Look before each element. for (var element in elements) { if (hasLineCommentBefore(element.beginToken)) return true; } // Look before the closing bracket. return hasLineCommentBefore(rightBracket); } /// Begins writing a literal body: a collection or block-bodied function /// expression. /// /// Writes the delimiter and then creates the [Rule] that handles splitting /// the body. void _startLiteralBody(Token leftBracket) { token(leftBracket); // See if this literal is associated with an argument list or if element // that wants to handle splitting and indenting it. If not, we'll use a // default rule. Rule rule; if (_blockRules.containsKey(leftBracket)) { rule = _blockRules[leftBracket]; } Chunk argumentChunk; if (_blockPreviousChunks.containsKey(leftBracket)) { argumentChunk = _blockPreviousChunks[leftBracket]; } // Create a rule for whether or not to split the block contents. builder.startRule(rule); // Process the collection contents as a separate set of chunks. builder = builder.startBlock(argumentChunk); } /// Ends the literal body started by a call to [_startLiteralBody()]. /// /// If [forceSplit] is `true`, forces the body to split. If [ignoredRule] is /// given, ignores that rule inside the body when determining if it should /// split. void _endLiteralBody(Token rightBracket, {Rule ignoredRule, bool forceSplit}) { if (forceSplit == null) forceSplit = false; // Put comments before the closing delimiter inside the block. var hasLeadingNewline = writePrecedingCommentsAndNewlines(rightBracket); builder = builder.endBlock(ignoredRule, forceSplit: hasLeadingNewline || forceSplit); builder.endRule(); // Now write the delimiter itself. _writeText(rightBracket.lexeme, rightBracket.offset); } /// Visits a list of configurations in an import or export directive. void _visitConfigurations(NodeList<Configuration> configurations) { if (configurations.isEmpty) return; builder.startRule(); for (var configuration in configurations) { split(); visit(configuration); } builder.endRule(); } /// Visits a "combinator". /// /// This is a [keyword] followed by a list of [nodes], with specific line /// splitting rules. As the name implies, this is used for [HideCombinator] /// and [ShowCombinator], but it also used for "with" and "implements" /// clauses in class declarations, which are formatted the same way. /// /// This assumes the current rule is a [CombinatorRule]. void _visitCombinator(Token keyword, Iterable<AstNode> nodes) { // Allow splitting before the keyword. var rule = builder.rule as CombinatorRule; rule.addCombinator(split()); builder.nestExpression(); token(keyword); rule.addName(split()); visitCommaSeparatedNodes(nodes, between: () => rule.addName(split())); builder.unnest(); } /// If [keyword] is `const`, begins a new constant context. void _startPossibleConstContext(Token keyword) { if (keyword != null && keyword.keyword == Keyword.CONST) { _constNesting++; } } /// If [keyword] is `const`, ends the current outermost constant context. void _endPossibleConstContext(Token keyword) { if (keyword != null && keyword.keyword == Keyword.CONST) { _constNesting--; } } /// Writes the simple statement or semicolon-delimited top-level declaration. /// /// Handles nesting if a line break occurs in the statement and writes the /// terminating semicolon. Invokes [body] which should write statement itself. void _simpleStatement(AstNode node, body()) { builder.nestExpression(); body(); // TODO(rnystrom): Can the analyzer move "semicolon" to some shared base // type? token((node as dynamic).semicolon); builder.unnest(); } /// Marks the block that starts with [token] as being controlled by /// [rule] and following [previousChunk]. /// /// When the block is visited, these will determine the indentation and /// splitting rule for the block. These are used for handling block-like /// expressions inside argument lists and spread collections inside if /// elements. void beforeBlock(Token token, Rule rule, [Chunk previousChunk]) { _blockRules[token] = rule; if (previousChunk != null) _blockPreviousChunks[token] = previousChunk; } /// Writes the beginning of a brace-delimited body and handles indenting and /// starting the rule used to split the contents. void _beginBody(Token leftBracket, {bool space = false}) { token(leftBracket); // Indent the body. builder.indent(); // Split after the bracket. builder.startRule(); builder.split(isDouble: false, nest: false, space: space); } /// Finishes the body started by a call to [_beginBody]. void _endBody(Token rightBracket, {bool space = false}) { token(rightBracket, before: () { // Split before the closing bracket character. builder.unindent(); builder.split(nest: false, space: space); }); builder.endRule(); } /// Returns `true` if [node] is immediately contained within an anonymous /// [FunctionExpression]. bool _isInLambda(AstNode node) => node.parent is FunctionExpression && node.parent.parent is! FunctionDeclaration; /// Writes the string literal [string] to the output. /// /// Splits multiline strings into separate chunks so that the line splitter /// can handle them correctly. void _writeStringLiteral(Token string) { // Since we output the string literal manually, ensure any preceding // comments are written first. writePrecedingCommentsAndNewlines(string); // Split each line of a multiline string into separate chunks. var lines = string.lexeme.split(_formatter.lineEnding); var offset = string.offset; _writeText(lines.first, offset); offset += lines.first.length; for (var line in lines.skip(1)) { builder.writeWhitespace(Whitespace.newlineFlushLeft); offset++; _writeText(line, offset); offset += line.length; } } /// Write the comma token following [node], if there is one. void _writeCommaAfter(AstNode node) { token(_commaAfter(node)); } /// Whether there is a comma token immediately following [node]. bool hasCommaAfter(AstNode node) => _commaAfter(node) != null; /// The comma token immediately following [node] if there is one, or `null`. Token _commaAfter(AstNode node) { if (node.endToken.next.type == TokenType.COMMA) { return node.endToken.next; } // TODO(sdk#38990): endToken doesn't include the "?" on a nullable // function-typed formal, so check for that case and handle it. if (node.endToken.next.type == TokenType.QUESTION && node.endToken.next.next.type == TokenType.COMMA) { return node.endToken.next.next; } return null; } /// Emit the given [modifier] if it's non null, followed by non-breaking /// whitespace. void modifier(Token modifier) { token(modifier, after: space); } /// Emit a non-breaking space. void space() { builder.writeWhitespace(Whitespace.space); } /// Emit a single mandatory newline. void newline() { builder.writeWhitespace(Whitespace.newline); } /// Emit a two mandatory newlines. void twoNewlines() { builder.writeWhitespace(Whitespace.twoNewlines); } /// Allow either a single split or newline to be emitted before the next /// non-whitespace token based on whether a newline exists in the source /// between the last token and the next one. void splitOrNewline() { builder.writeWhitespace(Whitespace.splitOrNewline); } /// Allow either a single split or newline to be emitted before the next /// non-whitespace token based on whether a newline exists in the source /// between the last token and the next one. void splitOrTwoNewlines() { builder.writeWhitespace(Whitespace.splitOrTwoNewlines); } /// Allow either one or two newlines to be emitted before the next /// non-whitespace token based on whether more than one newline exists in the /// source between the last token and the next one. void oneOrTwoNewlines() { builder.writeWhitespace(Whitespace.oneOrTwoNewlines); } /// Writes a single space split owned by the current rule. /// /// Returns the chunk the split was applied to. Chunk split() => builder.split(space: true); /// Writes a zero-space split owned by the current rule. /// /// Returns the chunk the split was applied to. Chunk zeroSplit() => builder.split(); /// Writes a single space split with its own rule. Rule soloSplit([int cost]) { var rule = Rule(cost); builder.startRule(rule); split(); builder.endRule(); return rule; } /// Writes a zero-space split with its own rule. void soloZeroSplit() { builder.startRule(); builder.split(); builder.endRule(); } /// Emit [token], along with any comments and formatted whitespace that comes /// before it. /// /// Does nothing if [token] is `null`. If [before] is given, it will be /// executed before the token is outout. Likewise, [after] will be called /// after the token is output. void token(Token token, {before(), after()}) { if (token == null) return; writePrecedingCommentsAndNewlines(token); if (before != null) before(); _writeText(token.lexeme, token.offset); if (after != null) after(); } /// Writes all formatted whitespace and comments that appear before [token]. bool writePrecedingCommentsAndNewlines(Token token) { var comment = token.precedingComments; // For performance, avoid calculating newlines between tokens unless // actually needed. if (comment == null) { if (builder.needsToPreserveNewlines) { builder.preserveNewlines(_startLine(token) - _endLine(token.previous)); } return false; } var previousLine = _endLine(token.previous); var tokenLine = _startLine(token); // Edge case: The analyzer includes the "\n" in the script tag's lexeme, // which confuses some of these calculations. We don't want to allow a // blank line between the script tag and a following comment anyway, so // just override the script tag's line. if (token.previous.type == TokenType.SCRIPT_TAG) previousLine = tokenLine; var comments = <SourceComment>[]; while (comment != null) { var commentLine = _startLine(comment); // Don't preserve newlines at the top of the file. if (comment == token.precedingComments && token.previous.type == TokenType.EOF) { previousLine = commentLine; } var text = comment.lexeme.trim(); var linesBefore = commentLine - previousLine; var flushLeft = _startColumn(comment) == 1; if (text.startsWith("///") && !text.startsWith("////")) { // Line doc comments are always indented even if they were flush left. flushLeft = false; // Always add a blank line (if possible) before a doc comment block. if (comment == token.precedingComments) linesBefore = 2; } var sourceComment = SourceComment(text, linesBefore, isLineComment: comment.type == TokenType.SINGLE_LINE_COMMENT, flushLeft: flushLeft); // If this comment contains either of the selection endpoints, mark them // in the comment. var start = _getSelectionStartWithin(comment.offset, comment.length); if (start != null) sourceComment.startSelection(start); var end = _getSelectionEndWithin(comment.offset, comment.length); if (end != null) sourceComment.endSelection(end); comments.add(sourceComment); previousLine = _endLine(comment); comment = comment.next; } builder.writeComments(comments, tokenLine - previousLine, token.lexeme); // TODO(rnystrom): This is wrong. Consider: // // [/* inline comment */ // // line comment // element]; return comments.first.linesBefore > 0; } /// Write [text] to the current chunk, given that it starts at [offset] in /// the original source. /// /// Also outputs the selection endpoints if needed. void _writeText(String text, int offset) { builder.write(text); // If this text contains either of the selection endpoints, mark them in // the chunk. var start = _getSelectionStartWithin(offset, text.length); if (start != null) { builder.startSelectionFromEnd(text.length - start); } var end = _getSelectionEndWithin(offset, text.length); if (end != null) { builder.endSelectionFromEnd(text.length - end); } } /// Returns the number of characters past [offset] in the source where the /// selection start appears if it appears before `offset + length`. /// /// Returns `null` if the selection start has already been processed or is /// not within that range. int _getSelectionStartWithin(int offset, int length) { // If there is no selection, do nothing. if (_source.selectionStart == null) return null; // If we've already passed it, don't consider it again. if (_passedSelectionStart) return null; var start = _source.selectionStart - offset; // If it started in whitespace before this text, push it forward to the // beginning of the non-whitespace text. if (start < 0) start = 0; // If we haven't reached it yet, don't consider it. if (start >= length) return null; // We found it. _passedSelectionStart = true; return start; } /// Returns the number of characters past [offset] in the source where the /// selection endpoint appears if it appears before `offset + length`. /// /// Returns `null` if the selection endpoint has already been processed or is /// not within that range. int _getSelectionEndWithin(int offset, int length) { // If there is no selection, do nothing. if (_source.selectionLength == null) return null; // If we've already passed it, don't consider it again. if (_passedSelectionEnd) return null; var end = _findSelectionEnd() - offset; // If it started in whitespace before this text, push it forward to the // beginning of the non-whitespace text. if (end < 0) end = 0; // If we haven't reached it yet, don't consider it. if (end > length) return null; if (end == length && _findSelectionEnd() == _source.selectionStart) { return null; } // We found it. _passedSelectionEnd = true; return end; } /// Calculates the character offset in the source text of the end of the /// selection. /// /// Removes any trailing whitespace from the selection. int _findSelectionEnd() { if (_selectionEnd != null) return _selectionEnd; _selectionEnd = _source.selectionStart + _source.selectionLength; // If the selection bumps to the end of the source, pin it there. if (_selectionEnd == _source.text.length) return _selectionEnd; // Trim off any trailing whitespace. We want the selection to "rubberband" // around the selected non-whitespace tokens since the whitespace will // be munged by the formatter itself. while (_selectionEnd > _source.selectionStart) { // Stop if we hit anything other than space, tab, newline or carriage // return. var char = _source.text.codeUnitAt(_selectionEnd - 1); if (char != 0x20 && char != 0x09 && char != 0x0a && char != 0x0d) { break; } _selectionEnd--; } return _selectionEnd; } /// Gets the 1-based line number that the beginning of [token] lies on. int _startLine(Token token) => _lineInfo.getLocation(token.offset).lineNumber; /// Gets the 1-based line number that the end of [token] lies on. int _endLine(Token token) => _lineInfo.getLocation(token.end).lineNumber; /// Gets the 1-based column number that the beginning of [token] lies on. int _startColumn(Token token) => _lineInfo.getLocation(token.offset).columnNumber; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/io.dart
// 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 dart_style.src.io; import 'dart:io'; import 'package:path/path.dart' as p; import 'dart_formatter.dart'; import 'exceptions.dart'; import 'formatter_options.dart'; import 'source_code.dart'; /// Runs the formatter on every .dart file in [path] (and its subdirectories), /// and replaces them with their formatted output. /// /// Returns `true` if successful or `false` if an error occurred in any of the /// files. bool processDirectory(FormatterOptions options, Directory directory) { options.reporter.showDirectory(directory.path); var success = true; var shownHiddenPaths = Set<String>(); for (var entry in directory.listSync( recursive: true, followLinks: options.followLinks)) { var relative = p.relative(entry.path, from: directory.path); if (entry is Link) { options.reporter.showSkippedLink(relative); continue; } if (entry is! File || !entry.path.endsWith(".dart")) continue; // If the path is in a subdirectory starting with ".", ignore it. var parts = p.split(relative); var hiddenIndex; for (var i = 0; i < parts.length; i++) { if (parts[i].startsWith(".")) { hiddenIndex = i; break; } } if (hiddenIndex != null) { // Since we'll hide everything inside the directory starting with ".", // show the directory name once instead of once for each file. var hiddenPath = p.joinAll(parts.take(hiddenIndex + 1)); if (shownHiddenPaths.add(hiddenPath)) { options.reporter.showHiddenPath(hiddenPath); } continue; } if (!processFile(options, entry, label: relative)) success = false; } return success; } /// Runs the formatter on [file]. /// /// Returns `true` if successful or `false` if an error occurred. bool processFile(FormatterOptions options, File file, {String label}) { if (label == null) label = file.path; var formatter = DartFormatter( indent: options.indent, pageWidth: options.pageWidth, fixes: options.fixes); try { var source = SourceCode(file.readAsStringSync(), uri: file.path); options.reporter.beforeFile(file, label); var output = formatter.formatSource(source); options.reporter .afterFile(file, label, output, changed: source.text != output.text); return true; } on FormatterException catch (err) { var color = Platform.operatingSystem != "windows" && stdioType(stderr) == StdioType.terminal; stderr.writeln(err.message(color: color)); } on UnexpectedOutputException catch (err) { stderr.writeln('''Hit a bug in the formatter when formatting $label. $err Please report at github.com/dart-lang/dart_style/issues.'''); } catch (err, stack) { stderr.writeln('''Hit a bug in the formatter when formatting $label. Please report at github.com/dart-lang/dart_style/issues. $err $stack'''); } return false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/nesting_builder.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.nesting_builder; import 'nesting_level.dart'; import 'whitespace.dart'; /// Keeps track of block indentation and expression nesting while the source /// code is being visited and the chunks are being built. /// /// This class requires (and verifies) that indentation and nesting are /// stratified from each other. Expression nesting is always inside block /// indentation, which means it is an error to try to change the block /// indentation while any expression nesting is in effect. class NestingBuilder { /// The block indentation levels. /// /// This is tracked as a stack of numbers, each of which is the total number /// of spaces of block indentation. We only store the stack of previous /// levels as a convenience to the caller: it spares you from having to pass /// the unindent amount to [unindent()]. final List<int> _stack = [0]; /// When not `null`, the expression nesting after the next token is written. /// /// When the nesting is increased, we don't want it to take effect until /// after at least one token has been written. That ensures that comments /// appearing before the first token are correctly indented. For example, a /// binary operator expression increases the nesting before the first operand /// to ensure any splits within the left operand are handled correctly. If we /// changed the nesting level immediately, then code like: /// /// { /// // comment /// foo + bar; /// } /// /// would incorrectly get indented because the line comment adds a split which /// would take the nesting level of the binary operator into account even /// though we haven't written any of its tokens yet. /// /// Likewise, when nesting is decreased, we may want to defer that until /// we've written the next token to handle uncommon cases like: /// /// do // comment /// { /// ... /// } /// /// Here, if we discard the expression nesting before we reach the "{", then /// it won't get indented as it should. NestingLevel _pendingNesting; /// The current number of characters of block indentation. int get indentation => _stack.last; /// The current nesting, ignoring any pending nesting. NestingLevel get nesting => _nesting; NestingLevel _nesting = NestingLevel(); /// The current nesting, including any pending nesting. NestingLevel get currentNesting => _pendingNesting != null ? _pendingNesting : _nesting; /// Creates a new indentation level [spaces] deeper than the current one. /// /// If omitted, [spaces] defaults to [Indent.block]. void indent([int spaces]) { spaces ??= Indent.block; // Indentation should only change outside of nesting. assert(_pendingNesting == null); assert(_nesting.indent == 0); _stack.add(_stack.last + spaces); } /// Discards the most recent indentation level. void unindent() { // Indentation should only change outside of nesting. assert(_pendingNesting == null); assert(_nesting.indent == 0); // If this fails, an unindent() call did not have a preceding indent() call. assert(_stack.isNotEmpty); _stack.removeLast(); } /// Begins a new expression nesting level [indent] deeper than the current /// one if it splits. /// /// Expressions that are more nested will get increased indentation when split /// if the previous line has a lower level of nesting. /// /// If [indent] is omitted, defaults to [Indent.expression]. void nest([int indent]) { if (indent == null) indent = Indent.expression; if (_pendingNesting != null) { _pendingNesting = _pendingNesting.nest(indent); } else { _pendingNesting = _nesting.nest(indent); } } /// Discards the most recent level of expression nesting. void unnest() { if (_pendingNesting != null) { _pendingNesting = _pendingNesting.parent; } else { _pendingNesting = _nesting.parent; } // If this fails, an unnest() call did not have a preceding nest() call. assert(_pendingNesting != null); } /// Applies any pending nesting now that we are ready for it to take effect. void commitNesting() { if (_pendingNesting == null) return; _nesting = _pendingNesting; _pendingNesting = null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/style_fix.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Enum-like class for the different syntactic fixes that can be applied while /// formatting. class StyleFix { static const docComments = StyleFix._( "doc-comments", 'Use triple slash for documentation comments.'); static const functionTypedefs = StyleFix._( "function-typedefs", 'Use new syntax for function type typedefs.'); static const namedDefaultSeparator = StyleFix._("named-default-separator", 'Use "=" as the separator before named parameter default values.'); static const optionalConst = StyleFix._( "optional-const", 'Remove "const" keyword inside constant context.'); static const optionalNew = StyleFix._("optional-new", 'Remove "new" keyword.'); static const all = [ docComments, functionTypedefs, namedDefaultSeparator, optionalConst, optionalNew ]; final String name; final String description; const StyleFix._(this.name, this.description); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/line_splitting/rule_set.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.line_splitting.rule_set; import '../rule/rule.dart'; /// An optimized data structure for storing a set of values for some rules. /// /// This conceptually behaves roughly like a `Map<Rule, int>`, but is much /// faster since it avoids hashing. Instead, it assumes the line splitter has /// provided an ordered list of [Rule]s and that each rule's [index] field has /// been set to point to the rule in the list. /// /// Internally, this then just stores the values in a sparse list whose indices /// are the indices of the rules. class RuleSet { List<int> _values; RuleSet(int numRules) : this._(List(numRules)); RuleSet._(this._values); /// Returns `true` of [rule] is bound in this set. bool contains(Rule rule) { // Treat hardened rules as implicitly bound. if (rule.isHardened) return true; return _values[rule.index] != null; } /// Gets the bound value for [rule] or [Rule.unsplit] if it is not bound. int getValue(Rule rule) { // Hardened rules are implicitly bound. if (rule.isHardened) return rule.fullySplitValue; var value = _values[rule.index]; if (value != null) return value; return Rule.unsplit; } /// Invokes [callback] for each rule in [rules] with the rule's value, which /// will be `null` if it is not bound. void forEach(List<Rule> rules, callback(Rule rule, int value)) { var i = 0; for (var rule in rules) { var value = _values[i]; if (value != null) callback(rule, value); i++; } } /// Creates a new [RuleSet] with the same bound rule values as this one. RuleSet clone() => RuleSet._(_values.toList(growable: false)); /// Binds [rule] to [value] then checks to see if that violates any /// constraints. /// /// Returns `true` if all constraints between the bound rules are valid. Even /// if not, this still modifies the [RuleSet]. /// /// If an unbound rule gets constrained to `-1` (meaning it must split, but /// can split any way it wants), invokes [onSplitRule] with it. bool tryBind(List<Rule> rules, Rule rule, int value, onSplitRule(Rule rule)) { assert(!rule.isHardened); _values[rule.index] = value; // Test this rule against the other rules being bound. for (var other in rule.constrainedRules) { var otherValue; // Hardened rules are implicitly bound. if (other.isHardened) { otherValue = other.fullySplitValue; } else { otherValue = _values[other.index]; } var constraint = rule.constrain(value, other); if (otherValue == null) { // The other rule is unbound, so see if we can constrain it eagerly to // a value now. if (constraint == Rule.mustSplit) { // If we know the rule has to split and there's only one way it can, // just bind that. if (other.numValues == 2) { if (!tryBind(rules, other, 1, onSplitRule)) return false; } else { onSplitRule(other); } } else if (constraint != null) { // Bind the other rule to its value and recursively propagate its // constraints. if (!tryBind(rules, other, constraint, onSplitRule)) return false; } } else { // It's already bound, so see if the new rule's constraint disallows // that value. if (constraint == Rule.mustSplit) { if (otherValue == Rule.unsplit) return false; } else if (constraint != null) { if (otherValue != constraint) return false; } // See if the other rule's constraint allows us to use this value. constraint = other.constrain(otherValue, rule); if (constraint == Rule.mustSplit) { if (value == Rule.unsplit) return false; } else if (constraint != null) { if (value != constraint) return false; } } } return true; } String toString() => _values.map((value) => value == null ? "?" : value).join(" "); } /// For each chunk, this tracks if it has been split and, if so, what the /// chosen column is for the following line. /// /// Internally, this uses a list where each element corresponds to the column /// of the chunk at that index in the chunk list, or `null` if that chunk did /// not split. This had about a 10% perf improvement over using a [Set] of /// splits. class SplitSet { List<int> _columns; /// The cost of the solution that led to these splits. int get cost => _cost; int _cost; /// Creates a new empty split set for a line with [numChunks]. SplitSet(int numChunks) : _columns = List(numChunks - 1); /// Marks the line after chunk [index] as starting at [column]. void add(int index, int column) { _columns[index] = column; } /// Returns `true` if the chunk at [splitIndex] should be split. bool shouldSplitAt(int index) => index < _columns.length && _columns[index] != null; /// Gets the zero-based starting column for the chunk at [index]. int getColumn(int index) => _columns[index]; /// Sets the resulting [cost] for the splits. /// /// This can only be called once. void setCost(int cost) { assert(_cost == null); _cost = cost; } String toString() { var result = []; for (var i = 0; i < _columns.length; i++) { if (_columns[i] != null) { result.add("$i:${_columns[i]}"); } } return result.join(" "); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/line_splitting/solve_state.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.line_splitting.solve_state; import '../debug.dart' as debug; import '../nesting_level.dart'; import '../rule/rule.dart'; import '../whitespace.dart'; import 'line_splitter.dart'; import 'rule_set.dart'; /// A possibly incomplete solution in the line splitting search space. /// /// A single [SolveState] binds some subset of the rules to values while /// leaving the rest unbound. If every rule is bound, the solve state describes /// a complete solution to the line splitting problem. Even if rules are /// unbound, a state can also usually be used as a solution by treating all /// unbound rules as unsplit. (The usually is because a state that constrains /// an unbound rule to split can't be used with that rule unsplit.) /// /// From a given solve state, we can explore the search tree to more refined /// solve states by producing new ones that add more bound rules to the current /// state. class SolveState { final LineSplitter _splitter; final RuleSet _ruleValues; /// The set of [Rule]s that are bound by [_ruleValues]. /// /// Cached by [_ensureConstraints] for use by [_ensureUnboundConstraints]. Set<Rule> _boundRules; /// The set of [Rule]s that are not bound by [_ruleValues]. /// /// Cached by [_ensureConstraints] for use by [_ensureUnboundConstraints]. Set<Rule> _unboundRules; /// The unbound rules in this state that can be bound to produce new more /// refined states. /// /// Keeping this set small is the key to make the entire line splitter /// perform well. If we consider too many rules at each state, our /// exploration of the solution space is too branchy and we waste time on /// dead end solutions. /// /// Here is the key insight. The line splitter treats any unbound rule as /// being unsplit. This means refining a solution always means taking a rule /// that is unsplit and making it split. That monotonically increases the /// cost, but may help fit the solution inside the page. /// /// We want to keep the cost low, so the only reason to consider making a /// rule split is if it reduces an overflowing line. It's also the case that /// splitting an earlier rule will often reshuffle the rest of the line. /// /// Taking that into account, the only rules we consider binding to extend a /// solve state are *unbound rules inside the first line that is overflowing*. /// Even if a line has dozens of rules, this generally keeps the branching /// down to a few. It also means rules inside lines that already fit are /// never touched. /// /// There is one other set of rules that go in here. Sometimes a bound rule /// in the solve state constrains some other unbound rule to split. In that /// case, we also consider that active so we know to not leave it at zero. final _liveRules = Set<Rule>(); /// The set of splits chosen for this state. SplitSet get splits => _splits; SplitSet _splits; /// The number of characters that do not fit inside the page with this set of /// splits. int get overflowChars => _overflowChars; int _overflowChars; /// Whether we can treat this state as a complete solution by leaving its /// unbound rules unsplit. /// /// This is generally true but will be false if the state contains any /// unbound rules that are constrained to not be zero by other bound rules. /// This avoids picking a solution that leaves those rules at zero when they /// aren't allowed to be. bool _isComplete = true; /// The constraints the bound rules in this state have on the remaining /// unbound rules. Map<Rule, int> _constraints; /// The unbound rule values that are disallowed because they would place /// invalid constraints on the currently bound values. /// /// For example, say rule A is bound to 1 and B is unbound. If B has value /// 1, it constrains A to be 1. Likewise, if B is 2, it constrains A to be /// 2 as well. Since we already know A is 1, that means we know B cannot be /// bound to value 2. This means B is more limited in this state than it /// might be in another state that binds A to a different value. /// /// It's important to track this, because we can't allow to states to overlap /// if one permits more values for some unbound rule than the other does. Map<Rule, Set<int>> _unboundConstraints; /// The bound rules that appear inside lines also containing unbound rules. /// /// By appearing in the same line, it means these bound rules may affect the /// results of binding those unbound rules. This is used to tell if two /// states may diverge by binding unbound rules or not. Set<Rule> _boundRulesInUnboundLines; SolveState(this._splitter, this._ruleValues) { _calculateSplits(); _calculateCost(); } /// Gets the value to use for [rule], either the bound value or /// [Rule.unsplit] if it isn't bound. int getValue(Rule rule) => _ruleValues.getValue(rule); /// Returns `true` if this state is a better solution to use as the final /// result than [other]. bool isBetterThan(SolveState other) { // If this state contains an unbound rule that we know can't be left // unsplit, we can't pick this as a solution. if (!_isComplete) return false; // Anything is better than nothing. if (other == null) return true; // Prefer the solution that fits the most in the page. if (overflowChars != other.overflowChars) { return overflowChars < other.overflowChars; } // Otherwise, prefer the best cost. return splits.cost < other.splits.cost; } /// Determines if this state "overlaps" [other]. /// /// Two states overlap if they currently have the same score and we can tell /// for certain that they won't diverge as their unbound rules are bound. If /// that's the case, then whichever state is better now (based on their /// currently bound rule values) is the one that will always win, regardless /// of how they get expanded. /// /// In other words, their entire expanded solution trees also overlap. In /// that case, there's no point in expanding both, so we can just pick the /// winner now and discard the other. /// /// For this to be true, we need to prove that binding an unbound rule won't /// affect one state differently from the other. We have to show that they /// are parallel. /// /// Two things could cause this *not* to be the case. /// /// 1. If one state's bound rules place different constraints on the unbound /// rules than the other. /// /// 2. If one state's different bound rules are in the same line as an /// unbound rule. That affects the indentation and length of the line, /// which affects the context where the unbound rule is being chosen. /// /// If neither of these is the case, the states overlap. Returns `<0` if this /// state is better, or `>0` if [other] wins. If the states do not overlap, /// returns `0`. int compareOverlap(SolveState other) { if (!_isOverlapping(other)) return 0; // They do overlap, so see which one wins. for (var rule in _splitter.rules) { var value = _ruleValues.getValue(rule); var otherValue = other._ruleValues.getValue(rule); if (value != otherValue) return value.compareTo(otherValue); } // The way SolveStates are expanded should guarantee that we never generate // the exact same state twice. Getting here implies that that failed. throw "unreachable"; } /// Enqueues more solve states to consider based on this one. /// /// For each unbound rule in this state that occurred in the first long line, /// enqueue solve states that bind that rule to each value it can have and /// bind all previous rules to zero. (In other words, try all subsolutions /// where that rule becomes the first new rule to split at.) void expand() { var unsplitRules = _ruleValues.clone(); // Walk down the rules looking for unbound ones to try. var triedRules = 0; for (var rule in _splitter.rules) { if (_liveRules.contains(rule)) { // We found one worth trying, so try all of its values. for (var value = 1; value < rule.numValues; value++) { var boundRules = unsplitRules.clone(); List<Rule> mustSplitRules; var valid = boundRules.tryBind(_splitter.rules, rule, value, (rule) { if (mustSplitRules == null) mustSplitRules = []; mustSplitRules.add(rule); }); // Make sure we don't violate the constraints of the bound rules. if (!valid) continue; var state = SolveState(_splitter, boundRules); // If some unbound rules are constrained to split, remember that. if (mustSplitRules != null) { state._isComplete = false; state._liveRules.addAll(mustSplitRules); } _splitter.enqueue(state); } // Stop once we've tried all of the ones we can. if (++triedRules == _liveRules.length) break; } // Fill in previous unbound rules with zero. if (!_ruleValues.contains(rule)) { // Pass a dummy callback because zero will never fail. (If it would // have, that rule would already be bound to some other value.) if (!unsplitRules.tryBind(_splitter.rules, rule, 0, (_) {})) { break; } } } } /// Returns `true` if [other] overlaps this state. bool _isOverlapping(SolveState other) { // Lines that contain both bound and unbound rules must have the same // bound values. _ensureBoundRulesInUnboundLines(); other._ensureBoundRulesInUnboundLines(); if (_boundRulesInUnboundLines.length != other._boundRulesInUnboundLines.length) { return false; } for (var rule in _boundRulesInUnboundLines) { if (!other._boundRulesInUnboundLines.contains(rule)) return false; if (_ruleValues.getValue(rule) != other._ruleValues.getValue(rule)) { return false; } } _ensureConstraints(); other._ensureConstraints(); if (_constraints.length != other._constraints.length) return false; for (var rule in _constraints.keys) { if (_constraints[rule] != other._constraints[rule]) return false; } _ensureUnboundConstraints(); other._ensureUnboundConstraints(); if (_unboundConstraints.length != other._unboundConstraints.length) { return false; } for (var rule in _unboundConstraints.keys) { var disallowed = _unboundConstraints[rule]; var otherDisallowed = other._unboundConstraints[rule]; if (disallowed.length != otherDisallowed.length) return false; for (var value in disallowed) { if (!otherDisallowed.contains(value)) return false; } } return true; } /// Calculates the [SplitSet] for this solve state, assuming any unbound /// rules are set to zero. void _calculateSplits() { // Figure out which expression nesting levels got split and need to be // assigned columns. var usedNestingLevels = Set<NestingLevel>(); for (var i = 0; i < _splitter.chunks.length - 1; i++) { var chunk = _splitter.chunks[i]; if (chunk.rule.isSplit(getValue(chunk.rule), chunk)) { usedNestingLevels.add(chunk.nesting); chunk.nesting.clearTotalUsedIndent(); } } for (var nesting in usedNestingLevels) { nesting.refreshTotalUsedIndent(usedNestingLevels); } _splits = SplitSet(_splitter.chunks.length); for (var i = 0; i < _splitter.chunks.length - 1; i++) { var chunk = _splitter.chunks[i]; if (chunk.rule.isSplit(getValue(chunk.rule), chunk)) { var indent = 0; if (!chunk.flushLeftAfter) { // Add in the chunk's indent. indent = _splitter.blockIndentation + chunk.indent; // And any expression nesting. indent += chunk.nesting.totalUsedIndent; if (chunk.indentBlock(getValue)) indent += Indent.expression; } _splits.add(i, indent); } } } /// Evaluates the cost (i.e. the relative "badness") of splitting the line /// into [lines] physical lines based on the current set of rules. void _calculateCost() { assert(_splits != null); // Calculate the length of each line and apply the cost of any spans that // get split. var cost = 0; _overflowChars = 0; var length = _splitter.firstLineIndent; // The unbound rules in use by the current line. This will be null after // the first long line has completed. var foundOverflowRules = false; var start = 0; endLine(int end) { // Track lines that went over the length. It is only rules contained in // long lines that we may want to split. if (length > _splitter.writer.pageWidth) { _overflowChars += length - _splitter.writer.pageWidth; // Only try rules that are in the first long line, since we know at // least one of them *will* be split. if (!foundOverflowRules) { for (var i = start; i < end; i++) { if (_addLiveRules(_splitter.chunks[i].rule)) { foundOverflowRules = true; } } } } start = end; } // The set of spans that contain chunks that ended up splitting. We store // these in a set so a span's cost doesn't get double-counted if more than // one split occurs in it. var splitSpans = Set(); // The nesting level of the chunk that ended the previous line. var previousNesting; for (var i = 0; i < _splitter.chunks.length; i++) { var chunk = _splitter.chunks[i]; length += chunk.text.length; // Ignore the split after the last chunk. if (i == _splitter.chunks.length - 1) break; if (_splits.shouldSplitAt(i)) { endLine(i); splitSpans.addAll(chunk.spans); // Include the cost of the nested block. if (chunk.isBlock) { cost += _splitter.writer.formatBlock(chunk, _splits.getColumn(i)).cost; } // Do not allow sequential lines to have the same indentation but for // different reasons. In other words, don't allow different expressions // to claim the same nesting level on subsequent lines. // // A contrived example would be: // // function(inner( // argument), second( // another); // // For the most part, we prevent this by the constraints on splits. // For example, the above can't happen because the split before // "argument", forces the split before "second". // // But there are a couple of squirrely cases where it's hard to prevent // by construction. Instead, this outlaws it by penalizing it very // heavily if it happens to get this far. if (previousNesting != null && chunk.nesting.totalUsedIndent != 0 && chunk.nesting.totalUsedIndent == previousNesting.totalUsedIndent && !identical(chunk.nesting, previousNesting)) { _overflowChars += 10000; } previousNesting = chunk.nesting; // Start the new line. length = _splits.getColumn(i); } else { if (chunk.spaceWhenUnsplit) length++; // Include the nested block inline, if any. length += chunk.unsplitBlockLength; } } // Add the costs for the rules that have any splits. _ruleValues.forEach(_splitter.rules, (rule, value) { if (value != Rule.unsplit) cost += rule.cost; }); // Add the costs for the spans containing splits. for (var span in splitSpans) { cost += span.cost; } // Finish the last line. endLine(_splitter.chunks.length); _splits.setCost(cost); } /// Adds [rule] and all of the rules it constrains to the set of [_liveRules]. /// /// Only does this if [rule] is a valid soft rule. Returns `true` if any new /// live rules were added. bool _addLiveRules(Rule rule) { if (rule == null) return false; var added = false; for (var constrained in rule.allConstrainedRules) { if (_ruleValues.contains(constrained)) continue; _liveRules.add(constrained); added = true; } return added; } /// Lazily initializes the [_boundInUnboundLines], which is needed to compare /// two states for overlap. /// /// We do this lazily because the calculation is a bit slow, and is only /// needed when we have two states with the same score. void _ensureBoundRulesInUnboundLines() { if (_boundRulesInUnboundLines != null) return; _boundRulesInUnboundLines = Set<Rule>(); var boundInLine = Set<Rule>(); var hasUnbound = false; for (var i = 0; i < _splitter.chunks.length - 1; i++) { if (splits.shouldSplitAt(i)) { if (hasUnbound) _boundRulesInUnboundLines.addAll(boundInLine); boundInLine.clear(); hasUnbound = false; } var rule = _splitter.chunks[i].rule; if (rule != null) { if (_ruleValues.contains(rule)) { boundInLine.add(rule); } else { hasUnbound = true; } } } if (hasUnbound) _boundRulesInUnboundLines.addAll(boundInLine); } /// Lazily initializes the [_constraints], which is needed to compare two /// states for overlap. /// /// We do this lazily because the calculation is a bit slow, and is only /// needed when we have two states with the same score. void _ensureConstraints() { if (_constraints != null) return; _unboundRules = Set(); _boundRules = Set(); for (var rule in _splitter.rules) { if (_ruleValues.contains(rule)) { _boundRules.add(rule); } else { _unboundRules.add(rule); } } _constraints = {}; for (var bound in _boundRules) { for (var unbound in bound.constrainedRules) { if (!_unboundRules.contains(unbound)) continue; var value = _ruleValues.getValue(bound); var constraint = bound.constrain(value, unbound); if (constraint != null) { _constraints[unbound] = constraint; } } } } /// Lazily initializes the [_unboundConstraints], which is needed to compare /// two states for overlap. /// /// We do this lazily because the calculation is a bit slow, and is only /// needed when we have two states with the same score. void _ensureUnboundConstraints() { if (_unboundConstraints != null) return; // _ensureConstraints should be called first which initializes these. assert(_boundRules != null); assert(_unboundRules != null); _unboundConstraints = {}; for (var unbound in _unboundRules) { Set<int> disallowedValues; for (var bound in unbound.constrainedRules) { if (!_boundRules.contains(bound)) continue; var boundValue = _ruleValues.getValue(bound); for (var value = 0; value < unbound.numValues; value++) { var constraint = unbound.constrain(value, bound); // If the unbound rule doesn't place any constraint on this bound // rule, we're fine. if (constraint == null) continue; // If the bound rule's value already meets the constraint it applies, // we don't need to track it. This way, two states that have the // same bound value, one of which has a satisfied constraint, are // still allowed to overlap. if (constraint == boundValue) continue; if (constraint == Rule.mustSplit && boundValue != Rule.unsplit) { continue; } if (disallowedValues == null) { disallowedValues = Set<int>(); _unboundConstraints[unbound] = disallowedValues; } disallowedValues.add(value); } } } } String toString() { var buffer = StringBuffer(); buffer.writeAll(_splitter.rules.map((rule) { var valueLength = "${rule.fullySplitValue}".length; var value = "?"; if (_ruleValues.contains(rule)) { value = "${_ruleValues.getValue(rule)}"; } value = value.padLeft(valueLength); if (_liveRules.contains(rule)) { value = debug.bold(value); } else { value = debug.gray(value); } return value; }), " "); buffer.write(" \$${splits.cost}"); if (overflowChars > 0) buffer.write(" (${overflowChars} over)"); if (!_isComplete) buffer.write(" (incomplete)"); if (splits == null) buffer.write(" invalid"); return buffer.toString(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/line_splitting/solve_state_queue.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.line_splitting.solve_state_queue; import 'line_splitter.dart'; import 'solve_state.dart'; /// A priority queue of [SolveStates] to consider while line splitting. /// /// This is based on the [HeapPriorityQueue] class from the "collection" /// package, but is modified to handle the "overlap" logic that allows one /// [SolveState] to supercede another. /// /// States are stored internally in a heap ordered by cost, the number of /// overflow characters. When a new state is added to the heap, it will be /// discarded, or a previously enqueued one will be discarded, if two overlap. class SolveStateQueue { /// Initial capacity of a queue when created, or when added to after a [clear]. /// Number can be any positive value. Picking a size that gives a whole /// number of "tree levels" in the heap is only done for aesthetic reasons. static const int _INITIAL_CAPACITY = 7; LineSplitter _splitter; /// List implementation of a heap. List<SolveState> _queue = List<SolveState>(_INITIAL_CAPACITY); /// Number of elements in queue. /// The heap is implemented in the first [_length] entries of [_queue]. int _length = 0; bool get isNotEmpty => _length != 0; void bindSplitter(LineSplitter splitter) { // Only do this once. assert(_splitter == null); _splitter = splitter; } /// Add [state] to the queue. /// /// Grows the capacity if the backing list is full. void add(SolveState state) { if (_tryOverlap(state)) return; if (_length == _queue.length) { var newCapacity = _queue.length * 2 + 1; if (newCapacity < _INITIAL_CAPACITY) newCapacity = _INITIAL_CAPACITY; var newQueue = List<SolveState>(newCapacity); newQueue.setRange(0, _length, _queue); _queue = newQueue; } _bubbleUp(state, _length++); } SolveState removeFirst() { assert(_length > 0); // Remove the highest priority state. var result = _queue[0]; _length--; // Fill the gap with the one at the end of the list and re-heapify. if (_length > 0) { var last = _queue[_length]; _queue[_length] = null; _bubbleDown(last, 0); } return result; } /// Orders this state relative to [other]. /// /// This is a best-first ordering that prefers cheaper states even if they /// overflow because this ensures it finds the best solution first as soon as /// it finds one that fits in the page so it can early out. int _compare(SolveState a, SolveState b) { // TODO(rnystrom): It may be worth sorting by the estimated lowest number // of overflow characters first. That doesn't help in cases where there is // a solution that fits, but may help in corner cases where there is no // fitting solution. var comparison = _compareScore(a, b); if (comparison != 0) return comparison; return _compareRules(a, b); } /// Compares the overflow and cost of [a] to [b]. int _compareScore(SolveState a, SolveState b) { if (a.splits.cost != b.splits.cost) { return a.splits.cost.compareTo(b.splits.cost); } return a.overflowChars.compareTo(b.overflowChars); } /// Distinguish states based on the rule values just so that states with the /// same cost range but different rule values don't get considered identical /// and inadvertantly merged. int _compareRules(SolveState a, SolveState b) { for (var rule in _splitter.rules) { var aValue = a.getValue(rule); var bValue = b.getValue(rule); if (aValue != bValue) return aValue.compareTo(bValue); } // The way SolveStates are expanded should guarantee that we never generate // the exact same state twice. Getting here implies that that failed. throw "unreachable"; } /// Determines if any already enqueued state overlaps [state]. /// /// If so, chooses the best and discards the other. Returns `true` in this /// case. Otherwise, returns `false`. bool _tryOverlap(SolveState state) { if (_length == 0) return false; // Count positions from one instead of zero. This gives the numbers some // nice properties. For example, all right children are odd, their left // sibling is even, and the parent is found by shifting right by one. // Valid range for position is [1.._length], inclusive. var position = 1; // Pre-order depth first search, omit child nodes if the current node has // lower priority than [object], because all nodes lower in the heap will // also have lower priority. do { var index = position - 1; var enqueued = _queue[index]; var comparison = _compareScore(enqueued, state); if (comparison == 0) { var overlap = enqueued.compareOverlap(state); if (overlap < 0) { // The old state is better, so just discard the new one. return true; } else if (overlap > 0) { // The new state is better than the enqueued one, so replace it. _queue[index] = state; return true; } else { // We can't merge them, so sort by their bound rule values. comparison = _compareRules(enqueued, state); } } if (comparison < 0) { // Element may be in subtree. Continue with the left child, if any. var leftChildPosition = position * 2; if (leftChildPosition <= _length) { position = leftChildPosition; continue; } } // Find the next right sibling or right ancestor sibling. do { while (position.isOdd) { // While position is a right child, go to the parent. position >>= 1; } // Then go to the right sibling of the left child. position += 1; } while (position > _length); // Happens if last element is a left child. } while (position != 1); // At root again. Happens for right-most element. return false; } /// Place [element] in heap at [index] or above. /// /// Put element into the empty cell at `index`. While the `element` has /// higher priority than the parent, swap it with the parent. void _bubbleUp(SolveState element, int index) { while (index > 0) { var parentIndex = (index - 1) ~/ 2; var parent = _queue[parentIndex]; if (_compare(element, parent) > 0) break; _queue[index] = parent; index = parentIndex; } _queue[index] = element; } /// Place [element] in heap at [index] or above. /// /// Put element into the empty cell at `index`. While the `element` has lower /// priority than either child, swap it with the highest priority child. void _bubbleDown(SolveState element, int index) { var rightChildIndex = index * 2 + 2; while (rightChildIndex < _length) { var leftChildIndex = rightChildIndex - 1; var leftChild = _queue[leftChildIndex]; var rightChild = _queue[rightChildIndex]; var comparison = _compare(leftChild, rightChild); var minChildIndex; var minChild; if (comparison < 0) { minChild = leftChild; minChildIndex = leftChildIndex; } else { minChild = rightChild; minChildIndex = rightChildIndex; } comparison = _compare(element, minChild); if (comparison <= 0) { _queue[index] = element; return; } _queue[index] = minChild; index = minChildIndex; rightChildIndex = index * 2 + 2; } var leftChildIndex = rightChildIndex - 1; if (leftChildIndex < _length) { var child = _queue[leftChildIndex]; var comparison = _compare(element, child); if (comparison > 0) { _queue[index] = child; index = leftChildIndex; } } _queue[index] = element; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/line_splitting/line_splitter.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.line_splitting.line_splitter; import '../chunk.dart'; import '../debug.dart' as debug; import '../line_writer.dart'; import '../rule/rule.dart'; import 'rule_set.dart'; import 'solve_state.dart'; import 'solve_state_queue.dart'; /// To ensure the solver doesn't go totally pathological on giant code, we cap /// it at a fixed number of attempts. /// /// If the optimal solution isn't found after this many tries, it just uses the /// best it found so far. const _maxAttempts = 5000; /// Takes a set of chunks and determines the best values for its rules in order /// to fit it inside the page boundary. /// /// This problem is exponential in the number of rules and a single expression /// in Dart can be quite large, so it isn't feasible to brute force this. For /// example: /// /// outer( /// fn(1 + 2, 3 + 4, 5 + 6, 7 + 8), /// fn(1 + 2, 3 + 4, 5 + 6, 7 + 8), /// fn(1 + 2, 3 + 4, 5 + 6, 7 + 8), /// fn(1 + 2, 3 + 4, 5 + 6, 7 + 8)); /// /// There are 509,607,936 ways this can be split. /// /// The problem is even harder because we may not be able to easily tell if a /// given solution is the best one. It's possible that there is *no* solution /// that fits in the page (due to long strings or identifiers) so the winning /// solution may still have overflow characters. This makes it hard to know /// when we are done and can stop looking. /// /// There are a couple of pieces of domain knowledge we use to cope with this: /// /// - Changing a rule from unsplit to split will never lower its cost. A /// solution with all rules unsplit will always be the one with the lowest /// cost (zero). Conversely, setting all of its rules to the maximum split /// value will always have the highest cost. /// /// (You might think there is a converse rule about overflow characters. The /// solution with the fewest splits will have the most overflow, and the /// solution with the most splits will have the least overflow. Alas, because /// of indentation, that isn't always the case. Adding a split may *increase* /// overflow in some cases.) /// /// - If all of the chunks for a rule are inside lines that already fit in the /// page, then splitting that rule will never improve the solution. /// /// - If two partial solutions have the same cost and the bound rules don't /// affect any of the remaining unbound rules, then whichever partial /// solution is currently better will always be the winner regardless of what /// the remaining unbound rules are bound to. /// /// We start off with a [SolveState] where all rules are unbound (which /// implicitly treats them as unsplit). For a given solve state, we can produce /// a set of expanded states that takes some of the rules in the first long /// line and bind them to split values. This always produces new solve states /// with higher cost (but often fewer overflow characters) than the parent /// state. /// /// We take these expanded states and add them to a work list sorted by cost. /// Since unsplit rules always have lower cost solutions, we know that no state /// we enqueue later will ever have a lower cost than the ones we already have /// enqueued. /// /// Then we keep pulling states off the work list and expanding them and adding /// the results back into the list. We do this until we hit a solution where /// all characters fit in the page. The first one we find will have the lowest /// cost and we're done. /// /// We also keep running track of the best solution we've found so far that /// has the fewest overflow characters and the lowest cost. If no solution fits, /// we'll use this one. /// /// When enqueing a solution, we can sometimes collapse it and a previously /// queued one by preferring one or the other. If two solutions have the same /// cost and we can prove that they won't diverge later as unbound rules are /// set, we can pick the winner now and discard the other. This lets us avoid /// redundantly exploring entire subtrees of the solution space. /// /// As a final escape hatch for pathologically nasty code, after trying some /// fixed maximum number of solve states, we just bail and return the best /// solution found so far. /// /// Even with the above algorithmic optimizations, complex code may still /// require a lot of exploring to find an optimal solution. To make that fast, /// this code is carefully profiled and optimized. If you modify this, make /// sure to test against the benchmark to ensure you don't regress performance. class LineSplitter { final LineWriter writer; /// The list of chunks being split. final List<Chunk> chunks; /// The set of soft rules whose values are being selected. final List<Rule> rules; /// The number of characters of additional indentation to apply to each line. /// /// This is used when formatting blocks to get the output into the right /// column based on where the block appears. final int blockIndentation; /// The starting column of the first line. final int firstLineIndent; /// The queue of solve states to explore further. /// /// This is sorted lowest-cost first. This ensures that as soon as we find a /// solution that fits in the page, we know it will be the lowest cost one /// and can stop looking. final _queue = SolveStateQueue(); /// The lowest cost solution found so far. SolveState _bestSolution; /// Creates a new splitter for [_writer] that tries to fit [chunks] into the /// page width. LineSplitter(this.writer, List<Chunk> chunks, int blockIndentation, int firstLineIndent, {bool flushLeft = false}) : chunks = chunks, // Collect the set of rules that we need to select values for. rules = chunks .map((chunk) => chunk.rule) .where((rule) => rule != null) .toSet() .toList(growable: false), blockIndentation = blockIndentation, firstLineIndent = flushLeft ? 0 : firstLineIndent + blockIndentation { _queue.bindSplitter(this); // Store the rule's index in the rule so we can get from a chunk to a rule // index quickly. for (var i = 0; i < rules.length; i++) { rules[i].index = i; } // Now that every used rule has an index, tell the rules to discard any // constraints on unindexed rules. for (var rule in rules) { rule.forgetUnusedRules(); } } /// Determine the best way to split the chunks into lines that fit in the /// page, if possible. /// /// Returns a [SplitSet] that defines where each split occurs and the /// indentation of each line. /// /// [firstLineIndent] is the number of characters of whitespace to prefix the /// first line of output with. SplitSet apply() { // Start with a completely unbound, unsplit solution. _queue.add(SolveState(this, RuleSet(rules.length))); var attempts = 0; while (_queue.isNotEmpty) { var state = _queue.removeFirst(); if (state.isBetterThan(_bestSolution)) { _bestSolution = state; // Since we sort solutions by cost the first solution we find that // fits is the winner. if (_bestSolution.overflowChars == 0) break; } if (debug.traceSplitter) { var best = state == _bestSolution ? " (best)" : ""; debug.log("$state$best"); debug.dumpLines(chunks, firstLineIndent, state.splits); debug.log(); } if (attempts++ > _maxAttempts) break; // Try bumping the rule values for rules whose chunks are on long lines. state.expand(); } if (debug.traceSplitter) { debug.log("$_bestSolution (winner)"); debug.dumpLines(chunks, firstLineIndent, _bestSolution.splits); debug.log(); } return _bestSolution.splits; } void enqueue(SolveState state) { _queue.add(state); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/rule/rule.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.rule.rule; import '../chunk.dart'; import '../fast_hash.dart'; /// A constraint that determines the different ways a related set of chunks may /// be split. class Rule extends FastHash { /// Rule value that splits no chunks. /// /// Every rule is required to treat this value as fully unsplit. static const unsplit = 0; /// Rule constraint value that means "any value as long as something splits". /// /// It disallows [unsplit] but allows any other value. static const mustSplit = -1; /// The number of different states this rule can be in. /// /// Each state determines which set of chunks using this rule are split and /// which aren't. Values range from zero to one minus this. Value zero /// always means "no chunks are split" and increasing values by convention /// mean increasingly undesirable splits. /// /// By default, a rule has two values: fully unsplit and fully split. int get numValues => 2; /// The rule value that forces this rule into its maximally split state. /// /// By convention, this is the highest of the range of allowed values. int get fullySplitValue => numValues - 1; int get cost => _cost; final int _cost; /// During line splitting [LineSplitter] sets this to the index of this /// rule in its list of rules. int index; /// If `true`, the rule has been "hardened" meaning it's been placed into a /// permanent "must fully split" state. bool get isHardened => _isHardened; bool _isHardened = false; /// The other [Rule]s that are implied this one. /// /// In many cases, if a split occurs inside an expression, surrounding rules /// also want to split too. For example, a split in the middle of an argument /// forces the entire argument list to also split. /// /// This tracks those relationships. If this rule splits, (sets its value to /// [fullySplitValue]) then all of the surrounding implied rules are also set /// to their fully split value. /// /// This contains all direct as well as transitive relationships. If A /// contains B which contains C, C's outerRules contains both B and A. final Set<Rule> _implied = Set<Rule>(); /// Marks [other] as implied by this one. /// /// That means that if this rule splits, then [other] is force to split too. void imply(Rule other) { _implied.add(other); } /// Whether this rule cares about rules that it contains. /// /// If `true` then inner rules will constrain this one and force it to split /// when they split. Otherwise, it can split independently of any contained /// rules. bool get splitsOnInnerRules => true; Rule([int cost]) : _cost = cost ?? Cost.normal; /// Creates a new rule that is already fully split. Rule.hard() : _cost = 0 { // Set the cost to zero since it will always be applied, so there's no // point in penalizing it. // // Also, this avoids doubled counting in literal blocks where there is both // a split in the outer chunk containing the block and the inner hard split // between the elements or statements. harden(); } /// Fixes this rule into a "fully split" state. void harden() { _isHardened = true; } /// Returns `true` if [chunk] should split when this rule has [value]. bool isSplit(int value, Chunk chunk) { if (_isHardened) return true; if (value == Rule.unsplit) return false; // Let the subclass decide. return isSplitAtValue(value, chunk); } /// Subclasses can override this to determine which values split which chunks. /// /// By default, this assumes every chunk splits. bool isSplitAtValue(int value, Chunk chunk) => true; /// Given that this rule has [value], determine if [other]'s value should be /// constrained. /// /// Allows relationships between rules like "if I split, then this should /// split too". Returns a non-negative value to force [other] to take that /// value. Returns -1 to allow [other] to take any non-zero value. Returns /// null to not constrain other. int constrain(int value, Rule other) { // By default, any containing rule will be fully split if this one is split. if (value == Rule.unsplit) return null; if (_implied.contains(other)) return other.fullySplitValue; return null; } /// A protected method for subclasses to add the rules that they constrain /// to [rules]. /// /// Called by [Rule] the first time [constrainedRules] is accessed. void addConstrainedRules(Set<Rule> rules) {} /// Discards constraints on any rule that doesn't have an index. /// /// This is called by [LineSplitter] after it has indexed all of the in-use /// rules. A rule may end up with a constraint on a rule that's no longer /// used by any chunk. This can happen if the rule gets hardened, or if it /// simply never got used by a chunk. For example, a rule for splitting an /// empty list of metadata annotations. /// /// This removes all of those. void forgetUnusedRules() { _implied.retainWhere((rule) => rule.index != null); // Clear the cached ones too. _constrainedRules = null; _allConstrainedRules = null; } /// The other [Rule]s that this rule places immediate constraints on. Set<Rule> get constrainedRules { // Lazy initialize this on first use. Note: Assumes this is only called // after the chunks have been written and any constraints have been wired // up. if (_constrainedRules == null) { _constrainedRules = _implied.toSet(); addConstrainedRules(_constrainedRules); } return _constrainedRules; } Set<Rule> _constrainedRules; /// The transitive closure of all of the rules this rule places constraints /// on, directly or indirectly, including itself. Set<Rule> get allConstrainedRules { if (_allConstrainedRules == null) { visit(Rule rule) { if (_allConstrainedRules.contains(rule)) return; _allConstrainedRules.add(rule); rule.constrainedRules.forEach(visit); } _allConstrainedRules = Set(); visit(this); } return _allConstrainedRules; } Set<Rule> _allConstrainedRules; String toString() => "$id"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/rule/argument.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.rule.argument; import '../chunk.dart'; import 'rule.dart'; /// Base class for a rule that handles argument or parameter lists. abstract class ArgumentRule extends Rule { /// The chunks prior to each positional argument. final List<Chunk> _arguments = []; /// The rule used to split collections in the argument list, if any. Rule _collectionRule; /// The number of leading collection arguments. /// /// This and [_trailingCollections] cannot both be positive. If every /// argument is a collection, this will be [_arguments.length] and /// [_trailingCollections] will be 0. final int _leadingCollections; /// The number of trailing collections. /// /// This and [_leadingCollections] cannot both be positive. final int _trailingCollections; /// If true, then inner rules that are written will force this rule to split. /// /// Temporarily disabled while writing collection arguments so that they can /// be multi-line without forcing the whole argument list to split. bool _trackInnerRules = true; /// Don't split when an inner collection rule splits. bool get splitsOnInnerRules => _trackInnerRules; ArgumentRule(this._collectionRule, this._leadingCollections, this._trailingCollections); void addConstrainedRules(Set<Rule> rules) { super.addConstrainedRules(rules); if (_collectionRule != null) rules.add(_collectionRule); } void forgetUnusedRules() { super.forgetUnusedRules(); if (_collectionRule != null && _collectionRule.index == null) { _collectionRule = null; } } /// Remembers [chunk] as containing the split that occurs right before an /// argument in the list. void beforeArgument(Chunk chunk) { _arguments.add(chunk); } /// Disables tracking inner rules while a collection argument is written. void disableSplitOnInnerRules() { assert(_trackInnerRules == true); _trackInnerRules = false; } /// Re-enables tracking inner rules. void enableSplitOnInnerRules() { assert(_trackInnerRules == false); _trackInnerRules = true; } } /// Rule for handling positional argument lists. /// /// The number of values is based on the number of arguments and whether or not /// there are bodies. The first two values are always: /// /// * 0: Do not split at all. /// * 1: Split only before the first argument. /// /// Then there is a value for each argument, to split before that argument. /// These values work back to front. So, for a two-argument list, value 2 splits /// after the second argument and value 3 splits after the first. /// /// Then there is a value that splits before every argument. /// /// Finally, if there are collection arguments, there is another value that /// splits before all of the non-collection arguments, but does not split /// before the collections, so that they can split internally. class PositionalRule extends ArgumentRule { /// If there are named arguments following these positional ones, this will /// be their rule. Rule _namedArgsRule; /// Creates a new rule for a positional argument list. /// /// If [_collectionRule] is given, it is the rule used to split the collection /// arguments in the list. PositionalRule( Rule collectionRule, int leadingCollections, int trailingCollections) : super(collectionRule, leadingCollections, trailingCollections); int get numValues { // Can split before any one argument or none. var result = _arguments.length + 1; // If there are multiple arguments, can split before all of them. if (_arguments.length > 1) result++; // When there are collection arguments, there are two ways we can split on // "all" arguments: // // - Split on just the non-collection arguments, and force the collection // arguments to split internally. // - Split on all of them including the collection arguments, and do not // allow the collection arguments to split internally. if (_leadingCollections > 0 || _trailingCollections > 0) result++; return result; } void addConstrainedRules(Set<Rule> rules) { super.addConstrainedRules(rules); if (_namedArgsRule != null) rules.add(_namedArgsRule); } void forgetUnusedRules() { super.forgetUnusedRules(); if (_namedArgsRule != null && _namedArgsRule.index == null) { _namedArgsRule = null; } } bool isSplitAtValue(int value, Chunk chunk) { // Split only before the first argument. Keep the entire argument list // together on the next line. if (value == 1) return chunk == _arguments.first; // Split before a single argument. Try later arguments before earlier ones // to try to keep as much on the first line as possible. if (value <= _arguments.length) { var argument = _arguments.length - value + 1; return chunk == _arguments[argument]; } // Only split before the non-collection arguments. if (value == _arguments.length + 1) { for (var i = 0; i < _leadingCollections; i++) { if (chunk == _arguments[i]) return false; } for (var i = _arguments.length - _trailingCollections; i < _arguments.length; i++) { if (chunk == _arguments[i]) return false; } return true; } // Split before all of the arguments, even the collections. return true; } /// Remembers that [rule] is the [Rule] immediately following this positional /// positional argument list. /// /// This is normally a [NamedRule] but [PositionalRule] is also used for the /// property accesses at the beginning of a call chain, in which case this /// is just a [SimpleRule]. void setNamedArgsRule(Rule rule) { _namedArgsRule = rule; } /// Constrains the named argument list to at least move to the next line if /// there are any splits in the positional arguments. Prevents things like: /// /// function( /// argument, /// argument, named: argument); int constrain(int value, Rule other) { var constrained = super.constrain(value, other); if (constrained != null) return constrained; // Handle the relationship between the positional and named args. if (other == _namedArgsRule) { // If the positional args are one-per-line, the named args are too. if (value == fullySplitValue) return _namedArgsRule.fullySplitValue; // Otherwise, if there is any split in the positional arguments, don't // allow the named arguments on the same line as them. if (value != 0) return -1; } // Decide how to constrain the collection rule. if (other != _collectionRule) return null; // If all of the collections are in the named arguments, [_collectionRule] // will not be null, but we don't have to handle it. if (_leadingCollections == 0 && _trailingCollections == 0) return null; // If we aren't splitting any args, we can split the collection. if (value == Rule.unsplit) return null; // Split only before the first argument. if (value == 1) { if (_leadingCollections > 0) { // We are splitting before a collection, so don't let it split // internally. return Rule.unsplit; } else { // The split is outside of the collections so they can split or not. return null; } } // Split before a single argument. If it's in the middle of the collection // arguments, don't allow them to split. if (value <= _arguments.length) { var argument = _arguments.length - value + 1; if (argument < _leadingCollections || argument >= _arguments.length - _trailingCollections) { return Rule.unsplit; } return null; } // Only split before the non-collection arguments. This case only comes into // play when we do want to split the collection, so force that here. if (value == _arguments.length + 1) return 1; // Split before all of the arguments, even the collections. We'll allow // them to split but indent their bodies if they do. return null; } String toString() => "Pos${super.toString()}"; } /// Splitting rule for a list of named arguments or parameters. Its values mean: /// /// * Do not split at all. /// * Split only before first argument. /// * Split before all arguments. class NamedRule extends ArgumentRule { int get numValues => 3; NamedRule( Rule collectionRule, int leadingCollections, int trailingCollections) : super(collectionRule, leadingCollections, trailingCollections); bool isSplitAtValue(int value, Chunk chunk) { // Move all arguments to the second line as a unit. if (value == 1) return chunk == _arguments.first; // Otherwise, split before all arguments. return true; } int constrain(int value, Rule other) { var constrained = super.constrain(value, other); if (constrained != null) return constrained; // Decide how to constrain the collection rule. if (other != _collectionRule) return null; // If all of the collections are in the named arguments, [_collectionRule] // will not be null, but we don't have to handle it. if (_leadingCollections == 0 && _trailingCollections == 0) return null; // If we aren't splitting any args, we can split the collection. if (value == Rule.unsplit) return null; // Split only before the first argument. Don't allow the collections to // split. if (value == 1) return Rule.unsplit; // Split before all of the arguments, even the collections. We'll allow // them to split but indent their bodies if they do. return null; } String toString() => "Named${super.toString()}"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/rule/metadata.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.rule.metadata; import 'argument.dart'; import 'rule.dart'; /// Rule for handling splits between parameter metadata annotations and the /// following parameter. /// /// Metadata annotations for parameters (and type parameters) get some special /// handling. We use a single rule for all annotations in the parameter list. /// If any of the annotations split, they all do. /// /// Also, if the annotations split, we force the entire parameter list to fully /// split, both named and positional. class MetadataRule extends Rule { Rule _positionalRule; Rule _namedRule; /// Remembers that [rule] is the [PositionalRule] used by the argument list /// containing the parameter metadata using this rule. void bindPositionalRule(PositionalRule rule) { _positionalRule = rule; } /// Remembers that [rule] is the [NamedRule] used by the argument list /// containing the parameter metadata using this rule. void bindNamedRule(NamedRule rule) { _namedRule = rule; } /// Constrains the surrounding argument list rules to fully split if the /// metadata does. int constrain(int value, Rule other) { var constrained = super.constrain(value, other); if (constrained != null) return constrained; // If the metadata doesn't split, we don't care what the arguments do. if (value == Rule.unsplit) return null; // Otherwise, they have to split. if (other == _positionalRule) return _positionalRule.fullySplitValue; if (other == _namedRule) return _namedRule.fullySplitValue; return null; } void addConstrainedRules(Set<Rule> rules) { if (_positionalRule != null) rules.add(_positionalRule); if (_namedRule != null) rules.add(_namedRule); } void forgetUnusedRules() { super.forgetUnusedRules(); if (_positionalRule != null && _positionalRule.index == null) { _positionalRule = null; } if (_namedRule != null && _namedRule.index == null) { _namedRule = null; } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/rule/combinator.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.rule.combinator; import '../chunk.dart'; import 'rule.dart'; /// Handles a list of "combinators". /// /// A combinator is a keyword followed by a list of nodes used to modify some /// declaration. It's used for actual hide and show combinators as well as /// "with" and "implements" clauses in class declarations. /// /// Combinators can be split in a few different ways: /// /// // All on one line: /// import 'animals.dart' show Ant hide Cat; /// /// // Wrap before each keyword: /// import 'animals.dart' /// show Ant, Baboon /// hide Cat; /// /// // Wrap either or both of the name lists: /// import 'animals.dart' /// show /// Ant, /// Baboon /// hide Cat; /// /// These are not allowed: /// /// // Wrap list but not keyword: /// import 'animals.dart' show /// Ant, /// Baboon /// hide Cat; /// /// // Wrap one keyword but not both: /// import 'animals.dart' /// show Ant, Baboon hide Cat; /// /// This ensures that when any wrapping occurs, the keywords are always at /// the beginning of the line. class CombinatorRule extends Rule { /// The set of chunks before the combinators. final Set<Chunk> _combinators = Set(); /// A list of sets of chunks prior to each name in a combinator. /// /// The outer list is a list of combinators (i.e. "hide", "show", etc.). Each /// inner set is the set of names for that combinator. final List<Set<Chunk>> _names = []; int get numValues { var count = 2; // No wrapping, or wrap just before each combinator. if (_names.length == 2) { count += 3; // Wrap first set of names, second, or both. } else { assert(_names.length == 1); count++; // Wrap the names. } return count; } /// Adds a new combinator to the list of combinators. /// /// This must be called before adding any names. void addCombinator(Chunk chunk) { _combinators.add(chunk); _names.add(Set()); } /// Adds a chunk prior to a name to the current combinator. void addName(Chunk chunk) { _names.last.add(chunk); } bool isSplitAtValue(int value, Chunk chunk) { switch (value) { case 1: // Just split at the combinators. return _combinators.contains(chunk); case 2: // Split at the combinators and the first set of names. return _isCombinatorSplit(0, chunk); case 3: // If there is two combinators, just split at the combinators and the // second set of names. if (_names.length == 2) { // Two sets of combinators, so just split at the combinators and the // second set of names. return _isCombinatorSplit(1, chunk); } // Split everything. return true; default: return true; } } /// Returns `true` if [chunk] is for a combinator or a name in the /// combinator at index [combinator]. bool _isCombinatorSplit(int combinator, Chunk chunk) { return _combinators.contains(chunk) || _names[combinator].contains(chunk); } String toString() => "Comb${super.toString()}"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/dart_style/src/rule/type_argument.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_style.src.rule.type_argument; import '../chunk.dart'; import 'rule.dart'; /// Rule for splitting a list of type arguments or type parameters. Type /// parameters split a little differently from normal value argument lists. In /// particular, this tries harder to avoid splitting before the first type /// argument since that looks stranger with `<...>` than it does with `(...)`. /// /// The values for a rule for `n` arguments are: /// /// * `0`: No splits at all. /// * `1 ... n`: Split before one argument, starting from the last. /// * `n + 1`: Split before all arguments. /// /// If there is only one type argument, the last two cases collapse and there /// are only two values. class TypeArgumentRule extends Rule { /// The chunks prior to each positional type argument. final List<Chunk> _arguments = []; int get cost => Cost.typeArgument; int get numValues => _arguments.length == 1 ? 2 : _arguments.length + 2; /// Remembers [chunk] as containing the split that occurs right before a type /// argument in the list. void beforeArgument(Chunk chunk) { _arguments.add(chunk); } bool isSplit(int value, Chunk chunk) { // Don't split at all. if (value == Rule.unsplit) return false; // Split before every argument. if (value == numValues - 1) return true; // Split before a single argument. Try later arguments before earlier ones // to try to keep as much on the first line as possible. return chunk == _arguments[_arguments.length - value]; } String toString() => "TypeArg${super.toString()}"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver_hashcode/hashcode.dart
// 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. /// Compute `hashCode` correctly for your objects. library quiver.hashcode; /// Generates a hash code for multiple [objects]. int hashObjects(Iterable objects) => _finish(objects.fold(0, (h, i) => _combine(h, i.hashCode))); /// Generates a hash code for two objects. int hash2(a, b) => _finish(_combine(_combine(0, a.hashCode), b.hashCode)); /// Generates a hash code for three objects. int hash3(a, b, c) => _finish( _combine(_combine(_combine(0, a.hashCode), b.hashCode), c.hashCode)); /// Generates a hash code for four objects. int hash4(a, b, c, d) => _finish(_combine( _combine(_combine(_combine(0, a.hashCode), b.hashCode), c.hashCode), d.hashCode)); // Jenkins hash functions int _combine(int hash, int value) { hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } int _finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing/timing.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/timing.dart' show TimeSlice, TimeSliceGroup, TimeTracker, SyncTimeTracker, SimpleAsyncTimeTracker, AsyncTimeTracker, NoOpTimeTracker;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing/src/timing.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:json_annotation/json_annotation.dart'; import 'clock.dart'; part 'timing.g.dart'; /// The timings of an operation, including its [startTime], [stopTime], and /// [duration]. @JsonSerializable(nullable: false) class TimeSlice { /// The total duration of this operation, equivalent to taking the difference /// between [stopTime] and [startTime]. Duration get duration => stopTime.difference(startTime); final DateTime startTime; final DateTime stopTime; TimeSlice(this.startTime, this.stopTime); factory TimeSlice.fromJson(Map<String, dynamic> json) => _$TimeSliceFromJson(json); Map<String, dynamic> toJson() => _$TimeSliceToJson(this); @override String toString() => '($startTime + $duration)'; } /// The timings of an async operation, consist of several sync [slices] and /// includes total [startTime], [stopTime], and [duration]. @JsonSerializable(nullable: false) class TimeSliceGroup implements TimeSlice { final List<TimeSlice> slices; @override DateTime get startTime => slices.first.startTime; @override DateTime get stopTime => slices.last.stopTime; /// The total duration of this operation, equivalent to taking the difference /// between [stopTime] and [startTime]. @override Duration get duration => stopTime.difference(startTime); /// Sum of [duration]s of all [slices]. /// /// If some of slices implements [TimeSliceGroup] [innerDuration] will be used /// to compute sum. Duration get innerDuration => slices.fold( Duration.zero, (duration, slice) => duration + (slice is TimeSliceGroup ? slice.innerDuration : slice.duration)); TimeSliceGroup(this.slices); /// Constructs TimeSliceGroup from JSON representation factory TimeSliceGroup.fromJson(Map<String, dynamic> json) => _$TimeSliceGroupFromJson(json); @override Map<String, dynamic> toJson() => _$TimeSliceGroupToJson(this); @override String toString() => slices.toString(); } abstract class TimeTracker implements TimeSlice { /// Whether tracking is active. /// /// Tracking is only active after `isStarted` and before `isFinished`. bool get isTracking; /// Whether tracking is finished. /// /// Tracker can't be used as [TimeSlice] before it is finished bool get isFinished; /// Whether tracking was started. /// /// Equivalent of `isTracking || isFinished` bool get isStarted; T track<T>(T Function() action); } /// Tracks only sync actions class SyncTimeTracker implements TimeTracker { /// When this operation started, call [_start] to set this. @override DateTime get startTime => _startTime; DateTime _startTime; /// When this operation stopped, call [_stop] to set this. @override DateTime get stopTime => _stopTime; DateTime _stopTime; /// Start tracking this operation, must only be called once, before [_stop]. void _start() { assert(_startTime == null && _stopTime == null); _startTime = now(); } /// Stop tracking this operation, must only be called once, after [_start]. void _stop() { assert(_startTime != null && _stopTime == null); _stopTime = now(); } /// Splits tracker into two slices /// /// Returns new [TimeSlice] started on [startTime] and ended now. /// Modifies [startTime] of tracker to current time point /// /// Don't change state of tracker. Can be called only while [isTracking], and /// tracker will sill be tracking after call. TimeSlice _split() { if (!isTracking) { throw StateError('Can be only called while tracking'); } final _now = now(); final prevSlice = TimeSlice(_startTime, _now); _startTime = _now; return prevSlice; } @override T track<T>(T Function() action) { if (isStarted) { throw StateError('Can not be tracked twice'); } _start(); try { return action(); } finally { _stop(); } } @override bool get isStarted => startTime != null; @override bool get isTracking => startTime != null && stopTime == null; @override bool get isFinished => startTime != null && stopTime != null; @override Duration get duration => stopTime?.difference(startTime); /// Converts to JSON representation /// /// Can't be used before [isFinished] @override Map<String, dynamic> toJson() => _$TimeSliceToJson(this); } /// Async actions returning [Future] will be tracked as single sync time span /// from the beginning of execution till completion of future class SimpleAsyncTimeTracker extends SyncTimeTracker { @override T track<T>(T Function() action) { if (isStarted) { throw StateError('Can not be tracked twice'); } T result; _start(); try { result = action(); } catch (_) { _stop(); rethrow; } if (result is Future) { return result.whenComplete(_stop) as T; } else { _stop(); return result; } } } /// No-op implementation of [SyncTimeTracker] that does nothing. class NoOpTimeTracker implements TimeTracker { static final sharedInstance = NoOpTimeTracker(); @override Duration get duration => throw UnsupportedError('Unsupported in no-op implementation'); @override DateTime get startTime => throw UnsupportedError('Unsupported in no-op implementation'); @override DateTime get stopTime => throw UnsupportedError('Unsupported in no-op implementation'); @override bool get isStarted => throw UnsupportedError('Unsupported in no-op implementation'); @override bool get isTracking => throw UnsupportedError('Unsupported in no-op implementation'); @override bool get isFinished => throw UnsupportedError('Unsupported in no-op implementation'); @override T track<T>(T Function() action) => action(); @override Map<String, dynamic> toJson() => throw UnsupportedError('Unsupported in no-op implementation'); } /// Track all async execution as disjoint time [slices] in ascending order. /// /// Can [track] both async and sync actions. /// Can exclude time of tested trackers. /// /// If tracked action spawns some dangled async executions behavior is't /// defined. Tracked might or might not track time of such executions class AsyncTimeTracker extends TimeSliceGroup implements TimeTracker { final bool trackNested; static const _zoneKey = #timing_AsyncTimeTracker; AsyncTimeTracker({this.trackNested = true}) : super([]); T _trackSyncSlice<T>(ZoneDelegate parent, Zone zone, T Function() action) { // Ignore dangling runs after tracker completes if (isFinished) { return action(); } final isNestedRun = slices.isNotEmpty && slices.last is SyncTimeTracker && (slices.last as SyncTimeTracker).isTracking; final isExcludedNestedTrack = !trackNested && zone[_zoneKey] != this; // Exclude nested sync tracks if (isNestedRun && isExcludedNestedTrack) { final timer = slices.last as SyncTimeTracker; // Split already tracked time into new slice. // Replace tracker in slices.last with splitted slice, to indicate for // recursive calls that we not tracking. slices.last = parent.run(zone, timer._split); try { return action(); } finally { // Split tracker again and discard slice that was spend in nested tracker parent.run(zone, timer._split); // Add tracker back to list of slices and continue tracking slices.add(timer); } } // Exclude nested async tracks if (isExcludedNestedTrack) { return action(); } // Split time slices in nested sync runs if (isNestedRun) { return action(); } final timer = SyncTimeTracker(); slices.add(timer); // Pass to parent zone, in case of overwritten clock return parent.runUnary(zone, timer.track, action); } static final asyncTimeTrackerZoneSpecification = ZoneSpecification( run: <R>(Zone self, ZoneDelegate parent, Zone zone, R Function() f) { final tracker = self[_zoneKey] as AsyncTimeTracker; return tracker._trackSyncSlice(parent, zone, () => parent.run(zone, f)); }, runUnary: <R, T>(Zone self, ZoneDelegate parent, Zone zone, R Function(T) f, T arg) { final tracker = self[_zoneKey] as AsyncTimeTracker; return tracker._trackSyncSlice( parent, zone, () => parent.runUnary(zone, f, arg)); }, runBinary: <R, T1, T2>(Zone self, ZoneDelegate parent, Zone zone, R Function(T1, T2) f, T1 arg1, T2 arg2) { final tracker = self[_zoneKey] as AsyncTimeTracker; return tracker._trackSyncSlice( parent, zone, () => parent.runBinary(zone, f, arg1, arg2)); }, ); @override T track<T>(T Function() action) { if (isStarted) { throw StateError('Can not be tracked twice'); } _tracking = true; final result = runZoned(action, zoneSpecification: asyncTimeTrackerZoneSpecification, zoneValues: {_zoneKey: this}); if (result is Future) { return result // Break possible sync processing of future completion, so slice trackers can be finished .whenComplete(() => Future.value()) .whenComplete(() => _tracking = false) as T; } else { _tracking = false; return result; } } bool _tracking; @override bool get isStarted => _tracking != null; @override bool get isFinished => _tracking == false; @override bool get isTracking => _tracking == true; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing/src/timing.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'timing.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** TimeSlice _$TimeSliceFromJson(Map<String, dynamic> json) { return TimeSlice( DateTime.parse(json['startTime'] as String), DateTime.parse(json['stopTime'] as String), ); } Map<String, dynamic> _$TimeSliceToJson(TimeSlice instance) => <String, dynamic>{ 'startTime': instance.startTime.toIso8601String(), 'stopTime': instance.stopTime.toIso8601String(), }; TimeSliceGroup _$TimeSliceGroupFromJson(Map<String, dynamic> json) { return TimeSliceGroup( (json['slices'] as List) .map((e) => TimeSlice.fromJson(e as Map<String, dynamic>)) .toList(), ); } Map<String, dynamic> _$TimeSliceGroupToJson(TimeSliceGroup instance) => <String, dynamic>{ 'slices': instance.slices, };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/timing/src/clock.dart
// 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'; /// A function that returns the current [DateTime]. typedef _Clock = DateTime Function(); DateTime _defaultClock() => DateTime.now(); const _zoneKey = #timing_Clock; /// Returns the current [DateTime]. /// /// May be overridden for tests using [scopeClock]. DateTime now() => (Zone.current[_zoneKey] as _Clock ?? _defaultClock)(); /// Runs [f], with [clock] scoped whenever [now] is called. T scopeClock<T>(DateTime Function() clock, T Function() f) => runZoned(f, zoneValues: {_zoneKey: clock});
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pedantic/pedantic.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async' show Future; /// Indicates to tools that [future] is intentionally not `await`-ed. /// /// In an `async` context, it is normally expected that all [Future]s are /// awaited, and that is the basis of the lint `unawaited_futures`. However, /// there are times where one or more futures are intentionally not awaited. /// This function may be used to ignore a particular future. It silences the /// `unawaited_futures` lint. /// /// ``` /// Future<void> saveUserPreferences() async { /// await _writePreferences(); /// /// // While 'log' returns a Future, the consumer of 'saveUserPreferences' /// // is unlikely to want to wait for that future to complete; they only /// // care about the preferences being written). /// unawaited(log('Preferences saved!')); /// } /// ``` void unawaited(Future<void> future) {}
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/watcher.dart
// 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:async'; import 'dart:io'; import 'src/watch_event.dart'; import 'src/directory_watcher.dart'; import 'src/file_watcher.dart'; export 'src/watch_event.dart'; export 'src/directory_watcher.dart'; export 'src/directory_watcher/polling.dart'; export 'src/file_watcher.dart'; export 'src/file_watcher/polling.dart'; abstract class Watcher { /// The path to the file or directory whose contents are being monitored. String get path; /// The broadcast [Stream] of events that have occurred to the watched file or /// files in the watched directory. /// /// Changes will only be monitored while this stream has subscribers. Any /// changes that occur during periods when there are no subscribers will not /// be reported the next time a subscriber is added. Stream<WatchEvent> get events; /// Whether the watcher is initialized and watching for changes. /// /// This is true if and only if [ready] is complete. bool get isReady; /// A [Future] that completes when the watcher is initialized and watching for /// changes. /// /// If the watcher is not currently monitoring the file or directory (because /// there are no subscribers to [events]), this returns a future that isn't /// complete yet. It will complete when a subscriber starts listening and the /// watcher finishes any initialization work it needs to do. /// /// If the watcher is already monitoring, this returns an already complete /// future. Future get ready; /// Creates a new [DirectoryWatcher] or [FileWatcher] monitoring [path], /// depending on whether it's a file or directory. /// /// If a native watcher is available for this platform, this will use it. /// Otherwise, it will fall back to a polling watcher. Notably, watching /// individual files is not natively supported on Windows, although watching /// directories is. /// /// If [pollingDelay] is passed, it specifies the amount of time the watcher /// will pause between successive polls of the contents of [path]. Making this /// shorter will give more immediate feedback at the expense of doing more IO /// and higher CPU usage. Defaults to one second. Ignored for non-polling /// watchers. factory Watcher(String path, {Duration pollingDelay}) { if (File(path).existsSync()) { return FileWatcher(path, pollingDelay: pollingDelay); } else { return DirectoryWatcher(path, pollingDelay: pollingDelay); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/file_watcher.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import '../watcher.dart'; import 'file_watcher/native.dart'; import 'file_watcher/polling.dart'; /// Watches a file and emits [WatchEvent]s when the file has changed. /// /// Note that since each watcher only watches a single file, it will only emit /// [ChangeType.MODIFY] events, except when the file is deleted at which point /// it will emit a single [ChangeType.REMOVE] event and then close the stream. /// /// If the file is deleted and quickly replaced (when a new file is moved in its /// place, for example) this will emit a [ChangeType.MODIFY] event. abstract class FileWatcher implements Watcher { /// Creates a new [FileWatcher] monitoring [file]. /// /// If a native file watcher is available for this platform, this will use it. /// Otherwise, it will fall back to a [PollingFileWatcher]. Notably, native /// file watching is *not* supported on Windows. /// /// If [pollingDelay] is passed, it specifies the amount of time the watcher /// will pause between successive polls of the directory contents. Making this /// shorter will give more immediate feedback at the expense of doing more IO /// and higher CPU usage. Defaults to one second. Ignored for non-polling /// watchers. factory FileWatcher(String file, {Duration pollingDelay}) { // [File.watch] doesn't work on Windows, but // [FileSystemEntity.isWatchSupported] is still true because directory // watching does work. if (FileSystemEntity.isWatchSupported && !Platform.isWindows) { return NativeFileWatcher(file); } return PollingFileWatcher(file, pollingDelay: pollingDelay); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/constructable_file_system_event.dart
// 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'; abstract class _ConstructableFileSystemEvent implements FileSystemEvent { @override final bool isDirectory; @override final String path; @override int get type; _ConstructableFileSystemEvent(this.path, this.isDirectory); } class ConstructableFileSystemCreateEvent extends _ConstructableFileSystemEvent implements FileSystemCreateEvent { @override final type = FileSystemEvent.create; ConstructableFileSystemCreateEvent(String path, bool isDirectory) : super(path, isDirectory); @override String toString() => "FileSystemCreateEvent('$path')"; } class ConstructableFileSystemDeleteEvent extends _ConstructableFileSystemEvent implements FileSystemDeleteEvent { @override final type = FileSystemEvent.delete; ConstructableFileSystemDeleteEvent(String path, bool isDirectory) : super(path, isDirectory); @override String toString() => "FileSystemDeleteEvent('$path')"; } class ConstructableFileSystemModifyEvent extends _ConstructableFileSystemEvent implements FileSystemModifyEvent { @override final bool contentChanged; @override final type = FileSystemEvent.modify; ConstructableFileSystemModifyEvent( String path, bool isDirectory, this.contentChanged) : super(path, isDirectory); @override String toString() => "FileSystemModifyEvent('$path', contentChanged=$contentChanged)"; } class ConstructableFileSystemMoveEvent extends _ConstructableFileSystemEvent implements FileSystemMoveEvent { @override final String destination; @override final type = FileSystemEvent.move; ConstructableFileSystemMoveEvent( String path, bool isDirectory, this.destination) : super(path, isDirectory); @override String toString() => "FileSystemMoveEvent('$path', '$destination')"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/path_set.dart
// 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:collection'; import 'package:path/path.dart' as p; /// A set of paths, organized into a directory hierarchy. /// /// When a path is [add]ed, it creates an implicit directory structure above /// that path. Directories can be inspected using [containsDir] and removed /// using [remove]. If they're removed, their contents are removed as well. /// /// The paths in the set are normalized so that they all begin with [root]. class PathSet { /// The root path, which all paths in the set must be under. final String root; /// The path set's directory hierarchy. /// /// Each entry represents a directory or file. It may be a file or directory /// that was explicitly added, or a parent directory that was implicitly /// added in order to add a child. final _Entry _entries = _Entry(); PathSet(this.root); /// Adds [path] to the set. void add(String path) { path = _normalize(path); var parts = p.split(path); var entry = _entries; for (var part in parts) { entry = entry.contents.putIfAbsent(part, () => _Entry()); } entry.isExplicit = true; } /// Removes [path] and any paths beneath it from the set and returns the /// removed paths. /// /// Even if [path] itself isn't in the set, if it's a directory containing /// paths that are in the set those paths will be removed and returned. /// /// If neither [path] nor any paths beneath it are in the set, returns an /// empty set. Set<String> remove(String path) { path = _normalize(path); var parts = Queue.of(p.split(path)); // Remove the children of [dir], as well as [dir] itself if necessary. // // [partialPath] is the path to [dir], and a prefix of [path]; the remaining // components of [path] are in [parts]. Set<String> recurse(_Entry dir, String partialPath) { if (parts.length > 1) { // If there's more than one component left in [path], recurse down to // the next level. var part = parts.removeFirst(); var entry = dir.contents[part]; if (entry == null || entry.contents.isEmpty) return <String>{}; partialPath = p.join(partialPath, part); var paths = recurse(entry, partialPath); // After removing this entry's children, if it has no more children and // it's not in the set in its own right, remove it as well. if (entry.contents.isEmpty && !entry.isExplicit) { dir.contents.remove(part); } return paths; } // If there's only one component left in [path], we should remove it. var entry = dir.contents.remove(parts.first); if (entry == null) return <String>{}; if (entry.contents.isEmpty) { return {p.join(root, path)}; } var set = _explicitPathsWithin(entry, path); if (entry.isExplicit) { set.add(p.join(root, path)); } return set; } return recurse(_entries, root); } /// Recursively lists all of the explicit paths within [dir]. /// /// [dirPath] should be the path to [dir]. Set<String> _explicitPathsWithin(_Entry dir, String dirPath) { var paths = <String>{}; void recurse(_Entry dir, String path) { dir.contents.forEach((name, entry) { var entryPath = p.join(path, name); if (entry.isExplicit) paths.add(p.join(root, entryPath)); recurse(entry, entryPath); }); } recurse(dir, dirPath); return paths; } /// Returns whether this set contains [path]. /// /// This only returns true for paths explicitly added to this set. /// Implicitly-added directories can be inspected using [containsDir]. bool contains(String path) { path = _normalize(path); var entry = _entries; for (var part in p.split(path)) { entry = entry.contents[part]; if (entry == null) return false; } return entry.isExplicit; } /// Returns whether this set contains paths beneath [path]. bool containsDir(String path) { path = _normalize(path); var entry = _entries; for (var part in p.split(path)) { entry = entry.contents[part]; if (entry == null) return false; } return entry.contents.isNotEmpty; } /// All of the paths explicitly added to this set. List<String> get paths { var result = <String>[]; void recurse(_Entry dir, String path) { for (var name in dir.contents.keys) { var entry = dir.contents[name]; var entryPath = p.join(path, name); if (entry.isExplicit) result.add(entryPath); recurse(entry, entryPath); } } recurse(_entries, root); return result; } /// Removes all paths from this set. void clear() { _entries.contents.clear(); } /// Returns a normalized version of [path]. /// /// This removes any extra ".." or "."s and ensure that the returned path /// begins with [root]. It's an error if [path] isn't within [root]. String _normalize(String path) { assert(p.isWithin(root, path)); return p.relative(p.normalize(path), from: root); } } /// A virtual file system entity tracked by the [PathSet]. /// /// It may have child entries in [contents], which implies it's a directory. class _Entry { /// The child entries contained in this directory. final Map<String, _Entry> contents = {}; /// If this entry was explicitly added as a leaf file system entity, this /// will be true. /// /// Otherwise, it represents a parent directory that was implicitly added /// when added some child of it. bool isExplicit = false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/async_queue.dart
// 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:async'; import 'dart:collection'; typedef ItemProcessor<T> = Future<void> Function(T item); /// A queue of items that are sequentially, asynchronously processed. /// /// Unlike [Stream.map] or [Stream.forEach], the callback used to process each /// item returns a [Future], and it will not advance to the next item until the /// current item is finished processing. /// /// Items can be added at any point in time and processing will be started as /// needed. When all items are processed, it stops processing until more items /// are added. class AsyncQueue<T> { final _items = Queue<T>(); /// Whether or not the queue is currently waiting on a processing future to /// complete. bool _isProcessing = false; /// The callback to invoke on each queued item. /// /// The next item in the queue will not be processed until the [Future] /// returned by this completes. final ItemProcessor<T> _processor; /// The handler for errors thrown during processing. /// /// Used to avoid top-leveling asynchronous errors. final Function _errorHandler; AsyncQueue(this._processor, {Function onError}) : _errorHandler = onError; /// Enqueues [item] to be processed and starts asynchronously processing it /// if a process isn't already running. void add(T item) { _items.add(item); // Start up the asynchronous processing if not already running. if (_isProcessing) return; _isProcessing = true; _processNextItem().catchError(_errorHandler); } /// Removes all remaining items to be processed. void clear() { _items.clear(); } /// Pulls the next item off [_items] and processes it. /// /// When complete, recursively calls itself to continue processing unless /// the process was cancelled. Future<void> _processNextItem() async { var item = _items.removeFirst(); await _processor(item); if (_items.isNotEmpty) return _processNextItem(); // We have drained the queue, stop processing and wait until something // has been enqueued. _isProcessing = false; return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/watch_event.dart
// 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. /// An event describing a single change to the file system. class WatchEvent { /// The manner in which the file at [path] has changed. final ChangeType type; /// The path of the file that changed. final String path; WatchEvent(this.type, this.path); @override String toString() => '$type $path'; } /// Enum for what kind of change has happened to a file. class ChangeType { /// A new file has been added. static const ADD = ChangeType('add'); /// A file has been removed. static const REMOVE = ChangeType('remove'); /// The contents of a file have changed. static const MODIFY = ChangeType('modify'); final String _name; const ChangeType(this._name); @override String toString() => _name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/directory_watcher.dart
// 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'; import '../watcher.dart'; import 'directory_watcher/linux.dart'; import 'directory_watcher/mac_os.dart'; import 'directory_watcher/windows.dart'; import 'directory_watcher/polling.dart'; /// Watches the contents of a directory and emits [WatchEvent]s when something /// in the directory has changed. abstract class DirectoryWatcher implements Watcher { /// The directory whose contents are being monitored. @Deprecated('Expires in 1.0.0. Use DirectoryWatcher.path instead.') String get directory; /// Creates a new [DirectoryWatcher] monitoring [directory]. /// /// If a native directory watcher is available for this platform, this will /// use it. Otherwise, it will fall back to a [PollingDirectoryWatcher]. /// /// If [pollingDelay] is passed, it specifies the amount of time the watcher /// will pause between successive polls of the directory contents. Making this /// shorter will give more immediate feedback at the expense of doing more IO /// and higher CPU usage. Defaults to one second. Ignored for non-polling /// watchers. factory DirectoryWatcher(String directory, {Duration pollingDelay}) { if (FileSystemEntity.isWatchSupported) { if (Platform.isLinux) return LinuxDirectoryWatcher(directory); if (Platform.isMacOS) return MacOSDirectoryWatcher(directory); if (Platform.isWindows) return WindowsDirectoryWatcher(directory); } return PollingDirectoryWatcher(directory, pollingDelay: pollingDelay); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/stat.dart
// 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:async'; import 'dart:io'; /// A function that takes a file path and returns the last modified time for /// the file at that path. typedef MockTimeCallback = DateTime Function(String path); MockTimeCallback _mockTimeCallback; /// Overrides the default behavior for accessing a file's modification time /// with [callback]. /// /// The OS file modification time has pretty rough granularity (like a few /// seconds) which can make for slow tests that rely on modtime. This lets you /// replace it with something you control. void mockGetModificationTime(MockTimeCallback callback) { _mockTimeCallback = callback; } /// Gets the modification time for the file at [path]. Future<DateTime> modificationTime(String path) async { if (_mockTimeCallback != null) { return _mockTimeCallback(path); } final stat = await FileStat.stat(path); if (stat.type == FileSystemEntityType.notFound) return null; return stat.modified; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/utils.dart
// 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:async'; import 'dart:io'; import 'dart:collection'; /// Returns `true` if [error] is a [FileSystemException] for a missing /// directory. bool isDirectoryNotFoundException(error) { if (error is! FileSystemException) return false; // See dartbug.com/12461 and tests/standalone/io/directory_error_test.dart. var notFoundCode = Platform.operatingSystem == 'windows' ? 3 : 2; return error.osError.errorCode == notFoundCode; } /// Returns the union of all elements in each set in [sets]. Set<T> unionAll<T>(Iterable<Set<T>> sets) => sets.fold(<T>{}, (union, set) => union.union(set)); /// A stream transformer that batches all events that are sent at the same time. /// /// When multiple events are synchronously added to a stream controller, the /// [StreamController] implementation uses [scheduleMicrotask] to schedule the /// asynchronous firing of each event. In order to recreate the synchronous /// batches, this collates all the events that are received in "nearby" /// microtasks. class BatchedStreamTransformer<T> extends StreamTransformerBase<T, List<T>> { @override Stream<List<T>> bind(Stream<T> input) { var batch = Queue<T>(); return StreamTransformer<T, List<T>>.fromHandlers( handleData: (event, sink) { batch.add(event); // [Timer.run] schedules an event that runs after any microtasks that have // been scheduled. Timer.run(() { if (batch.isEmpty) return; sink.add(batch.toList()); batch.clear(); }); }, handleDone: (sink) { if (batch.isNotEmpty) { sink.add(batch.toList()); batch.clear(); } sink.close(); }).bind(input); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/resubscribable.dart
// 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:async'; import '../watcher.dart'; import 'watch_event.dart'; /// A wrapper for [ManuallyClosedWatcher] that encapsulates support for closing /// the watcher when it has no subscribers and re-opening it when it's /// re-subscribed. /// /// It's simpler to implement watchers without worrying about this behavior. /// This class wraps a watcher class which can be written with the simplifying /// assumption that it can continue emitting events until an explicit `close` /// method is called, at which point it will cease emitting events entirely. The /// [ManuallyClosedWatcher] interface is used for these watchers. /// /// This would be more cleanly implemented as a function that takes a class and /// emits a new class, but Dart doesn't support that sort of thing. Instead it /// takes a factory function that produces instances of the inner class. abstract class ResubscribableWatcher implements Watcher { /// The factory function that produces instances of the inner class. final ManuallyClosedWatcher Function() _factory; @override final String path; @override Stream<WatchEvent> get events => _eventsController.stream; StreamController<WatchEvent> _eventsController; @override bool get isReady => _readyCompleter.isCompleted; @override Future<void> get ready => _readyCompleter.future; var _readyCompleter = Completer<void>(); /// Creates a new [ResubscribableWatcher] wrapping the watchers /// emitted by [_factory]. ResubscribableWatcher(this.path, this._factory) { ManuallyClosedWatcher watcher; StreamSubscription subscription; _eventsController = StreamController<WatchEvent>.broadcast( onListen: () async { watcher = _factory(); subscription = watcher.events.listen(_eventsController.add, onError: _eventsController.addError, onDone: _eventsController.close); // It's important that we complete the value of [_readyCompleter] at // the time [onListen] is called, as opposed to the value when // [watcher.ready] fires. A new completer may be created by that time. await watcher.ready; _readyCompleter.complete(); }, onCancel: () { // Cancel the subscription before closing the watcher so that the // watcher's `onDone` event doesn't close [events]. subscription.cancel(); watcher.close(); _readyCompleter = Completer(); }, sync: true); } } /// An interface for watchers with an explicit, manual [close] method. /// /// See [ResubscribableWatcher]. abstract class ManuallyClosedWatcher implements Watcher { /// Closes the watcher. /// /// Subclasses should close their [events] stream and release any internal /// resources. void close(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/directory_watcher/linux.dart
// 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:async'; import 'dart:io'; import 'package:async/async.dart'; import '../directory_watcher.dart'; import '../path_set.dart'; import '../resubscribable.dart'; import '../utils.dart'; import '../watch_event.dart'; /// Uses the inotify subsystem to watch for filesystem events. /// /// Inotify doesn't suport recursively watching subdirectories, nor does /// [Directory.watch] polyfill that functionality. This class polyfills it /// instead. /// /// This class also compensates for the non-inotify-specific issues of /// [Directory.watch] producing multiple events for a single logical action /// (issue 14372) and providing insufficient information about move events /// (issue 14424). class LinuxDirectoryWatcher extends ResubscribableWatcher implements DirectoryWatcher { @override String get directory => path; LinuxDirectoryWatcher(String directory) : super(directory, () => _LinuxDirectoryWatcher(directory)); } class _LinuxDirectoryWatcher implements DirectoryWatcher, ManuallyClosedWatcher { @override String get directory => _files.root; @override String get path => _files.root; @override Stream<WatchEvent> get events => _eventsController.stream; final _eventsController = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _readyCompleter.isCompleted; @override Future get ready => _readyCompleter.future; final _readyCompleter = Completer(); /// A stream group for the [Directory.watch] events of [path] and all its /// subdirectories. final _nativeEvents = StreamGroup<FileSystemEvent>(); /// All known files recursively within [path]. final PathSet _files; /// [Directory.watch] streams for [path]'s subdirectories, indexed by name. /// /// A stream is in this map if and only if it's also in [_nativeEvents]. final _subdirStreams = <String, Stream<FileSystemEvent>>{}; /// A set of all subscriptions that this watcher subscribes to. /// /// These are gathered together so that they may all be canceled when the /// watcher is closed. final _subscriptions = <StreamSubscription>{}; _LinuxDirectoryWatcher(String path) : _files = PathSet(path) { _nativeEvents.add(Directory(path) .watch() .transform(StreamTransformer.fromHandlers(handleDone: (sink) { // Handle the done event here rather than in the call to [_listen] because // [innerStream] won't close until we close the [StreamGroup]. However, if // we close the [StreamGroup] here, we run the risk of new-directory // events being fired after the group is closed, since batching delays // those events. See b/30768513. _onDone(); }))); // Batch the inotify changes together so that we can dedup events. var innerStream = _nativeEvents.stream .transform(BatchedStreamTransformer<FileSystemEvent>()); _listen(innerStream, _onBatch, onError: _eventsController.addError); _listen(Directory(path).list(recursive: true), (FileSystemEntity entity) { if (entity is Directory) { _watchSubdir(entity.path); } else { _files.add(entity.path); } }, onError: (error, StackTrace stackTrace) { _eventsController.addError(error, stackTrace); close(); }, onDone: () { _readyCompleter.complete(); }, cancelOnError: true); } @override void close() { for (var subscription in _subscriptions) { subscription.cancel(); } _subscriptions.clear(); _subdirStreams.clear(); _files.clear(); _nativeEvents.close(); _eventsController.close(); } /// Watch a subdirectory of [directory] for changes. void _watchSubdir(String path) { // TODO(nweiz): Right now it's possible for the watcher to emit an event for // a file before the directory list is complete. This could lead to the user // seeing a MODIFY or REMOVE event for a file before they see an ADD event, // which is bad. We should handle that. // // One possibility is to provide a general means (e.g. // `DirectoryWatcher.eventsAndExistingFiles`) to tell a watcher to emit // events for all the files that already exist. This would be useful for // top-level clients such as barback as well, and could be implemented with // a wrapper similar to how listening/canceling works now. // TODO(nweiz): Catch any errors here that indicate that the directory in // question doesn't exist and silently stop watching it instead of // propagating the errors. var stream = Directory(path).watch(); _subdirStreams[path] = stream; _nativeEvents.add(stream); } /// The callback that's run when a batch of changes comes in. void _onBatch(List<FileSystemEvent> batch) { var files = <String>{}; var dirs = <String>{}; var changed = <String>{}; // inotify event batches are ordered by occurrence, so we treat them as a // log of what happened to a file. We only emit events based on the // difference between the state before the batch and the state after it, not // the intermediate state. for (var event in batch) { // If the watched directory is deleted or moved, we'll get a deletion // event for it. Ignore it; we handle closing [this] when the underlying // stream is closed. if (event.path == path) continue; changed.add(event.path); if (event is FileSystemMoveEvent) { files.remove(event.path); dirs.remove(event.path); changed.add(event.destination); if (event.isDirectory) { files.remove(event.destination); dirs.add(event.destination); } else { files.add(event.destination); dirs.remove(event.destination); } } else if (event is FileSystemDeleteEvent) { files.remove(event.path); dirs.remove(event.path); } else if (event.isDirectory) { files.remove(event.path); dirs.add(event.path); } else { files.add(event.path); dirs.remove(event.path); } } _applyChanges(files, dirs, changed); } /// Applies the net changes computed for a batch. /// /// The [files] and [dirs] sets contain the files and directories that now /// exist, respectively. The [changed] set contains all files and directories /// that have changed (including being removed), and so is a superset of /// [files] and [dirs]. void _applyChanges(Set<String> files, Set<String> dirs, Set<String> changed) { for (var path in changed) { var stream = _subdirStreams.remove(path); if (stream != null) _nativeEvents.add(stream); // Unless [path] was a file and still is, emit REMOVE events for it or its // contents, if (files.contains(path) && _files.contains(path)) continue; for (var file in _files.remove(path)) { _emit(ChangeType.REMOVE, file); } } for (var file in files) { if (_files.contains(file)) { _emit(ChangeType.MODIFY, file); } else { _emit(ChangeType.ADD, file); _files.add(file); } } for (var dir in dirs) { _watchSubdir(dir); _addSubdir(dir); } } /// Emits [ChangeType.ADD] events for the recursive contents of [path]. void _addSubdir(String path) { _listen(Directory(path).list(recursive: true), (FileSystemEntity entity) { if (entity is Directory) { _watchSubdir(entity.path); } else { _files.add(entity.path); _emit(ChangeType.ADD, entity.path); } }, onError: (error, StackTrace stackTrace) { // Ignore an exception caused by the dir not existing. It's fine if it // was added and then quickly removed. if (error is FileSystemException) return; _eventsController.addError(error, stackTrace); close(); }, cancelOnError: true); } /// Handles the underlying event stream closing, indicating that the directory /// being watched was removed. void _onDone() { // Most of the time when a directory is removed, its contents will get // individual REMOVE events before the watch stream is closed -- in that // case, [_files] will be empty here. However, if the directory's removal is // caused by a MOVE, we need to manually emit events. if (isReady) { for (var file in _files.paths) { _emit(ChangeType.REMOVE, file); } } close(); } /// Emits a [WatchEvent] with [type] and [path] if this watcher is in a state /// to emit events. void _emit(ChangeType type, String path) { if (!isReady) return; if (_eventsController.isClosed) return; _eventsController.add(WatchEvent(type, path)); } /// Like [Stream.listen], but automatically adds the subscription to /// [_subscriptions] so that it can be canceled when [close] is called. void _listen<T>(Stream<T> stream, void Function(T) onData, {Function onError, void Function() onDone, bool cancelOnError}) { StreamSubscription subscription; subscription = stream.listen(onData, onError: onError, onDone: () { _subscriptions.remove(subscription); onDone?.call(); }, cancelOnError: cancelOnError); _subscriptions.add(subscription); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/directory_watcher/polling.dart
// 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:async'; import 'dart:io'; import '../async_queue.dart'; import '../directory_watcher.dart'; import '../resubscribable.dart'; import '../stat.dart'; import '../utils.dart'; import '../watch_event.dart'; /// Periodically polls a directory for changes. class PollingDirectoryWatcher extends ResubscribableWatcher implements DirectoryWatcher { @override String get directory => path; /// Creates a new polling watcher monitoring [directory]. /// /// If [pollingDelay] is passed, it specifies the amount of time the watcher /// will pause between successive polls of the directory contents. Making this /// shorter will give more immediate feedback at the expense of doing more IO /// and higher CPU usage. Defaults to one second. PollingDirectoryWatcher(String directory, {Duration pollingDelay}) : super(directory, () { return _PollingDirectoryWatcher( directory, pollingDelay ?? Duration(seconds: 1)); }); } class _PollingDirectoryWatcher implements DirectoryWatcher, ManuallyClosedWatcher { @override String get directory => path; @override final String path; @override Stream<WatchEvent> get events => _events.stream; final _events = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _ready.isCompleted; @override Future<void> get ready => _ready.future; final _ready = Completer<void>(); /// The amount of time the watcher pauses between successive polls of the /// directory contents. final Duration _pollingDelay; /// The previous modification times of the files in the directory. /// /// Used to tell which files have been modified. final _lastModifieds = <String, DateTime>{}; /// The subscription used while [directory] is being listed. /// /// Will be `null` if a list is not currently happening. StreamSubscription<FileSystemEntity> _listSubscription; /// The queue of files waiting to be processed to see if they have been /// modified. /// /// Processing a file is asynchronous, as is listing the directory, so the /// queue exists to let each of those proceed at their own rate. The lister /// will enqueue files as quickly as it can. Meanwhile, files are dequeued /// and processed sequentially. AsyncQueue<String> _filesToProcess; /// The set of files that have been seen in the current directory listing. /// /// Used to tell which files have been removed: files that are in /// [_lastModifieds] but not in here when a poll completes have been removed. final _polledFiles = <String>{}; _PollingDirectoryWatcher(this.path, this._pollingDelay) { _filesToProcess = AsyncQueue<String>(_processFile, onError: (e, StackTrace stackTrace) { if (!_events.isClosed) _events.addError(e, stackTrace); }); _poll(); } @override void close() { _events.close(); // If we're in the middle of listing the directory, stop. _listSubscription?.cancel(); // Don't process any remaining files. _filesToProcess.clear(); _polledFiles.clear(); _lastModifieds.clear(); } /// Scans the contents of the directory once to see which files have been /// added, removed, and modified. void _poll() { _filesToProcess.clear(); _polledFiles.clear(); void endListing() { assert(!_events.isClosed); _listSubscription = null; // Null tells the queue consumer that we're done listing. _filesToProcess.add(null); } var stream = Directory(path).list(recursive: true); _listSubscription = stream.listen((entity) { assert(!_events.isClosed); if (entity is! File) return; _filesToProcess.add(entity.path); }, onError: (error, StackTrace stackTrace) { if (!isDirectoryNotFoundException(error)) { // It's some unknown error. Pipe it over to the event stream so the // user can see it. _events.addError(error, stackTrace); } // When an error occurs, we end the listing normally, which has the // desired effect of marking all files that were in the directory as // being removed. endListing(); }, onDone: endListing, cancelOnError: true); } /// Processes [file] to determine if it has been modified since the last /// time it was scanned. Future<void> _processFile(String file) async { // `null` is the sentinel which means the directory listing is complete. if (file == null) { await _completePoll(); return; } final modified = await modificationTime(file); if (_events.isClosed) return; var lastModified = _lastModifieds[file]; // If its modification time hasn't changed, assume the file is unchanged. if (lastModified != null && lastModified == modified) { // The file is still here. _polledFiles.add(file); return; } if (_events.isClosed) return; _lastModifieds[file] = modified; _polledFiles.add(file); // Only notify if we're ready to emit events. if (!isReady) return; var type = lastModified == null ? ChangeType.ADD : ChangeType.MODIFY; _events.add(WatchEvent(type, file)); } /// After the directory listing is complete, this determines which files were /// removed and then restarts the next poll. Future<void> _completePoll() async { // Any files that were not seen in the last poll but that we have a // status for must have been removed. var removedFiles = _lastModifieds.keys.toSet().difference(_polledFiles); for (var removed in removedFiles) { if (isReady) _events.add(WatchEvent(ChangeType.REMOVE, removed)); _lastModifieds.remove(removed); } if (!isReady) _ready.complete(); // Wait and then poll again. await Future.delayed(_pollingDelay); if (_events.isClosed) return; _poll(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/directory_watcher/windows.dart
// 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. // TODO(rnystrom): Merge with mac_os version. import 'dart:async'; import 'dart:collection'; import 'dart:io'; import 'package:path/path.dart' as p; import '../constructable_file_system_event.dart'; import '../directory_watcher.dart'; import '../path_set.dart'; import '../resubscribable.dart'; import '../utils.dart'; import '../watch_event.dart'; class WindowsDirectoryWatcher extends ResubscribableWatcher implements DirectoryWatcher { @override String get directory => path; WindowsDirectoryWatcher(String directory) : super(directory, () => _WindowsDirectoryWatcher(directory)); } class _EventBatcher { static const Duration _BATCH_DELAY = Duration(milliseconds: 100); final List<FileSystemEvent> events = []; Timer timer; void addEvent(FileSystemEvent event, void Function() callback) { events.add(event); timer?.cancel(); timer = Timer(_BATCH_DELAY, callback); } void cancelTimer() { timer.cancel(); } } class _WindowsDirectoryWatcher implements DirectoryWatcher, ManuallyClosedWatcher { @override String get directory => path; @override final String path; @override Stream<WatchEvent> get events => _eventsController.stream; final _eventsController = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _readyCompleter.isCompleted; @override Future<void> get ready => _readyCompleter.future; final _readyCompleter = Completer(); final Map<String, _EventBatcher> _eventBatchers = HashMap<String, _EventBatcher>(); /// The set of files that are known to exist recursively within the watched /// directory. /// /// The state of files on the filesystem is compared against this to determine /// the real change that occurred. This is also used to emit REMOVE events /// when subdirectories are moved out of the watched directory. final PathSet _files; /// The subscription to the stream returned by [Directory.watch]. StreamSubscription<FileSystemEvent> _watchSubscription; /// The subscription to the stream returned by [Directory.watch] of the /// parent directory to [directory]. This is needed to detect changes to /// [directory], as they are not included on Windows. StreamSubscription<FileSystemEvent> _parentWatchSubscription; /// The subscription to the [Directory.list] call for the initial listing of /// the directory to determine its initial state. StreamSubscription<FileSystemEntity> _initialListSubscription; /// The subscriptions to the [Directory.list] calls for listing the contents /// of subdirectories that were moved into the watched directory. final Set<StreamSubscription<FileSystemEntity>> _listSubscriptions = HashSet<StreamSubscription<FileSystemEntity>>(); _WindowsDirectoryWatcher(String path) : path = path, _files = PathSet(path) { // Before we're ready to emit events, wait for [_listDir] to complete. _listDir().then((_) { _startWatch(); _startParentWatcher(); _readyCompleter.complete(); }); } @override void close() { _watchSubscription?.cancel(); _parentWatchSubscription?.cancel(); _initialListSubscription?.cancel(); for (var sub in _listSubscriptions) { sub.cancel(); } _listSubscriptions.clear(); for (var batcher in _eventBatchers.values) { batcher.cancelTimer(); } _eventBatchers.clear(); _watchSubscription = null; _parentWatchSubscription = null; _initialListSubscription = null; _eventsController.close(); } /// On Windows, if [directory] is deleted, we will not receive any event. /// /// Instead, we add a watcher on the parent folder (if any), that can notify /// us about [path]. This also includes events such as moves. void _startParentWatcher() { var absoluteDir = p.absolute(path); var parent = p.dirname(absoluteDir); // Check if [path] is already the root directory. if (FileSystemEntity.identicalSync(parent, path)) return; var parentStream = Directory(parent).watch(recursive: false); _parentWatchSubscription = parentStream.listen((event) { // Only look at events for 'directory'. if (p.basename(event.path) != p.basename(absoluteDir)) return; // Test if the directory is removed. FileSystemEntity.typeSync will // return NOT_FOUND if it's unable to decide upon the type, including // access denied issues, which may happen when the directory is deleted. // FileSystemMoveEvent and FileSystemDeleteEvent events will always mean // the directory is now gone. if (event is FileSystemMoveEvent || event is FileSystemDeleteEvent || (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound)) { for (var path in _files.paths) { _emitEvent(ChangeType.REMOVE, path); } _files.clear(); close(); } }, onError: (error) { // Ignore errors, simply close the stream. The user listens on // [directory], and while it can fail to listen on the parent, we may // still be able to listen on the path requested. _parentWatchSubscription.cancel(); _parentWatchSubscription = null; }); } void _onEvent(FileSystemEvent event) { assert(isReady); final batcher = _eventBatchers.putIfAbsent(event.path, () => _EventBatcher()); batcher.addEvent(event, () { _eventBatchers.remove(event.path); _onBatch(batcher.events); }); } /// The callback that's run when [Directory.watch] emits a batch of events. void _onBatch(List<FileSystemEvent> batch) { _sortEvents(batch).forEach((path, eventSet) { var canonicalEvent = _canonicalEvent(eventSet); var events = canonicalEvent == null ? _eventsBasedOnFileSystem(path) : [canonicalEvent]; for (var event in events) { if (event is FileSystemCreateEvent) { if (!event.isDirectory) { if (_files.contains(path)) continue; _emitEvent(ChangeType.ADD, path); _files.add(path); continue; } if (_files.containsDir(path)) continue; var stream = Directory(path).list(recursive: true); StreamSubscription<FileSystemEntity> subscription; subscription = stream.listen((entity) { if (entity is Directory) return; if (_files.contains(path)) return; _emitEvent(ChangeType.ADD, entity.path); _files.add(entity.path); }, onDone: () { _listSubscriptions.remove(subscription); }, onError: (e, StackTrace stackTrace) { _listSubscriptions.remove(subscription); _emitError(e, stackTrace); }, cancelOnError: true); _listSubscriptions.add(subscription); } else if (event is FileSystemModifyEvent) { if (!event.isDirectory) { _emitEvent(ChangeType.MODIFY, path); } } else { assert(event is FileSystemDeleteEvent); for (var removedPath in _files.remove(path)) { _emitEvent(ChangeType.REMOVE, removedPath); } } } }); } /// Sort all the events in a batch into sets based on their path. /// /// A single input event may result in multiple events in the returned map; /// for example, a MOVE event becomes a DELETE event for the source and a /// CREATE event for the destination. /// /// The returned events won't contain any [FileSystemMoveEvent]s, nor will it /// contain any events relating to [path]. Map<String, Set<FileSystemEvent>> _sortEvents(List<FileSystemEvent> batch) { var eventsForPaths = <String, Set<FileSystemEvent>>{}; // Events within directories that already have events are superfluous; the // directory's full contents will be examined anyway, so we ignore such // events. Emitting them could cause useless or out-of-order events. var directories = unionAll(batch.map((event) { if (!event.isDirectory) return <String>{}; if (event is FileSystemMoveEvent) { return {event.path, event.destination}; } return {event.path}; })); bool isInModifiedDirectory(String path) => directories.any((dir) => path != dir && p.isWithin(dir, path)); void addEvent(String path, FileSystemEvent event) { if (isInModifiedDirectory(path)) return; eventsForPaths.putIfAbsent(path, () => <FileSystemEvent>{}).add(event); } for (var event in batch) { if (event is FileSystemMoveEvent) { addEvent(event.destination, event); } addEvent(event.path, event); } return eventsForPaths; } /// Returns the canonical event from a batch of events on the same path, if /// one exists. /// /// If [batch] doesn't contain any contradictory events (e.g. DELETE and /// CREATE, or events with different values for `isDirectory`), this returns a /// single event that describes what happened to the path in question. /// /// If [batch] does contain contradictory events, this returns `null` to /// indicate that the state of the path on the filesystem should be checked to /// determine what occurred. FileSystemEvent _canonicalEvent(Set<FileSystemEvent> batch) { // An empty batch indicates that we've learned earlier that the batch is // contradictory (e.g. because of a move). if (batch.isEmpty) return null; var type = batch.first.type; var isDir = batch.first.isDirectory; for (var event in batch.skip(1)) { // If one event reports that the file is a directory and another event // doesn't, that's a contradiction. if (isDir != event.isDirectory) return null; // Modify events don't contradict either CREATE or REMOVE events. We can // safely assume the file was modified after a CREATE or before the // REMOVE; otherwise there will also be a REMOVE or CREATE event // (respectively) that will be contradictory. if (event is FileSystemModifyEvent) continue; assert(event is FileSystemCreateEvent || event is FileSystemDeleteEvent || event is FileSystemMoveEvent); // If we previously thought this was a MODIFY, we now consider it to be a // CREATE or REMOVE event. This is safe for the same reason as above. if (type == FileSystemEvent.modify) { type = event.type; continue; } // A CREATE event contradicts a REMOVE event and vice versa. assert(type == FileSystemEvent.create || type == FileSystemEvent.delete || type == FileSystemEvent.move); if (type != event.type) return null; } switch (type) { case FileSystemEvent.create: return ConstructableFileSystemCreateEvent(batch.first.path, isDir); case FileSystemEvent.delete: return ConstructableFileSystemDeleteEvent(batch.first.path, isDir); case FileSystemEvent.modify: return ConstructableFileSystemModifyEvent( batch.first.path, isDir, false); case FileSystemEvent.move: return null; default: throw 'unreachable'; } } /// Returns zero or more events that describe the change between the last /// known state of [path] and its current state on the filesystem. /// /// This returns a list whose order should be reflected in the events emitted /// to the user, unlike the batched events from [Directory.watch]. The /// returned list may be empty, indicating that no changes occurred to [path] /// (probably indicating that it was created and then immediately deleted). List<FileSystemEvent> _eventsBasedOnFileSystem(String path) { var fileExisted = _files.contains(path); var dirExisted = _files.containsDir(path); bool fileExists; bool dirExists; try { fileExists = File(path).existsSync(); dirExists = Directory(path).existsSync(); } on FileSystemException { return const <FileSystemEvent>[]; } var events = <FileSystemEvent>[]; if (fileExisted) { if (fileExists) { events.add(ConstructableFileSystemModifyEvent(path, false, false)); } else { events.add(ConstructableFileSystemDeleteEvent(path, false)); } } else if (dirExisted) { if (dirExists) { // If we got contradictory events for a directory that used to exist and // still exists, we need to rescan the whole thing in case it was // replaced with a different directory. events.add(ConstructableFileSystemDeleteEvent(path, true)); events.add(ConstructableFileSystemCreateEvent(path, true)); } else { events.add(ConstructableFileSystemDeleteEvent(path, true)); } } if (!fileExisted && fileExists) { events.add(ConstructableFileSystemCreateEvent(path, false)); } else if (!dirExisted && dirExists) { events.add(ConstructableFileSystemCreateEvent(path, true)); } return events; } /// The callback that's run when the [Directory.watch] stream is closed. /// Note that this is unlikely to happen on Windows, unless the system itself /// closes the handle. void _onDone() { _watchSubscription = null; // Emit remove events for any remaining files. for (var file in _files.paths) { _emitEvent(ChangeType.REMOVE, file); } _files.clear(); close(); } /// Start or restart the underlying [Directory.watch] stream. void _startWatch() { // Note: "watcher closed" exceptions do not get sent over the stream // returned by watch, and must be caught via a zone handler. runZoned(() { var innerStream = Directory(path).watch(recursive: true); _watchSubscription = innerStream.listen(_onEvent, onError: _eventsController.addError, onDone: _onDone); }, onError: (error, StackTrace stackTrace) { if (error is FileSystemException && error.message.startsWith('Directory watcher closed unexpectedly')) { _watchSubscription.cancel(); _eventsController.addError(error, stackTrace); _startWatch(); } else { throw error; } }); } /// Starts or restarts listing the watched directory to get an initial picture /// of its state. Future<void> _listDir() { assert(!isReady); _initialListSubscription?.cancel(); _files.clear(); var completer = Completer(); var stream = Directory(path).list(recursive: true); void handleEntity(FileSystemEntity entity) { if (entity is! Directory) _files.add(entity.path); } _initialListSubscription = stream.listen(handleEntity, onError: _emitError, onDone: completer.complete, cancelOnError: true); return completer.future; } /// Emit an event with the given [type] and [path]. void _emitEvent(ChangeType type, String path) { if (!isReady) return; _eventsController.add(WatchEvent(type, path)); } /// Emit an error, then close the watcher. void _emitError(error, StackTrace stackTrace) { _eventsController.addError(error, stackTrace); close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/directory_watcher/mac_os.dart
// 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:async'; import 'dart:io'; import 'package:path/path.dart' as p; import '../directory_watcher.dart'; import '../constructable_file_system_event.dart'; import '../path_set.dart'; import '../resubscribable.dart'; import '../utils.dart'; import '../watch_event.dart'; /// Uses the FSEvents subsystem to watch for filesystem events. /// /// FSEvents has two main idiosyncrasies that this class works around. First, it /// will occasionally report events that occurred before the filesystem watch /// was initiated. Second, if multiple events happen to the same file in close /// succession, it won't report them in the order they occurred. See issue /// 14373. /// /// This also works around issues 16003 and 14849 in the implementation of /// [Directory.watch]. class MacOSDirectoryWatcher extends ResubscribableWatcher implements DirectoryWatcher { @override String get directory => path; MacOSDirectoryWatcher(String directory) : super(directory, () => _MacOSDirectoryWatcher(directory)); } class _MacOSDirectoryWatcher implements DirectoryWatcher, ManuallyClosedWatcher { @override String get directory => path; @override final String path; @override Stream<WatchEvent> get events => _eventsController.stream; final _eventsController = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _readyCompleter.isCompleted; @override Future get ready => _readyCompleter.future; final _readyCompleter = Completer(); /// The set of files that are known to exist recursively within the watched /// directory. /// /// The state of files on the filesystem is compared against this to determine /// the real change that occurred when working around issue 14373. This is /// also used to emit REMOVE events when subdirectories are moved out of the /// watched directory. final PathSet _files; /// The subscription to the stream returned by [Directory.watch]. /// /// This is separate from [_listSubscriptions] because this stream /// occasionally needs to be resubscribed in order to work around issue 14849. StreamSubscription<List<FileSystemEvent>> _watchSubscription; /// The subscription to the [Directory.list] call for the initial listing of /// the directory to determine its initial state. StreamSubscription<FileSystemEntity> _initialListSubscription; /// The subscriptions to [Directory.list] calls for listing the contents of a /// subdirectory that was moved into the watched directory. final _listSubscriptions = <StreamSubscription<FileSystemEntity>>{}; /// The timer for tracking how long we wait for an initial batch of bogus /// events (see issue 14373). Timer _bogusEventTimer; _MacOSDirectoryWatcher(String path) : path = path, _files = PathSet(path) { _startWatch(); // Before we're ready to emit events, wait for [_listDir] to complete and // for enough time to elapse that if bogus events (issue 14373) would be // emitted, they will be. // // If we do receive a batch of events, [_onBatch] will ensure that these // futures don't fire and that the directory is re-listed. Future.wait([_listDir(), _waitForBogusEvents()]) .then((_) => _readyCompleter.complete()); } @override void close() { _watchSubscription?.cancel(); _initialListSubscription?.cancel(); _watchSubscription = null; _initialListSubscription = null; for (var subscription in _listSubscriptions) { subscription.cancel(); } _listSubscriptions.clear(); _eventsController.close(); } /// The callback that's run when [Directory.watch] emits a batch of events. void _onBatch(List<FileSystemEvent> batch) { // If we get a batch of events before we're ready to begin emitting events, // it's probable that it's a batch of pre-watcher events (see issue 14373). // Ignore those events and re-list the directory. if (!isReady) { // Cancel the timer because bogus events only occur in the first batch, so // we can fire [ready] as soon as we're done listing the directory. _bogusEventTimer.cancel(); _listDir().then((_) => _readyCompleter.complete()); return; } _sortEvents(batch).forEach((path, eventSet) { var canonicalEvent = _canonicalEvent(eventSet); var events = canonicalEvent == null ? _eventsBasedOnFileSystem(path) : [canonicalEvent]; for (var event in events) { if (event is FileSystemCreateEvent) { if (!event.isDirectory) { // If we already know about the file, treat it like a modification. // This can happen if a file is copied on top of an existing one. // We'll see an ADD event for the latter file when from the user's // perspective, the file's contents just changed. var type = _files.contains(path) ? ChangeType.MODIFY : ChangeType.ADD; _emitEvent(type, path); _files.add(path); continue; } if (_files.containsDir(path)) continue; StreamSubscription<FileSystemEntity> subscription; subscription = Directory(path).list(recursive: true).listen((entity) { if (entity is Directory) return; if (_files.contains(path)) return; _emitEvent(ChangeType.ADD, entity.path); _files.add(entity.path); }, onError: (e, StackTrace stackTrace) { _emitError(e, stackTrace); }, onDone: () { _listSubscriptions.remove(subscription); }, cancelOnError: true); _listSubscriptions.add(subscription); } else if (event is FileSystemModifyEvent) { assert(!event.isDirectory); _emitEvent(ChangeType.MODIFY, path); } else { assert(event is FileSystemDeleteEvent); for (var removedPath in _files.remove(path)) { _emitEvent(ChangeType.REMOVE, removedPath); } } } }); } /// Sort all the events in a batch into sets based on their path. /// /// A single input event may result in multiple events in the returned map; /// for example, a MOVE event becomes a DELETE event for the source and a /// CREATE event for the destination. /// /// The returned events won't contain any [FileSystemMoveEvent]s, nor will it /// contain any events relating to [path]. Map<String, Set<FileSystemEvent>> _sortEvents(List<FileSystemEvent> batch) { var eventsForPaths = <String, Set<FileSystemEvent>>{}; // FSEvents can report past events, including events on the root directory // such as it being created. We want to ignore these. If the directory is // really deleted, that's handled by [_onDone]. batch = batch.where((event) => event.path != path).toList(); // Events within directories that already have events are superfluous; the // directory's full contents will be examined anyway, so we ignore such // events. Emitting them could cause useless or out-of-order events. var directories = unionAll(batch.map((event) { if (!event.isDirectory) return <String>{}; if (event is FileSystemMoveEvent) { return {event.path, event.destination}; } return {event.path}; })); bool isInModifiedDirectory(String path) => directories.any((dir) => path != dir && p.isWithin(dir, path)); void addEvent(String path, FileSystemEvent event) { if (isInModifiedDirectory(path)) return; eventsForPaths.putIfAbsent(path, () => <FileSystemEvent>{}).add(event); } for (var event in batch) { // The Mac OS watcher doesn't emit move events. See issue 14806. assert(event is! FileSystemMoveEvent); addEvent(event.path, event); } return eventsForPaths; } /// Returns the canonical event from a batch of events on the same path, if /// one exists. /// /// If [batch] doesn't contain any contradictory events (e.g. DELETE and /// CREATE, or events with different values for `isDirectory`), this returns a /// single event that describes what happened to the path in question. /// /// If [batch] does contain contradictory events, this returns `null` to /// indicate that the state of the path on the filesystem should be checked to /// determine what occurred. FileSystemEvent _canonicalEvent(Set<FileSystemEvent> batch) { // An empty batch indicates that we've learned earlier that the batch is // contradictory (e.g. because of a move). if (batch.isEmpty) return null; var type = batch.first.type; var isDir = batch.first.isDirectory; var hadModifyEvent = false; for (var event in batch.skip(1)) { // If one event reports that the file is a directory and another event // doesn't, that's a contradiction. if (isDir != event.isDirectory) return null; // Modify events don't contradict either CREATE or REMOVE events. We can // safely assume the file was modified after a CREATE or before the // REMOVE; otherwise there will also be a REMOVE or CREATE event // (respectively) that will be contradictory. if (event is FileSystemModifyEvent) { hadModifyEvent = true; continue; } assert(event is FileSystemCreateEvent || event is FileSystemDeleteEvent); // If we previously thought this was a MODIFY, we now consider it to be a // CREATE or REMOVE event. This is safe for the same reason as above. if (type == FileSystemEvent.modify) { type = event.type; continue; } // A CREATE event contradicts a REMOVE event and vice versa. assert(type == FileSystemEvent.create || type == FileSystemEvent.delete); if (type != event.type) return null; } // If we got a CREATE event for a file we already knew about, that comes // from FSEvents reporting an add that happened prior to the watch // beginning. If we also received a MODIFY event, we want to report that, // but not the CREATE. if (type == FileSystemEvent.create && hadModifyEvent && _files.contains(batch.first.path)) { type = FileSystemEvent.modify; } switch (type) { case FileSystemEvent.create: // Issue 16003 means that a CREATE event for a directory can indicate // that the directory was moved and then re-created. // [_eventsBasedOnFileSystem] will handle this correctly by producing a // DELETE event followed by a CREATE event if the directory exists. if (isDir) return null; return ConstructableFileSystemCreateEvent(batch.first.path, false); case FileSystemEvent.delete: return ConstructableFileSystemDeleteEvent(batch.first.path, isDir); case FileSystemEvent.modify: return ConstructableFileSystemModifyEvent( batch.first.path, isDir, false); default: throw 'unreachable'; } } /// Returns one or more events that describe the change between the last known /// state of [path] and its current state on the filesystem. /// /// This returns a list whose order should be reflected in the events emitted /// to the user, unlike the batched events from [Directory.watch]. The /// returned list may be empty, indicating that no changes occurred to [path] /// (probably indicating that it was created and then immediately deleted). List<FileSystemEvent> _eventsBasedOnFileSystem(String path) { var fileExisted = _files.contains(path); var dirExisted = _files.containsDir(path); var fileExists = File(path).existsSync(); var dirExists = Directory(path).existsSync(); var events = <FileSystemEvent>[]; if (fileExisted) { if (fileExists) { events.add(ConstructableFileSystemModifyEvent(path, false, false)); } else { events.add(ConstructableFileSystemDeleteEvent(path, false)); } } else if (dirExisted) { if (dirExists) { // If we got contradictory events for a directory that used to exist and // still exists, we need to rescan the whole thing in case it was // replaced with a different directory. events.add(ConstructableFileSystemDeleteEvent(path, true)); events.add(ConstructableFileSystemCreateEvent(path, true)); } else { events.add(ConstructableFileSystemDeleteEvent(path, true)); } } if (!fileExisted && fileExists) { events.add(ConstructableFileSystemCreateEvent(path, false)); } else if (!dirExisted && dirExists) { events.add(ConstructableFileSystemCreateEvent(path, true)); } return events; } /// The callback that's run when the [Directory.watch] stream is closed. void _onDone() { _watchSubscription = null; // If the directory still exists and we're still expecting bogus events, // this is probably issue 14849 rather than a real close event. We should // just restart the watcher. if (!isReady && Directory(path).existsSync()) { _startWatch(); return; } // FSEvents can fail to report the contents of the directory being removed // when the directory itself is removed, so we need to manually mark the // files as removed. for (var file in _files.paths) { _emitEvent(ChangeType.REMOVE, file); } _files.clear(); close(); } /// Start or restart the underlying [Directory.watch] stream. void _startWatch() { // Batch the FSEvent changes together so that we can dedup events. var innerStream = Directory(path) .watch(recursive: true) .transform(BatchedStreamTransformer<FileSystemEvent>()); _watchSubscription = innerStream.listen(_onBatch, onError: _eventsController.addError, onDone: _onDone); } /// Starts or restarts listing the watched directory to get an initial picture /// of its state. Future _listDir() { assert(!isReady); _initialListSubscription?.cancel(); _files.clear(); var completer = Completer(); var stream = Directory(path).list(recursive: true); _initialListSubscription = stream.listen((entity) { if (entity is! Directory) _files.add(entity.path); }, onError: _emitError, onDone: completer.complete, cancelOnError: true); return completer.future; } /// Wait 200ms for a batch of bogus events (issue 14373) to come in. /// /// 200ms is short in terms of human interaction, but longer than any Mac OS /// watcher tests take on the bots, so it should be safe to assume that any /// bogus events will be signaled in that time frame. Future _waitForBogusEvents() { var completer = Completer(); _bogusEventTimer = Timer(Duration(milliseconds: 200), completer.complete); return completer.future; } /// Emit an event with the given [type] and [path]. void _emitEvent(ChangeType type, String path) { if (!isReady) return; _eventsController.add(WatchEvent(type, path)); } /// Emit an error, then close the watcher. void _emitError(error, StackTrace stackTrace) { _eventsController.addError(error, stackTrace); close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/file_watcher/native.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import '../file_watcher.dart'; import '../resubscribable.dart'; import '../utils.dart'; import '../watch_event.dart'; /// Uses the native file system notifications to watch for filesystem events. /// /// Single-file notifications are much simpler than those for multiple files, so /// this doesn't need to be split out into multiple OS-specific classes. class NativeFileWatcher extends ResubscribableWatcher implements FileWatcher { NativeFileWatcher(String path) : super(path, () => _NativeFileWatcher(path)); } class _NativeFileWatcher implements FileWatcher, ManuallyClosedWatcher { @override final String path; @override Stream<WatchEvent> get events => _eventsController.stream; final _eventsController = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _readyCompleter.isCompleted; @override Future get ready => _readyCompleter.future; final _readyCompleter = Completer(); StreamSubscription _subscription; _NativeFileWatcher(this.path) { _listen(); // We don't need to do any initial set-up, so we're ready immediately after // being listened to. _readyCompleter.complete(); } void _listen() { // Batch the events together so that we can dedup them. _subscription = File(path) .watch() .transform(BatchedStreamTransformer<FileSystemEvent>()) .listen(_onBatch, onError: _eventsController.addError, onDone: _onDone); } void _onBatch(List<FileSystemEvent> batch) { if (batch.any((event) => event.type == FileSystemEvent.delete)) { // If the file is deleted, the underlying stream will close. We handle // emitting our own REMOVE event in [_onDone]. return; } _eventsController.add(WatchEvent(ChangeType.MODIFY, path)); } void _onDone() async { var fileExists = await File(path).exists(); // Check for this after checking whether the file exists because it's // possible that [close] was called between [File.exists] being called and // it completing. if (_eventsController.isClosed) return; if (fileExists) { // If the file exists now, it was probably removed and quickly replaced; // this can happen for example when another file is moved on top of it. // Re-subscribe and report a modify event. _eventsController.add(WatchEvent(ChangeType.MODIFY, path)); _listen(); } else { _eventsController.add(WatchEvent(ChangeType.REMOVE, path)); close(); } } @override void close() { _subscription?.cancel(); _subscription = null; _eventsController.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/watcher/src/file_watcher/polling.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:pedantic/pedantic.dart'; import '../file_watcher.dart'; import '../resubscribable.dart'; import '../stat.dart'; import '../watch_event.dart'; /// Periodically polls a file for changes. class PollingFileWatcher extends ResubscribableWatcher implements FileWatcher { PollingFileWatcher(String path, {Duration pollingDelay}) : super(path, () { return _PollingFileWatcher( path, pollingDelay ?? Duration(seconds: 1)); }); } class _PollingFileWatcher implements FileWatcher, ManuallyClosedWatcher { @override final String path; @override Stream<WatchEvent> get events => _eventsController.stream; final _eventsController = StreamController<WatchEvent>.broadcast(); @override bool get isReady => _readyCompleter.isCompleted; @override Future get ready => _readyCompleter.future; final _readyCompleter = Completer(); /// The timer that controls polling. Timer _timer; /// The previous modification time of the file. /// /// Used to tell when the file was modified. This is `null` before the file's /// mtime has first been checked. DateTime _lastModified; _PollingFileWatcher(this.path, Duration pollingDelay) { _timer = Timer.periodic(pollingDelay, (_) => _poll()); _poll(); } /// Checks the mtime of the file and whether it's been removed. Future _poll() async { // We don't mark the file as removed if this is the first poll (indicated by // [_lastModified] being null). Instead, below we forward the dart:io error // that comes from trying to read the mtime below. var pathExists = await File(path).exists(); if (_eventsController.isClosed) return; if (_lastModified != null && !pathExists) { _eventsController.add(WatchEvent(ChangeType.REMOVE, path)); unawaited(close()); return; } DateTime modified; try { modified = await modificationTime(path); } on FileSystemException catch (error, stackTrace) { if (!_eventsController.isClosed) { _eventsController.addError(error, stackTrace); await close(); } } if (_eventsController.isClosed) return; if (_lastModified == modified) return; if (_lastModified == null) { // If this is the first poll, don't emit an event, just set the last mtime // and complete the completer. _lastModified = modified; _readyCompleter.complete(); } else { _lastModified = modified; _eventsController.add(WatchEvent(ChangeType.MODIFY, path)); } } @override Future<void> close() async { _timer.cancel(); await _eventsController.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/build_runner.dart
// 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. export 'src/daemon/constants.dart' show assetServerPort; export 'src/entrypoint/run.dart' show run;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/build_script_generate.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/build_script_generate/build_script_generate.dart' show generateBuildScript, scriptLocation;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/daemon/asset_server.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:http_multi_server/http_multi_server.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import '../server/server.dart'; import 'daemon_builder.dart'; class AssetServer { final HttpServer _server; AssetServer._(this._server); int get port => _server.port; Future<void> stop() => _server.close(force: true); static Future<AssetServer> run( BuildRunnerDaemonBuilder builder, String rootPackage, ) async { var server = await HttpMultiServer.loopback(0); var cascade = Cascade().add((_) async { await builder.building; return Response.notFound(''); }).add(AssetHandler(builder.reader, rootPackage).handle); shelf_io.serveRequests(server, cascade.handler); return AssetServer._(server); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/daemon/constants.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:build_daemon/constants.dart'; import 'package:path/path.dart' as p; String assetServerPortFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.asset_server_port'); /// Returns the port of the daemon asset server. int assetServerPort(String workingDirectory) { var portFile = File(assetServerPortFilePath(workingDirectory)); if (!portFile.existsSync()) { throw Exception('Unable to read daemon asset port file.'); } return int.parse(portFile.readAsStringSync()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/daemon/daemon_builder.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:build_daemon/change_provider.dart'; import 'package:build_daemon/constants.dart'; import 'package:build_daemon/daemon_builder.dart'; import 'package:build_daemon/data/build_status.dart'; import 'package:build_daemon/data/build_target.dart' hide OutputLocation; import 'package:build_daemon/data/server_log.dart'; import 'package:build_runner/src/entrypoint/options.dart'; import 'package:build_runner/src/package_graph/build_config_overrides.dart'; import 'package:build_runner/src/watcher/asset_change.dart'; import 'package:build_runner/src/watcher/change_filter.dart'; import 'package:build_runner/src/watcher/collect_changes.dart'; import 'package:build_runner/src/watcher/delete_writer.dart'; import 'package:build_runner/src/watcher/graph_watcher.dart'; import 'package:build_runner/src/watcher/node_watcher.dart'; import 'package:build_runner_core/build_runner_core.dart' hide BuildResult, BuildStatus; import 'package:build_runner_core/build_runner_core.dart' as core show BuildStatus; import 'package:build_runner_core/src/generate/build_definition.dart'; import 'package:build_runner_core/src/generate/build_impl.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:watcher/watcher.dart'; import 'change_providers.dart'; /// A Daemon Builder that uses build_runner_core for building. class BuildRunnerDaemonBuilder implements DaemonBuilder { final _buildResults = StreamController<BuildResults>(); final BuildImpl _builder; final BuildOptions _buildOptions; final StreamController<ServerLog> _outputStreamController; final ChangeProvider changeProvider; Completer<Null> _buildingCompleter; @override final Stream<ServerLog> logs; BuildRunnerDaemonBuilder._( this._builder, this._buildOptions, this._outputStreamController, this.changeProvider, ) : logs = _outputStreamController.stream.asBroadcastStream(); /// Waits for a running build to complete before returning. /// /// If there is no running build, it will return immediately. Future<void> get building => _buildingCompleter?.future; @override Stream<BuildResults> get builds => _buildResults.stream; FinalizedReader get reader => _builder.finalizedReader; final _buildScriptUpdateCompleter = Completer(); Future<void> get buildScriptUpdated => _buildScriptUpdateCompleter.future; @override Future<void> build( Set<BuildTarget> targets, Iterable<WatchEvent> fileChanges) async { var defaultTargets = targets.cast<DefaultBuildTarget>(); var changes = fileChanges .map<AssetChange>( (change) => AssetChange(AssetId.parse(change.path), change.type)) .toList(); if (!_buildOptions.skipBuildScriptCheck && _builder.buildScriptUpdates.hasBeenUpdated( changes.map<AssetId>((change) => change.id).toSet())) { _buildScriptUpdateCompleter.complete(); return; } var targetNames = targets.map((t) => t.target).toSet(); _logMessage(Level.INFO, 'About to build ${targetNames.toList()}...'); _signalStart(targetNames); var results = <BuildResult>[]; var buildDirs = <BuildDirectory>{}; var buildFilters = <BuildFilter>{}; for (var target in defaultTargets) { OutputLocation outputLocation; if (target.outputLocation != null) { outputLocation = OutputLocation(target.outputLocation.output, useSymlinks: target.outputLocation.useSymlinks, hoist: target.outputLocation.hoist); } buildDirs .add(BuildDirectory(target.target, outputLocation: outputLocation)); if (target.buildFilters != null && target.buildFilters.isNotEmpty) { buildFilters.addAll([ for (var pattern in target.buildFilters) BuildFilter.fromArg(pattern, _buildOptions.packageGraph.root.name) ]); } else { buildFilters ..add(BuildFilter.fromArg( 'package:*/**', _buildOptions.packageGraph.root.name)) ..add(BuildFilter.fromArg( '${target.target}/**', _buildOptions.packageGraph.root.name)); } } try { var mergedChanges = collectChanges([changes]); var result = await _builder.run(mergedChanges, buildDirs: buildDirs, buildFilters: buildFilters); for (var target in targets) { if (result.status == core.BuildStatus.success) { // TODO(grouma) - Can we notify if a target was cached? results.add(DefaultBuildResult((b) => b ..status = BuildStatus.succeeded ..target = target.target)); } else { results.add(DefaultBuildResult((b) => b ..status = BuildStatus.failed // TODO(grouma) - We should forward the error messages instead. // We can use the AssetGraph and FailureReporter to provide a better // error message. ..error = 'FailureType: ${result.failureType.exitCode}' ..target = target.target)); } } } catch (e) { for (var target in targets) { results.add(DefaultBuildResult((b) => b ..status = BuildStatus.failed ..error = '$e' ..target = target.target)); } _logMessage(Level.SEVERE, 'Build Failed:\n${e.toString()}'); } _signalEnd(results); } @override Future<void> stop() async { await _builder.beforeExit(); await _buildOptions.logListener.cancel(); } void _logMessage(Level level, String message) => _outputStreamController.add(ServerLog( (b) => b ..message = message ..level = level, )); void _signalEnd(Iterable<BuildResult> results) { _buildingCompleter.complete(); _buildResults.add(BuildResults((b) => b..results.addAll(results))); } void _signalStart(Iterable<String> targets) { _buildingCompleter = Completer(); var results = <BuildResult>[]; for (var target in targets) { results.add(DefaultBuildResult((b) => b ..status = BuildStatus.started ..target = target)); } _buildResults.add(BuildResults((b) => b..results.addAll(results))); } static Future<BuildRunnerDaemonBuilder> create( PackageGraph packageGraph, List<BuilderApplication> builders, DaemonOptions daemonOptions, ) async { var expectedDeletes = <AssetId>{}; var outputStreamController = StreamController<ServerLog>(); var environment = OverrideableEnvironment( IOEnvironment(packageGraph, outputSymlinksOnly: daemonOptions.outputSymlinksOnly), onLog: (record) { outputStreamController.add(ServerLog.fromLogRecord(record)); }); var daemonEnvironment = OverrideableEnvironment(environment, writer: OnDeleteWriter(environment.writer, expectedDeletes.add)); var logSubscription = LogSubscription(environment, verbose: daemonOptions.verbose); var overrideBuildConfig = await findBuildConfigOverrides(packageGraph, daemonOptions.configKey); var buildOptions = await BuildOptions.create( logSubscription, packageGraph: packageGraph, deleteFilesByDefault: daemonOptions.deleteFilesByDefault, overrideBuildConfig: overrideBuildConfig, skipBuildScriptCheck: daemonOptions.skipBuildScriptCheck, enableLowResourcesMode: daemonOptions.enableLowResourcesMode, trackPerformance: daemonOptions.trackPerformance, logPerformanceDir: daemonOptions.logPerformanceDir, ); var builder = await BuildImpl.create(buildOptions, daemonEnvironment, builders, daemonOptions.builderConfigOverrides, isReleaseBuild: daemonOptions.isReleaseBuild); // Only actually used for the AutoChangeProvider. Stream<List<WatchEvent>> graphEvents() => PackageGraphWatcher(packageGraph, watch: (node) => PackageNodeWatcher(node, watch: daemonOptions.directoryWatcherFactory)) .watch() .asyncWhere((change) => shouldProcess( change, builder.assetGraph, buildOptions, // Assume we will create an outputDir. true, expectedDeletes, environment.reader, )) .map((data) => WatchEvent(data.type, '${data.id}')) .debounceBuffer(buildOptions.debounceDelay); var changeProvider = daemonOptions.buildMode == BuildMode.Auto ? AutoChangeProvider(graphEvents()) : ManualChangeProvider(AssetTracker(builder.assetGraph, daemonEnvironment.reader, buildOptions.targetGraph)); return BuildRunnerDaemonBuilder._( builder, buildOptions, outputStreamController, changeProvider); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/daemon/change_providers.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build_daemon/change_provider.dart'; import 'package:build_runner_core/src/generate/build_definition.dart'; import 'package:watcher/src/watch_event.dart'; /// Continually updates the [changes] stream as watch events are seen on the /// input stream. /// /// The [collectChanges] method is a no-op for this implementation. class AutoChangeProvider implements ChangeProvider { @override final Stream<List<WatchEvent>> changes; AutoChangeProvider(this.changes); @override Future<List<WatchEvent>> collectChanges() async => []; } /// Computes changes with a file scan when requested by a call to /// [collectChanges]. class ManualChangeProvider implements ChangeProvider { final AssetTracker _assetTracker; ManualChangeProvider(this._assetTracker); @override Future<List<WatchEvent>> collectChanges() async { var updates = await _assetTracker.collectChanges(); return List.of(updates.entries .map((entry) => WatchEvent(entry.value, '${entry.key}'))); } @override Stream<List<WatchEvent>> get changes => Stream.empty(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/generate/build.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:build/build.dart'; import 'package:build_runner/src/generate/terminator.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; import 'package:watcher/watcher.dart'; import '../logging/std_io_logging.dart'; import '../package_graph/build_config_overrides.dart'; import '../server/server.dart'; import 'watch_impl.dart' as watch_impl; /// Runs all of the BuilderApplications in [builders] once. /// /// By default, the user will be prompted to delete any files which already /// exist but were not generated by this specific build script. The /// [deleteFilesByDefault] option can be set to `true` to skip this prompt. /// /// A [packageGraph] may be supplied, otherwise one will be constructed using /// [PackageGraph.forThisPackage]. The default functionality assumes you are /// running in the root directory of a package, with both a `pubspec.yaml` and /// `.packages` file present. /// /// A [reader] and [writer] may also be supplied, which can read/write assets /// to arbitrary locations or file systems. By default they will write directly /// to the root package directory, and will use the [packageGraph] to know where /// to read files from. /// /// Logging may be customized by passing a custom [logLevel] below which logs /// will be ignored, as well as an [onLog] handler which defaults to [print]. /// /// The [terminateEventStream] is a stream which can send termination events. /// By default the [ProcessSignal.sigint] stream is used. In this mode, it /// will simply consume the first event and allow the build to continue. /// Multiple termination events will cause a normal shutdown. /// /// If [outputSymlinksOnly] is `true`, then the merged output directories will /// contain only symlinks, which is much faster but not generally suitable for /// deployment. /// /// If [verbose] is `true` then verbose logging will be enabled. This changes /// the default [logLevel] to [Level.ALL] and removes stack frame folding, among /// other things. Future<BuildResult> build(List<BuilderApplication> builders, {bool deleteFilesByDefault, bool assumeTty, String configKey, PackageGraph packageGraph, RunnerAssetReader reader, RunnerAssetWriter writer, Resolvers resolvers, Level logLevel, void Function(LogRecord) onLog, Stream terminateEventStream, bool enableLowResourcesMode, Set<BuildDirectory> buildDirs, bool outputSymlinksOnly, bool trackPerformance, bool skipBuildScriptCheck, bool verbose, bool isReleaseBuild, Map<String, Map<String, dynamic>> builderConfigOverrides, String logPerformanceDir, Set<BuildFilter> buildFilters}) async { builderConfigOverrides ??= const {}; packageGraph ??= await PackageGraph.forThisPackage(); var environment = OverrideableEnvironment( IOEnvironment( packageGraph, assumeTty: assumeTty, outputSymlinksOnly: outputSymlinksOnly, ), reader: reader, writer: writer, onLog: onLog ?? stdIOLogListener(assumeTty: assumeTty, verbose: verbose)); var logSubscription = LogSubscription(environment, verbose: verbose, logLevel: logLevel); var options = await BuildOptions.create( logSubscription, deleteFilesByDefault: deleteFilesByDefault, packageGraph: packageGraph, skipBuildScriptCheck: skipBuildScriptCheck, overrideBuildConfig: await findBuildConfigOverrides(packageGraph, configKey), enableLowResourcesMode: enableLowResourcesMode, trackPerformance: trackPerformance, logPerformanceDir: logPerformanceDir, resolvers: resolvers, ); var terminator = Terminator(terminateEventStream); try { var build = await BuildRunner.create( options, environment, builders, builderConfigOverrides, isReleaseBuild: isReleaseBuild ?? false, ); var result = await build.run({}, buildDirs: buildDirs, buildFilters: buildFilters); await build?.beforeExit(); return result; } finally { await terminator.cancel(); await options.logListener.cancel(); } } /// Same as [build], except it watches the file system and re-runs builds /// automatically. /// /// Call [ServeHandler.handlerFor] to create a [Handler] for use with /// `package:shelf`. Requests for assets will be blocked while builds are /// running then served with the latest version of the asset. Only source and /// generated assets can be served through this handler. /// /// The [debounceDelay] controls how often builds will run. As long as files /// keep changing with less than that amount of time apart, builds will be put /// off. /// /// The [directoryWatcherFactory] allows you to inject a way of creating custom /// `DirectoryWatcher`s. By default a normal `DirectoryWatcher` will be used. /// /// The [terminateEventStream] is a stream which can send termination events. /// By default the [ProcessSignal.sigint] stream is used. In this mode, the /// first event will allow any ongoing builds to finish, and then the program /// will complete normally. Subsequent events are not handled (and will /// typically cause a shutdown). Future<ServeHandler> watch(List<BuilderApplication> builders, {bool deleteFilesByDefault, bool assumeTty, String configKey, PackageGraph packageGraph, RunnerAssetReader reader, RunnerAssetWriter writer, Resolvers resolvers, Level logLevel, void Function(LogRecord) onLog, Duration debounceDelay, DirectoryWatcher Function(String) directoryWatcherFactory, Stream terminateEventStream, bool enableLowResourcesMode, Set<BuildDirectory> buildDirs, bool outputSymlinksOnly, bool trackPerformance, bool skipBuildScriptCheck, bool verbose, bool isReleaseBuild, Map<String, Map<String, dynamic>> builderConfigOverrides, String logPerformanceDir, Set<BuildFilter> buildFilters}) => watch_impl.watch( builders, assumeTty: assumeTty, deleteFilesByDefault: deleteFilesByDefault, configKey: configKey, packageGraph: packageGraph, reader: reader, writer: writer, resolvers: resolvers, logLevel: logLevel, onLog: onLog, debounceDelay: debounceDelay, directoryWatcherFactory: directoryWatcherFactory, terminateEventStream: terminateEventStream, enableLowResourcesMode: enableLowResourcesMode, buildDirs: buildDirs, outputSymlinksOnly: outputSymlinksOnly, trackPerformance: trackPerformance, skipBuildScriptCheck: skipBuildScriptCheck, verbose: verbose, builderConfigOverrides: builderConfigOverrides, isReleaseBuild: isReleaseBuild, logPerformanceDir: logPerformanceDir, buildFilters: buildFilters, );
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/generate/watch_impl.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:build_config/build_config.dart'; import 'package:build_runner/src/package_graph/build_config_overrides.dart'; import 'package:build_runner/src/watcher/asset_change.dart'; import 'package:build_runner/src/watcher/change_filter.dart'; import 'package:build_runner/src/watcher/collect_changes.dart'; import 'package:build_runner/src/watcher/delete_writer.dart'; import 'package:build_runner/src/watcher/graph_watcher.dart'; import 'package:build_runner/src/watcher/node_watcher.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/asset_graph/graph.dart'; import 'package:build_runner_core/src/generate/build_impl.dart'; import 'package:crypto/crypto.dart'; import 'package:logging/logging.dart'; import 'package:pedantic/pedantic.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:watcher/watcher.dart'; import '../logging/std_io_logging.dart'; import '../server/server.dart'; import 'terminator.dart'; final _logger = Logger('Watch'); Future<ServeHandler> watch( List<BuilderApplication> builders, { bool deleteFilesByDefault, bool assumeTty, String configKey, PackageGraph packageGraph, RunnerAssetReader reader, RunnerAssetWriter writer, Resolvers resolvers, Level logLevel, void Function(LogRecord) onLog, Duration debounceDelay, DirectoryWatcher Function(String) directoryWatcherFactory, Stream terminateEventStream, bool skipBuildScriptCheck, bool enableLowResourcesMode, Map<String, BuildConfig> overrideBuildConfig, Set<BuildDirectory> buildDirs, bool outputSymlinksOnly, bool trackPerformance, bool verbose, Map<String, Map<String, dynamic>> builderConfigOverrides, bool isReleaseBuild, String logPerformanceDir, Set<BuildFilter> buildFilters, }) async { builderConfigOverrides ??= const {}; packageGraph ??= await PackageGraph.forThisPackage(); buildDirs ??= <BuildDirectory>{}; buildFilters ??= <BuildFilter>{}; var environment = OverrideableEnvironment( IOEnvironment(packageGraph, assumeTty: assumeTty, outputSymlinksOnly: outputSymlinksOnly), reader: reader, writer: writer, onLog: onLog ?? stdIOLogListener(assumeTty: assumeTty, verbose: verbose)); var logSubscription = LogSubscription(environment, verbose: verbose, logLevel: logLevel); overrideBuildConfig ??= await findBuildConfigOverrides(packageGraph, configKey); var options = await BuildOptions.create( logSubscription, deleteFilesByDefault: deleteFilesByDefault, packageGraph: packageGraph, overrideBuildConfig: overrideBuildConfig, debounceDelay: debounceDelay, skipBuildScriptCheck: skipBuildScriptCheck, enableLowResourcesMode: enableLowResourcesMode, trackPerformance: trackPerformance, logPerformanceDir: logPerformanceDir, resolvers: resolvers, ); var terminator = Terminator(terminateEventStream); var watch = _runWatch( options, environment, builders, builderConfigOverrides, terminator.shouldTerminate, directoryWatcherFactory, configKey, buildDirs .any((target) => target?.outputLocation?.path?.isNotEmpty ?? false), buildDirs, buildFilters, isReleaseMode: isReleaseBuild ?? false); unawaited(watch.buildResults.drain().then((_) async { await terminator.cancel(); await options.logListener.cancel(); })); return createServeHandler(watch); } /// Repeatedly run builds as files change on disk until [until] fires. /// /// Sets up file watchers and collects changes then triggers new builds. When /// [until] fires the file watchers will be stopped and up to one additional /// build may run if there were pending changes. /// /// The [BuildState.buildResults] stream will end after the final build has been /// run. WatchImpl _runWatch( BuildOptions options, BuildEnvironment environment, List<BuilderApplication> builders, Map<String, Map<String, dynamic>> builderConfigOverrides, Future until, DirectoryWatcher Function(String) directoryWatcherFactory, String configKey, bool willCreateOutputDirs, Set<BuildDirectory> buildDirs, Set<BuildFilter> buildFilters, {bool isReleaseMode = false}) => WatchImpl( options, environment, builders, builderConfigOverrides, until, directoryWatcherFactory, configKey, willCreateOutputDirs, buildDirs, buildFilters, isReleaseMode: isReleaseMode); class WatchImpl implements BuildState { BuildImpl _build; AssetGraph get assetGraph => _build?.assetGraph; final _readyCompleter = Completer<void>(); Future<void> get ready => _readyCompleter.future; final String _configKey; // may be null /// Delay to wait for more file watcher events. final Duration _debounceDelay; /// Injectable factory for creating directory watchers. final DirectoryWatcher Function(String) _directoryWatcherFactory; /// Whether or not we will be creating any output directories. /// /// If not, then we don't care about source edits that don't have outputs. final bool _willCreateOutputDirs; /// Should complete when we need to kill the build. final _terminateCompleter = Completer<Null>(); /// The [PackageGraph] for the current program. final PackageGraph packageGraph; /// The directories to build upon file changes and where to output them. final Set<BuildDirectory> _buildDirs; /// Filters for specific files to build. final Set<BuildFilter> _buildFilters; @override Future<BuildResult> currentBuild; /// Pending expected delete events from the build. final Set<AssetId> _expectedDeletes = <AssetId>{}; FinalizedReader _reader; FinalizedReader get reader => _reader; WatchImpl( BuildOptions options, BuildEnvironment environment, List<BuilderApplication> builders, Map<String, Map<String, dynamic>> builderConfigOverrides, Future until, this._directoryWatcherFactory, this._configKey, this._willCreateOutputDirs, this._buildDirs, this._buildFilters, {bool isReleaseMode = false}) : _debounceDelay = options.debounceDelay, packageGraph = options.packageGraph { buildResults = _run( options, environment, builders, builderConfigOverrides, until, isReleaseMode: isReleaseMode) .asBroadcastStream(); } @override Stream<BuildResult> buildResults; /// Runs a build any time relevant files change. /// /// Only one build will run at a time, and changes are batched. /// /// File watchers are scheduled synchronously. Stream<BuildResult> _run( BuildOptions options, BuildEnvironment environment, List<BuilderApplication> builders, Map<String, Map<String, dynamic>> builderConfigOverrides, Future until, {bool isReleaseMode = false}) { var watcherEnvironment = OverrideableEnvironment(environment, writer: OnDeleteWriter(environment.writer, _expectedDeletes.add)); var firstBuildCompleter = Completer<BuildResult>(); currentBuild = firstBuildCompleter.future; var controller = StreamController<BuildResult>(); Future<BuildResult> doBuild(List<List<AssetChange>> changes) async { assert(_build != null); _logger..info('${'-' * 72}\n')..info('Starting Build\n'); var mergedChanges = collectChanges(changes); _expectedDeletes.clear(); if (!options.skipBuildScriptCheck) { if (_build.buildScriptUpdates .hasBeenUpdated(mergedChanges.keys.toSet())) { _terminateCompleter.complete(); _logger.severe('Terminating builds due to build script update'); return BuildResult(BuildStatus.failure, [], failureType: FailureType.buildScriptChanged); } } return _build.run(mergedChanges, buildDirs: _buildDirs, buildFilters: _buildFilters); } var terminate = Future.any([until, _terminateCompleter.future]).then((_) { _logger.info('Terminating. No further builds will be scheduled\n'); }); Digest originalRootPackagesDigest; Digest originalRootPackageConfigDigest; final rootPackagesId = AssetId(packageGraph.root.name, '.packages'); final rootPackageConfigId = AssetId(packageGraph.root.name, '.dart_tool/package_config.json'); // Start watching files immediately, before the first build is even started. var graphWatcher = PackageGraphWatcher(packageGraph, logger: _logger, watch: (node) => PackageNodeWatcher(node, watch: _directoryWatcherFactory)); graphWatcher .watch() .asyncMap<AssetChange>((change) { // Delay any events until the first build is completed. if (firstBuildCompleter.isCompleted) return change; return firstBuildCompleter.future.then((_) => change); }) .asyncMap<AssetChange>((change) { var id = change.id; if (id == rootPackagesId || id == rootPackageConfigId) { var digest = id == rootPackagesId ? originalRootPackagesDigest : originalRootPackageConfigDigest; assert(digest != null); // Kill future builds if the root packages file changes. return watcherEnvironment.reader.readAsBytes(id).then((bytes) { if (md5.convert(bytes) != digest) { _terminateCompleter.complete(); _logger .severe('Terminating builds due to package graph update, ' 'please restart the build.'); } return change; }); } else if (_isBuildYaml(id) || _isConfiguredBuildYaml(id) || _isPackageBuildYamlOverride(id)) { controller.add(BuildResult(BuildStatus.failure, [], failureType: FailureType.buildConfigChanged)); // Kill future builds if the build.yaml files change. _terminateCompleter.complete(); _logger.severe( 'Terminating builds due to ${id.package}:${id.path} update.'); } return change; }) .asyncWhere((change) { assert(_readyCompleter.isCompleted); return shouldProcess( change, assetGraph, options, _willCreateOutputDirs, _expectedDeletes, watcherEnvironment.reader, ); }) .debounceBuffer(_debounceDelay) .takeUntil(terminate) .asyncMapBuffer((changes) => currentBuild = doBuild(changes) ..whenComplete(() => currentBuild = null)) .listen((BuildResult result) { if (controller.isClosed) return; controller.add(result); }) .onDone(() async { await currentBuild; await _build?.beforeExit(); if (!controller.isClosed) await controller.close(); _logger.info('Builds finished. Safe to exit\n'); }); // Schedule the actual first build for the future so we can return the // stream synchronously. () async { await logTimedAsync(_logger, 'Waiting for all file watchers to be ready', () => graphWatcher.ready); originalRootPackagesDigest = md5 .convert(await watcherEnvironment.reader.readAsBytes(rootPackagesId)); originalRootPackageConfigDigest = md5.convert( await watcherEnvironment.reader.readAsBytes(rootPackageConfigId)); BuildResult firstBuild; try { _build = await BuildImpl.create( options, watcherEnvironment, builders, builderConfigOverrides, isReleaseBuild: isReleaseMode); firstBuild = await _build .run({}, buildDirs: _buildDirs, buildFilters: _buildFilters); } on CannotBuildException { _terminateCompleter.complete(); firstBuild = BuildResult(BuildStatus.failure, []); } on BuildScriptChangedException { _terminateCompleter.complete(); firstBuild = BuildResult(BuildStatus.failure, [], failureType: FailureType.buildScriptChanged); } _reader = _build?.finalizedReader; _readyCompleter.complete(); // It is possible this is already closed if the user kills the process // early, which results in an exception without this check. if (!controller.isClosed) controller.add(firstBuild); firstBuildCompleter.complete(firstBuild); }(); return controller.stream; } bool _isBuildYaml(AssetId id) => id.path == 'build.yaml'; bool _isConfiguredBuildYaml(AssetId id) => id.package == packageGraph.root.name && id.path == 'build.$_configKey.yaml'; bool _isPackageBuildYamlOverride(AssetId id) => id.package == packageGraph.root.name && id.path.contains(_packageBuildYamlRegexp); final _packageBuildYamlRegexp = RegExp(r'^[a-z0-9_]+\.build\.yaml$'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/generate/terminator.dart
// 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 'dart:io'; /// Fires [shouldTerminate] once a `SIGINT` is intercepted. /// /// The `SIGINT` stream can optionally be replaced with another Stream in the /// constructor. [cancel] should be called after work is finished. If multiple /// events are receieved on the terminate event stream before work is finished /// the process will be terminated with [exit]. class Terminator { /// A Future that fires when a signal has been received indicating that builds /// should stop. final Future shouldTerminate; final StreamSubscription _subscription; factory Terminator([Stream terminateEventStream]) { var shouldTerminate = Completer<void>(); terminateEventStream ??= ProcessSignal.sigint.watch(); var numEventsSeen = 0; var terminateListener = terminateEventStream.listen((_) { numEventsSeen++; if (numEventsSeen == 1) { shouldTerminate.complete(); } else { exit(2); } }); return Terminator._(shouldTerminate.future, terminateListener); } Terminator._(this.shouldTerminate, this._subscription); Future cancel() => _subscription.cancel(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/generate/directory_watcher_factory.dart
// 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:watcher/watcher.dart'; DirectoryWatcher defaultDirectoryWatcherFactory(String path) => DirectoryWatcher(path); DirectoryWatcher pollingDirectoryWatcherFactory(String path) => PollingDirectoryWatcher(path);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/build.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import '../generate/build.dart'; import 'base_command.dart'; /// A command that does a single build and then exits. class BuildCommand extends BuildRunnerCommand { @override String get invocation => '${super.invocation} [directories]'; @override String get name => 'build'; @override String get description => 'Performs a single build on the specified targets and then exits.'; @override Future<int> run() async { var options = readOptions(); var result = await build( builderApplications, buildFilters: options.buildFilters, deleteFilesByDefault: options.deleteFilesByDefault, enableLowResourcesMode: options.enableLowResourcesMode, configKey: options.configKey, buildDirs: options.buildDirs, outputSymlinksOnly: options.outputSymlinksOnly, packageGraph: packageGraph, verbose: options.verbose, builderConfigOverrides: options.builderConfigOverrides, isReleaseBuild: options.isReleaseBuild, trackPerformance: options.trackPerformance, skipBuildScriptCheck: options.skipBuildScriptCheck, logPerformanceDir: options.logPerformanceDir, ); if (result.status == BuildStatus.success) { return ExitCode.success.code; } else { return result.failureType.exitCode; } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/run_script.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:isolate'; import 'package:args/command_runner.dart'; import 'package:build_runner/src/logging/std_io_logging.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import '../generate/build.dart'; import 'base_command.dart'; import 'options.dart'; class RunCommand extends BuildRunnerCommand { @override String get name => 'run'; @override String get description => 'Performs a single build, and executes ' 'a Dart script with the given arguments.'; @override String get invocation => '${super.invocation.replaceFirst('[arguments]', '[build-arguments]')} ' '<executable> [-- [script-arguments]]'; @override SharedOptions readOptions() { // Here we validate that [argResults.rest] is exactly equal to all the // arguments after the `--`. var separatorPos = argResults.arguments.indexOf('--'); if (separatorPos >= 0) { void throwUsageException() { throw UsageException( 'The `run` command does not support positional args before the ' '`--` separator which should separate build args from script args.', usage); } var expectedRest = argResults.arguments.skip(separatorPos + 1).toList(); // Since we expect the first argument to be the name of a script, // we should skip it when comparing extra arguments. var effectiveRest = argResults.rest.skip(1).toList(); if (effectiveRest.length != expectedRest.length) { throwUsageException(); } for (var i = 0; i < effectiveRest.length; i++) { if (expectedRest[i] != effectiveRest[i]) { throwUsageException(); } } } return SharedOptions.fromParsedArgs( argResults, [], packageGraph.root.name, this); } @override FutureOr<int> run() async { var options = readOptions(); var logSubscription = Logger.root.onRecord.listen(stdIOLogListener(verbose: options.verbose)); try { // Ensure that the user passed the name of a file to run. if (argResults.rest.isEmpty) { logger..severe('Must specify an executable to run.')..severe(usage); return ExitCode.usage.code; } var scriptName = argResults.rest[0]; var passedArgs = argResults.rest.skip(1).toList(); // Ensure the extension is .dart. if (p.extension(scriptName) != '.dart') { logger.severe('$scriptName is not a valid Dart file ' 'and cannot be run in the VM.'); return ExitCode.usage.code; } // Create a temporary directory in which to execute the script. var tempPath = Directory.systemTemp .createTempSync('build_runner_run_script') .absolute .uri .toFilePath(); // Create two ReceivePorts, so that we can quit when the isolate is done. // // Define these before starting the isolate, so that we can close // them if there is a spawn exception. ReceivePort onExit, onError; // Use a completer to determine the exit code. var exitCodeCompleter = Completer<int>(); try { var buildDirs = (options.buildDirs ?? <BuildDirectory>{}) ..add(BuildDirectory('', outputLocation: OutputLocation(tempPath, useSymlinks: options.outputSymlinksOnly, hoist: false))); var result = await build( builderApplications, deleteFilesByDefault: options.deleteFilesByDefault, enableLowResourcesMode: options.enableLowResourcesMode, configKey: options.configKey, buildDirs: buildDirs, packageGraph: packageGraph, verbose: options.verbose, builderConfigOverrides: options.builderConfigOverrides, isReleaseBuild: options.isReleaseBuild, trackPerformance: options.trackPerformance, skipBuildScriptCheck: options.skipBuildScriptCheck, logPerformanceDir: options.logPerformanceDir, buildFilters: options.buildFilters, ); if (result.status == BuildStatus.failure) { logger.warning('Skipping script run due to build failure'); return result.failureType.exitCode; } // Find the path of the script to run. var scriptPath = p.join(tempPath, scriptName); var packageConfigPath = p.join(tempPath, '.packages'); onExit = ReceivePort(); onError = ReceivePort(); // Cleanup after exit. onExit.listen((_) { // If no error was thrown, return 0. if (!exitCodeCompleter.isCompleted) exitCodeCompleter.complete(0); }); // On an error, kill the isolate, and log the error. onError.listen((e) { onExit.close(); onError.close(); logger.severe('Unhandled error from script: $scriptName', e[0], StackTrace.fromString(e[1].toString())); if (!exitCodeCompleter.isCompleted) exitCodeCompleter.complete(1); }); await Isolate.spawnUri( p.toUri(scriptPath), passedArgs, null, errorsAreFatal: true, onExit: onExit.sendPort, onError: onError.sendPort, packageConfig: p.toUri(packageConfigPath), ); return await exitCodeCompleter.future; } on IsolateSpawnException catch (e) { logger.severe( 'Could not spawn isolate. Ensure that your file is in a valid directory (i.e. "bin", "benchmark", "example", "test", "tool").', e); return ExitCode.ioError.code; } finally { // Clean up the output dir. var dir = Directory(tempPath); if (await dir.exists()) await dir.delete(recursive: true); onExit?.close(); onError?.close(); if (!exitCodeCompleter.isCompleted) { exitCodeCompleter.complete(ExitCode.success.code); } } } finally { await logSubscription.cancel(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/base_command.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'options.dart'; import 'runner.dart'; final lineLength = stdout.hasTerminal ? stdout.terminalColumns : 80; abstract class BuildRunnerCommand extends Command<int> { Logger get logger => Logger(name); List<BuilderApplication> get builderApplications => (runner as BuildCommandRunner).builderApplications; PackageGraph get packageGraph => (runner as BuildCommandRunner).packageGraph; BuildRunnerCommand({bool symlinksDefault}) { _addBaseFlags(symlinksDefault ?? false); } @override final argParser = ArgParser(usageLineLength: lineLength); void _addBaseFlags(bool symlinksDefault) { argParser ..addFlag(deleteFilesByDefaultOption, help: 'By default, the user will be prompted to delete any files which ' 'already exist but were not known to be generated by this ' 'specific build script.\n\n' 'Enabling this option skips the prompt and deletes the files. ' 'This should typically be used in continues integration servers ' 'and tests, but not otherwise.', negatable: false, defaultsTo: false) ..addFlag(lowResourcesModeOption, help: 'Reduce the amount of memory consumed by the build process. ' 'This will slow down builds but allow them to progress in ' 'resource constrained environments.', negatable: false, defaultsTo: false) ..addOption(configOption, help: 'Read `build.<name>.yaml` instead of the default `build.yaml`', abbr: 'c') ..addFlag('fail-on-severe', help: 'Deprecated argument - always enabled', negatable: true, defaultsTo: true, hide: true) ..addFlag(trackPerformanceOption, help: r'Enables performance tracking and the /$perf page.', negatable: true, defaultsTo: false) ..addOption(logPerformanceOption, help: 'A directory to write performance logs to, must be in the ' 'current package. Implies `--track-performance`.') ..addFlag(skipBuildScriptCheckOption, help: r'Skip validation for the digests of files imported by the ' 'build script.', hide: true, defaultsTo: false) ..addMultiOption(outputOption, help: 'A directory to copy the fully built package to. Or a mapping ' 'from a top-level directory in the package to the directory to ' 'write a filtered build output to. For example "web:deploy".', abbr: 'o') ..addFlag(verboseOption, abbr: 'v', defaultsTo: false, negatable: false, help: 'Enables verbose logging.') ..addFlag(releaseOption, abbr: 'r', defaultsTo: false, negatable: true, help: 'Build with release mode defaults for builders.') ..addMultiOption(defineOption, splitCommas: false, help: 'Sets the global `options` config for a builder by key.') ..addFlag(symlinkOption, defaultsTo: symlinksDefault, negatable: true, help: 'Symlink files in the output directories, instead of copying.') ..addMultiOption(buildFilterOption, help: 'An explicit filter of files to build. Relative paths and ' '`package:` uris are supported, including glob syntax for paths ' 'portions (but not package names).\n\n' 'If multiple filters are applied then outputs matching any filter ' 'will be built (they do not need to match all filters).'); } /// Must be called inside [run] so that [argResults] is non-null. /// /// You may override this to return more specific options if desired, but they /// must extend [SharedOptions]. SharedOptions readOptions() { return SharedOptions.fromParsedArgs( argResults, argResults.rest, packageGraph.root.name, this); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/doctor.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:build_config/build_config.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/generate/phase.dart'; import 'package:io/io.dart'; import 'package:logging/logging.dart'; import '../logging/std_io_logging.dart'; import '../package_graph/build_config_overrides.dart'; import 'base_command.dart'; /// A command that validates the build environment. class DoctorCommand extends BuildRunnerCommand { @override String get name => 'doctor'; @override bool get hidden => true; @override String get description => 'Check for misconfiguration of the build.'; @override Future<int> run() async { final options = readOptions(); final verbose = options.verbose ?? false; Logger.root.level = verbose ? Level.ALL : Level.INFO; final logSubscription = Logger.root.onRecord.listen(stdIOLogListener(verbose: verbose)); final config = await _loadBuilderDefinitions(); var isOk = true; for (final builderApplication in builderApplications) { final builderOk = _checkBuildExtensions(builderApplication, config); isOk = isOk && builderOk; } if (isOk) { logger.info('No problems found!\n'); } await logSubscription.cancel(); return isOk ? ExitCode.success.code : ExitCode.config.code; } Future<Map<String, BuilderDefinition>> _loadBuilderDefinitions() async { final packageGraph = await PackageGraph.forThisPackage(); final buildConfigOverrides = await findBuildConfigOverrides(packageGraph, null); Future<BuildConfig> _packageBuildConfig(PackageNode package) async { if (buildConfigOverrides.containsKey(package.name)) { return buildConfigOverrides[package.name]; } try { return await BuildConfig.fromBuildConfigDir(package.name, package.dependencies.map((n) => n.name), package.path); } on ArgumentError catch (e) { logger.severe( 'Failed to parse a `build.yaml` file for ${package.name}', e); return BuildConfig.useDefault( package.name, package.dependencies.map((n) => n.name)); } } final allConfig = await Future.wait( packageGraph.allPackages.values.map(_packageBuildConfig)); final allBuilders = <String, BuilderDefinition>{}; for (final config in allConfig) { allBuilders.addAll(config.builderDefinitions); } return allBuilders; } /// Returns true of [builderApplication] has sane build extension /// configuration. /// /// If there are any problems they will be logged and `false` returned. bool _checkBuildExtensions(BuilderApplication builderApplication, Map<String, BuilderDefinition> config) { var phases = builderApplication.buildPhaseFactories .map((f) => f(PackageNode(null, null, null, null, isRoot: true), BuilderOptions.empty, InputSet.anything, InputSet.anything, true)) .whereType<InBuildPhase>() .toList(); if (phases.isEmpty) return true; if (!config.containsKey(builderApplication.builderKey)) return false; var problemFound = false; var allowed = Map.of(config[builderApplication.builderKey].buildExtensions); for (final phase in phases.whereType<InBuildPhase>()) { final extensions = phase.builder.buildExtensions; for (final extension in extensions.entries) { if (!allowed.containsKey(extension.key)) { logger.warning('Builder ${builderApplication.builderKey} ' 'uses input extension ${extension.key} ' 'which is not specified in the `build.yaml`'); problemFound = true; continue; } final allowedOutputs = List.of(allowed[extension.key]); for (final output in extension.value) { if (!allowedOutputs.contains(output)) { logger.warning('Builder ${builderApplication.builderKey} ' 'outputs $output from ${extension.key} ' 'which is not specified in the `build.yaml`'); problemFound = true; } // Allow subsequent phases to use these outputs as inputs if (allowedOutputs.length > 1) { allowed.putIfAbsent(output, () => []).addAll(allowedOutputs); } } } } return !problemFound; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/clean.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/asset_graph/graph.dart'; import 'package:build_runner_core/src/asset_graph/node.dart'; import 'package:logging/logging.dart'; import '../logging/std_io_logging.dart'; import 'base_command.dart'; class CleanCommand extends Command<int> { @override final argParser = ArgParser(usageLineLength: lineLength); @override String get name => 'clean'; @override String get description => 'Cleans up output from previous builds. Does not clean up --output ' 'directories.'; Logger get logger => Logger(name); @override Future<int> run() async { var logSubscription = Logger.root.onRecord.listen(stdIOLogListener()); await cleanFor(assetGraphPath, logger); await logSubscription.cancel(); return 0; } } Future<void> cleanFor(String assetGraphPath, Logger logger) async { logger.warning('Deleting cache and generated source files.\n' 'This shouldn\'t be necessary for most applications, unless you have ' 'made intentional edits to generated files (i.e. for testing). ' 'Consider filing a bug at ' 'https://github.com/dart-lang/build/issues/new if you are using this ' 'to work around an apparent (and reproducible) bug.'); await logTimedAsync(logger, 'Cleaning up source outputs', () async { var assetGraphFile = File(assetGraphPath); if (!assetGraphFile.existsSync()) { logger.warning('No asset graph found. ' 'Skipping cleanup of generated files in source directories.'); return; } AssetGraph assetGraph; try { assetGraph = AssetGraph.deserialize(await assetGraphFile.readAsBytes()); } catch (_) { logger.warning('Failed to deserialize AssetGraph. ' 'Skipping cleanup of generated files in source directories.'); return; } var packageGraph = await PackageGraph.forThisPackage(); await _cleanUpSourceOutputs(assetGraph, packageGraph); }); await logTimedAsync( logger, 'Cleaning up cache directory', _cleanUpGeneratedDirectory); } Future<void> _cleanUpSourceOutputs( AssetGraph assetGraph, PackageGraph packageGraph) async { var writer = FileBasedAssetWriter(packageGraph); for (var id in assetGraph.outputs) { if (id.package != packageGraph.root.name) continue; var node = assetGraph.get(id) as GeneratedAssetNode; if (node.wasOutput) { // Note that this does a file.exists check in the root package and // only tries to delete the file if it exists. This way we only // actually delete to_source outputs, without reading in the build // actions. await writer.delete(id); } } } Future<void> _cleanUpGeneratedDirectory() async { var generatedDir = Directory(cacheDir); if (await generatedDir.exists()) { await generatedDir.delete(recursive: true); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/daemon.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:build_daemon/constants.dart'; import 'package:build_daemon/daemon.dart'; import 'package:build_daemon/data/serializers.dart'; import 'package:build_daemon/data/server_log.dart'; import 'package:build_runner/src/daemon/constants.dart'; import 'package:logging/logging.dart' hide Level; import 'package:pedantic/pedantic.dart'; import '../daemon/asset_server.dart'; import '../daemon/daemon_builder.dart'; import 'options.dart'; import 'watch.dart'; /// A command that starts the Build Daemon. class DaemonCommand extends WatchCommand { @override String get description => 'Starts the build daemon.'; @override bool get hidden => true; @override String get name => 'daemon'; DaemonCommand() { argParser.addOption(buildModeFlag, help: 'Specify the build mode of the daemon, e.g. auto or manual.', defaultsTo: 'BuildMode.Auto'); } @override DaemonOptions readOptions() => DaemonOptions.fromParsedArgs( argResults, argResults.rest, packageGraph.root.name, this); @override Future<int> run() async { var workingDirectory = Directory.current.path; var options = readOptions(); var daemon = Daemon(workingDirectory); var requestedOptions = argResults.arguments.toSet(); if (!daemon.hasLock) { var runningOptions = await daemon.currentOptions(); var version = await daemon.runningVersion(); if (version != currentVersion) { stdout ..writeln('Running Version: $version') ..writeln('Current Version: $currentVersion') ..writeln(versionSkew); return 1; } else if (!(runningOptions.length == requestedOptions.length && runningOptions.containsAll(requestedOptions))) { stdout ..writeln('Running Options: $runningOptions') ..writeln('Requested Options: $requestedOptions') ..writeln(optionsSkew); return 1; } else { stdout.writeln('Daemon is already running.'); print(readyToConnectLog); return 0; } } else { stdout.writeln('Starting daemon...'); BuildRunnerDaemonBuilder builder; // Ensure we capture any logs that happen during startup. // // These are serialized between special `<log-record>` and `</log-record>` // tags to make parsing them on stdout easier. They can have multiline // strings so we can't just serialize the json on a single line. var startupLogSub = Logger.root.onRecord.listen((record) => stdout.writeln(''' $logStartMarker ${jsonEncode(serializers.serialize(ServerLog.fromLogRecord(record)))} $logEndMarker''')); builder = await BuildRunnerDaemonBuilder.create( packageGraph, builderApplications, options, ); await startupLogSub.cancel(); // Forward server logs to daemon command STDIO. var logSub = builder.logs.listen((log) { if (log.level > Level.INFO) { var buffer = StringBuffer(log.message); if (log.error != null) buffer.writeln(log.error); if (log.stackTrace != null) buffer.writeln(log.stackTrace); stderr.writeln(buffer); } else { stdout.writeln(log.message); } }); var server = await AssetServer.run(builder, packageGraph.root.name); File(assetServerPortFilePath(workingDirectory)) .writeAsStringSync('${server.port}'); unawaited(builder.buildScriptUpdated.then((_) async { await daemon.stop( message: 'Build script updated. Shutting down the Build Daemon.', failureType: 75); })); await daemon.start(requestedOptions, builder, builder.changeProvider, timeout: Duration(seconds: 60)); stdout.writeln(readyToConnectLog); await logSub.cancel(); await daemon.onDone.whenComplete(() async { await server.stop(); }); // Clients can disconnect from the daemon mid build. // As a result we try to relinquish resources which can // cause the build to hang. To ensure there are no ghost processes // fast exit. exit(0); } return 0; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/run.dart
// 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 'dart:io'; import 'package:args/command_runner.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/ansi.dart' as ansi; import 'package:io/io.dart' show ExitCode; import 'clean.dart'; import 'runner.dart'; /// A common entry point to parse command line arguments and build or serve with /// [builders]. /// /// Returns the exit code that should be set when the calling process exits. `0` /// implies success. Future<int> run(List<String> args, List<BuilderApplication> builders) async { var runner = BuildCommandRunner(builders, await PackageGraph.forThisPackage()) ..addCommand(CleanCommand()); try { var result = await runner.run(args); return result ?? 0; } on UsageException catch (e) { print(ansi.red.wrap(e.message)); print(''); print(e.usage); return ExitCode.usage.code; } on ArgumentError catch (e) { print(ansi.red.wrap(e.toString())); return ExitCode.usage.code; } on CannotBuildException { // A message should have already been logged. return ExitCode.config.code; } on BuildScriptChangedException { _deleteAssetGraph(); if (_runningFromSnapshot) _deleteSelf(); return ExitCode.tempFail.code; } on BuildConfigChangedException { return ExitCode.tempFail.code; } } /// Deletes the asset graph for the current build script from disk. void _deleteAssetGraph() { var graph = File(assetGraphPath); if (graph.existsSync()) { graph.deleteSync(); } } /// Deletes the current running script. /// /// This should only happen if the current script is a snapshot, and it has /// been invalidated. void _deleteSelf() { var self = File(Platform.script.toFilePath()); if (self.existsSync()) { self.deleteSync(); } } bool get _runningFromSnapshot => !Platform.script.path.endsWith('.dart');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/runner.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'base_command.dart' show lineLength; import 'build.dart'; import 'daemon.dart'; import 'doctor.dart'; import 'run_script.dart'; import 'serve.dart'; import 'test.dart'; import 'watch.dart'; /// Unified command runner for all build_runner commands. class BuildCommandRunner extends CommandRunner<int> { @override final argParser = ArgParser(usageLineLength: lineLength); final List<BuilderApplication> builderApplications; final PackageGraph packageGraph; BuildCommandRunner( List<BuilderApplication> builderApplications, this.packageGraph) : builderApplications = List.unmodifiable(builderApplications), super('build_runner', 'Unified interface for running Dart builds.') { addCommand(BuildCommand()); addCommand(DaemonCommand()); addCommand(DoctorCommand()); addCommand(RunCommand()); addCommand(ServeCommand()); addCommand(TestCommand(packageGraph)); addCommand(WatchCommand()); } // CommandRunner._usageWithoutDescription is private – this is a reasonable // facsimile. /// Returns [usage] with [description] removed from the beginning. String get usageWithoutDescription => LineSplitter.split(usage) .skipWhile((line) => line == description || line.isEmpty) .join('\n'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/options.dart
// 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:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_config/build_config.dart'; import 'package:build_daemon/constants.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:watcher/watcher.dart'; import '../generate/directory_watcher_factory.dart'; const buildFilterOption = 'build-filter'; const configOption = 'config'; const defineOption = 'define'; const deleteFilesByDefaultOption = 'delete-conflicting-outputs'; const failOnSevereOption = 'fail-on-severe'; const hostnameOption = 'hostname'; const hotReloadOption = 'hot-reload'; const liveReloadOption = 'live-reload'; const logPerformanceOption = 'log-performance'; const logRequestsOption = 'log-requests'; const lowResourcesModeOption = 'low-resources-mode'; const outputOption = 'output'; const releaseOption = 'release'; const trackPerformanceOption = 'track-performance'; const skipBuildScriptCheckOption = 'skip-build-script-check'; const symlinkOption = 'symlink'; const usePollingWatcherOption = 'use-polling-watcher'; const verboseOption = 'verbose'; enum BuildUpdatesOption { none, liveReload, hotReload } final _defaultWebDirs = const ['web', 'test', 'example', 'benchmark']; /// Base options that are shared among all commands. class SharedOptions { /// A set of explicit filters for files to build. /// /// If provided no other files will be built that don't match these filters /// unless they are an input to something matching a filter. final Set<BuildFilter> buildFilters; /// By default, the user will be prompted to delete any files which already /// exist but were not generated by this specific build script. /// /// This option can be set to `true` to skip this prompt. final bool deleteFilesByDefault; final bool enableLowResourcesMode; /// Read `build.$configKey.yaml` instead of `build.yaml`. final String configKey; /// A set of targets to build with their corresponding output locations. final Set<BuildDirectory> buildDirs; /// Whether or not the output directories should contain only symlinks, /// or full copies of all files. final bool outputSymlinksOnly; /// Enables performance tracking and the `/$perf` page. final bool trackPerformance; /// A directory to log performance information to. String logPerformanceDir; /// Check digest of imports to the build script to invalidate the build. final bool skipBuildScriptCheck; final bool verbose; // Global config overrides by builder. // // Keys are the builder keys, such as my_package|my_builder, and values // represent config objects. All keys in the config will override the parsed // config for that key. final Map<String, Map<String, dynamic>> builderConfigOverrides; final bool isReleaseBuild; SharedOptions._({ @required this.buildFilters, @required this.deleteFilesByDefault, @required this.enableLowResourcesMode, @required this.configKey, @required this.buildDirs, @required this.outputSymlinksOnly, @required this.trackPerformance, @required this.skipBuildScriptCheck, @required this.verbose, @required this.builderConfigOverrides, @required this.isReleaseBuild, @required this.logPerformanceDir, }); factory SharedOptions.fromParsedArgs(ArgResults argResults, Iterable<String> positionalArgs, String rootPackage, Command command) { var buildDirs = { ..._parseBuildDirs(argResults), ..._parsePositionalBuildDirs(positionalArgs, command), }; var buildFilters = _parseBuildFilters(argResults, rootPackage); return SharedOptions._( buildFilters: buildFilters, deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool, enableLowResourcesMode: argResults[lowResourcesModeOption] as bool, configKey: argResults[configOption] as String, buildDirs: buildDirs, outputSymlinksOnly: argResults[symlinkOption] as bool, trackPerformance: argResults[trackPerformanceOption] as bool, skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool, verbose: argResults[verboseOption] as bool, builderConfigOverrides: _parseBuilderConfigOverrides(argResults[defineOption], rootPackage), isReleaseBuild: argResults[releaseOption] as bool, logPerformanceDir: argResults[logPerformanceOption] as String, ); } } /// Options specific to the `daemon` command. class DaemonOptions extends WatchOptions { BuildMode buildMode; DaemonOptions._({ @required Set<BuildFilter> buildFilters, @required this.buildMode, @required bool deleteFilesByDefault, @required bool enableLowResourcesMode, @required String configKey, @required Set<BuildDirectory> buildDirs, @required bool outputSymlinksOnly, @required bool trackPerformance, @required bool skipBuildScriptCheck, @required bool verbose, @required Map<String, Map<String, dynamic>> builderConfigOverrides, @required bool isReleaseBuild, @required String logPerformanceDir, @required bool usePollingWatcher, }) : super._( buildFilters: buildFilters, deleteFilesByDefault: deleteFilesByDefault, enableLowResourcesMode: enableLowResourcesMode, configKey: configKey, buildDirs: buildDirs, outputSymlinksOnly: outputSymlinksOnly, trackPerformance: trackPerformance, skipBuildScriptCheck: skipBuildScriptCheck, verbose: verbose, builderConfigOverrides: builderConfigOverrides, isReleaseBuild: isReleaseBuild, logPerformanceDir: logPerformanceDir, usePollingWatcher: usePollingWatcher, ); factory DaemonOptions.fromParsedArgs(ArgResults argResults, Iterable<String> positionalArgs, String rootPackage, Command command) { var buildDirs = { ..._parseBuildDirs(argResults), ..._parsePositionalBuildDirs(positionalArgs, command), }; var buildFilters = _parseBuildFilters(argResults, rootPackage); var buildModeValue = argResults[buildModeFlag] as String; BuildMode buildMode; if (buildModeValue == BuildMode.Auto.toString()) { buildMode = BuildMode.Auto; } else if (buildModeValue == BuildMode.Manual.toString()) { buildMode = BuildMode.Manual; } else { throw UsageException( 'Unexpected value for $buildModeFlag: $buildModeValue', command.usage); } return DaemonOptions._( buildFilters: buildFilters, buildMode: buildMode, deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool, enableLowResourcesMode: argResults[lowResourcesModeOption] as bool, configKey: argResults[configOption] as String, buildDirs: buildDirs, outputSymlinksOnly: argResults[symlinkOption] as bool, trackPerformance: argResults[trackPerformanceOption] as bool, skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool, verbose: argResults[verboseOption] as bool, builderConfigOverrides: _parseBuilderConfigOverrides(argResults[defineOption], rootPackage), isReleaseBuild: argResults[releaseOption] as bool, logPerformanceDir: argResults[logPerformanceOption] as String, usePollingWatcher: argResults[usePollingWatcherOption] as bool, ); } } class WatchOptions extends SharedOptions { final bool usePollingWatcher; DirectoryWatcher Function(String) get directoryWatcherFactory => usePollingWatcher ? pollingDirectoryWatcherFactory : defaultDirectoryWatcherFactory; WatchOptions._({ @required this.usePollingWatcher, @required Set<BuildFilter> buildFilters, @required bool deleteFilesByDefault, @required bool enableLowResourcesMode, @required String configKey, @required Set<BuildDirectory> buildDirs, @required bool outputSymlinksOnly, @required bool trackPerformance, @required bool skipBuildScriptCheck, @required bool verbose, @required Map<String, Map<String, dynamic>> builderConfigOverrides, @required bool isReleaseBuild, @required String logPerformanceDir, }) : super._( buildFilters: buildFilters, deleteFilesByDefault: deleteFilesByDefault, enableLowResourcesMode: enableLowResourcesMode, configKey: configKey, buildDirs: buildDirs, outputSymlinksOnly: outputSymlinksOnly, trackPerformance: trackPerformance, skipBuildScriptCheck: skipBuildScriptCheck, verbose: verbose, builderConfigOverrides: builderConfigOverrides, isReleaseBuild: isReleaseBuild, logPerformanceDir: logPerformanceDir, ); factory WatchOptions.fromParsedArgs(ArgResults argResults, Iterable<String> positionalArgs, String rootPackage, Command command) { var buildDirs = { ..._parseBuildDirs(argResults), ..._parsePositionalBuildDirs(positionalArgs, command), }; var buildFilters = _parseBuildFilters(argResults, rootPackage); return WatchOptions._( buildFilters: buildFilters, deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool, enableLowResourcesMode: argResults[lowResourcesModeOption] as bool, configKey: argResults[configOption] as String, buildDirs: buildDirs, outputSymlinksOnly: argResults[symlinkOption] as bool, trackPerformance: argResults[trackPerformanceOption] as bool, skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool, verbose: argResults[verboseOption] as bool, builderConfigOverrides: _parseBuilderConfigOverrides(argResults[defineOption], rootPackage), isReleaseBuild: argResults[releaseOption] as bool, logPerformanceDir: argResults[logPerformanceOption] as String, usePollingWatcher: argResults[usePollingWatcherOption] as bool, ); } } /// Options specific to the `serve` command. class ServeOptions extends WatchOptions { final String hostName; final BuildUpdatesOption buildUpdates; final bool logRequests; final List<ServeTarget> serveTargets; ServeOptions._({ @required this.hostName, @required this.buildUpdates, @required this.logRequests, @required this.serveTargets, @required Set<BuildFilter> buildFilters, @required bool deleteFilesByDefault, @required bool enableLowResourcesMode, @required String configKey, @required Set<BuildDirectory> buildDirs, @required bool outputSymlinksOnly, @required bool trackPerformance, @required bool skipBuildScriptCheck, @required bool verbose, @required Map<String, Map<String, dynamic>> builderConfigOverrides, @required bool isReleaseBuild, @required String logPerformanceDir, @required bool usePollingWatcher, }) : super._( buildFilters: buildFilters, deleteFilesByDefault: deleteFilesByDefault, enableLowResourcesMode: enableLowResourcesMode, configKey: configKey, buildDirs: buildDirs, outputSymlinksOnly: outputSymlinksOnly, trackPerformance: trackPerformance, skipBuildScriptCheck: skipBuildScriptCheck, verbose: verbose, builderConfigOverrides: builderConfigOverrides, isReleaseBuild: isReleaseBuild, logPerformanceDir: logPerformanceDir, usePollingWatcher: usePollingWatcher, ); factory ServeOptions.fromParsedArgs(ArgResults argResults, Iterable<String> positionalArgs, String rootPackage, Command command) { var serveTargets = <ServeTarget>[]; var nextDefaultPort = 8080; for (var arg in positionalArgs) { var parts = arg.split(':'); if (parts.length > 2) { throw UsageException( 'Invalid format for positional argument to serve `$arg`' ', expected <directory>:<port>.', command.usage); } var port = parts.length == 2 ? int.tryParse(parts[1]) : nextDefaultPort++; if (port == null) { throw UsageException( 'Unable to parse port number in `$arg`', command.usage); } var path = parts.first; var pathParts = p.split(path); if (pathParts.length > 1 || path == '.') { throw UsageException( 'Only top level directories such as `web` or `test` are allowed as ' 'positional args, but got `$path`', command.usage); } serveTargets.add(ServeTarget(path, port)); } if (serveTargets.isEmpty) { for (var dir in _defaultWebDirs) { if (Directory(dir).existsSync()) { serveTargets.add(ServeTarget(dir, nextDefaultPort++)); } } } var buildDirs = _parseBuildDirs(argResults); for (var target in serveTargets) { buildDirs.add(BuildDirectory(target.dir)); } var buildFilters = _parseBuildFilters(argResults, rootPackage); BuildUpdatesOption buildUpdates; if (argResults[liveReloadOption] as bool && argResults[hotReloadOption] as bool) { throw UsageException( 'Options --$liveReloadOption and --$hotReloadOption ' "can't both be used together", command.usage); } else if (argResults[liveReloadOption] as bool) { buildUpdates = BuildUpdatesOption.liveReload; } else if (argResults[hotReloadOption] as bool) { buildUpdates = BuildUpdatesOption.hotReload; } return ServeOptions._( buildFilters: buildFilters, hostName: argResults[hostnameOption] as String, buildUpdates: buildUpdates, logRequests: argResults[logRequestsOption] as bool, serveTargets: serveTargets, deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool, enableLowResourcesMode: argResults[lowResourcesModeOption] as bool, configKey: argResults[configOption] as String, buildDirs: buildDirs, outputSymlinksOnly: argResults[symlinkOption] as bool, trackPerformance: argResults[trackPerformanceOption] as bool, skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool, verbose: argResults[verboseOption] as bool, builderConfigOverrides: _parseBuilderConfigOverrides(argResults[defineOption], rootPackage), isReleaseBuild: argResults[releaseOption] as bool, logPerformanceDir: argResults[logPerformanceOption] as String, usePollingWatcher: argResults[usePollingWatcherOption] as bool, ); } } /// A target to serve, representing a directory and a port. class ServeTarget { final String dir; final int port; ServeTarget(this.dir, this.port); } Map<String, Map<String, dynamic>> _parseBuilderConfigOverrides( dynamic parsedArg, String rootPackage) { final builderConfigOverrides = <String, Map<String, dynamic>>{}; if (parsedArg == null) return builderConfigOverrides; var allArgs = parsedArg is List<String> ? parsedArg : [parsedArg as String]; for (final define in allArgs) { final parts = define.split('='); const expectedFormat = '--define "<builder_key>=<option>=<value>"'; if (parts.length < 3) { throw ArgumentError.value( define, defineOption, 'Expected at least 2 `=` signs, should be of the format like ' '$expectedFormat'); } else if (parts.length > 3) { var rest = parts.sublist(2); parts ..removeRange(2, parts.length) ..add(rest.join('=')); } final builderKey = normalizeBuilderKeyUsage(parts[0], rootPackage); final option = parts[1]; dynamic value; // Attempt to parse the value as JSON, and if that fails then treat it as // a normal string. try { value = json.decode(parts[2]); } on FormatException catch (_) { value = parts[2]; } final config = builderConfigOverrides.putIfAbsent( builderKey, () => <String, dynamic>{}); if (config.containsKey(option)) { throw ArgumentError( 'Got duplicate overrides for the same builder option: ' '$builderKey=$option. Only one is allowed.'); } config[option] = value; } return builderConfigOverrides; } /// Returns build directories with output information parsed from output /// arguments. /// /// Each output option is split on `:` where the first value is the /// root input directory and the second value output directory. /// If no delimeter is provided the root input directory will be null. Set<BuildDirectory> _parseBuildDirs(ArgResults argResults) { var outputs = argResults[outputOption] as List<String>; if (outputs == null) return <BuildDirectory>{}; var result = <BuildDirectory>{}; var outputPaths = <String>{}; void checkExisting(String outputDir) { if (outputPaths.contains(outputDir)) { throw ArgumentError.value(outputs.join(' '), '--output', 'Duplicate output directories are not allowed, got'); } outputPaths.add(outputDir); } for (var option in argResults[outputOption] as List<String>) { var split = option.split(':'); if (split.length == 1) { var output = split.first; checkExisting(output); result.add(BuildDirectory('', outputLocation: OutputLocation(output, hoist: false))); } else if (split.length >= 2) { var output = split.sublist(1).join(':'); checkExisting(output); var root = split.first; if (root.contains('/')) { throw ArgumentError.value( option, '--output', 'Input root can not be nested'); } result.add( BuildDirectory(split.first, outputLocation: OutputLocation(output))); } } return result; } /// Throws a [UsageException] if [arg] looks like anything other than a top /// level directory. String _checkTopLevel(String arg, Command command) { var parts = p.split(arg); if (parts.length > 1 || arg == '.') { throw UsageException( 'Only top level directories such as `web` or `test` are allowed as ' 'positional args, but got `$arg`', command.usage); } return arg; } /// Parses positional arguments as plain build directories. Set<BuildDirectory> _parsePositionalBuildDirs( Iterable<String> positionalArgs, Command command) => { for (var arg in positionalArgs) BuildDirectory(_checkTopLevel(arg, command)) }; /// Returns build filters parsed from [buildFilterOption] arguments. /// /// These support `package:` uri syntax as well as regular path syntax, /// with glob support for both package names and paths. Set<BuildFilter> _parseBuildFilters(ArgResults argResults, String rootPackage) { var filterArgs = argResults[buildFilterOption] as List<String>; if (filterArgs?.isEmpty ?? true) return null; try { return { for (var arg in filterArgs) BuildFilter.fromArg(arg, rootPackage), }; } on FormatException catch (e) { throw ArgumentError.value( e.source, '--build-filter', 'Not a valid build filter, must be either a relative path or ' '`package:` uri.\n\n$e'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/serve.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:http_multi_server/http_multi_server.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf_io.dart'; import '../generate/build.dart'; import '../logging/std_io_logging.dart'; import '../server/server.dart'; import 'options.dart'; import 'watch.dart'; /// Extends [WatchCommand] with dev server functionality. class ServeCommand extends WatchCommand { ServeCommand() { argParser ..addOption(hostnameOption, help: 'Specify the hostname to serve on', defaultsTo: 'localhost') ..addFlag(logRequestsOption, defaultsTo: false, negatable: false, help: 'Enables logging for each request to the server.') ..addFlag(liveReloadOption, defaultsTo: false, negatable: false, help: 'Enables automatic page reloading on rebuilds. ' "Can't be used together with --$hotReloadOption.") ..addFlag(hotReloadOption, defaultsTo: false, negatable: false, help: 'Enables automatic reloading of changed modules on rebuilds. ' "Can't be used together with --$liveReloadOption."); } @override String get invocation => '${super.invocation} [<directory>[:<port>]]...'; @override String get name => 'serve'; @override String get description => 'Runs a development server that serves the specified targets and runs ' 'builds based on file system updates.'; @override ServeOptions readOptions() => ServeOptions.fromParsedArgs( argResults, argResults.rest, packageGraph.root.name, this); @override Future<int> run() async { final servers = <ServeTarget, HttpServer>{}; return _runServe(servers).whenComplete(() async { await Future.wait( servers.values.map((server) => server.close(force: true))); }); } Future<int> _runServe(Map<ServeTarget, HttpServer> servers) async { var options = readOptions(); try { await Future.wait(options.serveTargets.map((target) async { servers[target] = await HttpMultiServer.bind(options.hostName, target.port); })); } on SocketException catch (e) { var listener = Logger.root.onRecord.listen(stdIOLogListener()); if (e.address != null && e.port != null) { logger.severe( 'Error starting server at ${e.address.address}:${e.port}, address ' 'is already in use. Please kill the server running on that port or ' 'serve on a different port and restart this process.'); } else { logger.severe('Error starting server on ${options.hostName}.'); } await listener.cancel(); return ExitCode.osError.code; } var handler = await watch( builderApplications, deleteFilesByDefault: options.deleteFilesByDefault, enableLowResourcesMode: options.enableLowResourcesMode, configKey: options.configKey, buildDirs: options.buildDirs, outputSymlinksOnly: options.outputSymlinksOnly, packageGraph: packageGraph, trackPerformance: options.trackPerformance, skipBuildScriptCheck: options.skipBuildScriptCheck, verbose: options.verbose, builderConfigOverrides: options.builderConfigOverrides, isReleaseBuild: options.isReleaseBuild, logPerformanceDir: options.logPerformanceDir, directoryWatcherFactory: options.directoryWatcherFactory, buildFilters: options.buildFilters, ); if (handler == null) return ExitCode.config.code; servers.forEach((target, server) { serveRequests( server, handler.handlerFor(target.dir, logRequests: options.logRequests, buildUpdates: options.buildUpdates)); }); _ensureBuildWebCompilersDependency(packageGraph, logger); final completer = Completer<int>(); handleBuildResultsStream(handler.buildResults, completer); _logServerPorts(handler, options, logger); return completer.future; } void _logServerPorts( ServeHandler serveHandler, ServeOptions options, Logger logger) async { await serveHandler.currentBuild; // Warn if in serve mode with no servers. if (options.serveTargets.isEmpty) { logger.warning( 'Found no known web directories to serve, but running in `serve` ' 'mode. You may expliclity provide a directory to serve with trailing ' 'args in <dir>[:<port>] format.'); } else { for (var target in options.serveTargets) { stdout.writeln('Serving `${target.dir}` on ' 'http://${options.hostName}:${target.port}'); } } } } void _ensureBuildWebCompilersDependency(PackageGraph packageGraph, Logger log) { if (!packageGraph.allPackages.containsKey('build_web_compilers')) { log.warning(''' Missing dev dependency on package:build_web_compilers, which is required to serve Dart compiled to JavaScript. Please update your dev_dependencies section of your pubspec.yaml: dev_dependencies: build_runner: any build_test: any build_web_compilers: any'''); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/watch.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build_runner/src/entrypoint/options.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import '../generate/build.dart'; import 'base_command.dart'; /// A command that watches the file system for updates and rebuilds as /// appropriate. class WatchCommand extends BuildRunnerCommand { @override String get invocation => '${super.invocation} [directories]'; @override String get name => 'watch'; @override String get description => 'Builds the specified targets, watching the file system for updates and ' 'rebuilding as appropriate.'; WatchCommand() { argParser.addFlag(usePollingWatcherOption, help: 'Use a polling watcher instead of the current platforms default ' 'watcher implementation. This should generally only be used if ' 'you are having problems with the default watcher, as it is ' 'generally less efficient.'); } @override WatchOptions readOptions() => WatchOptions.fromParsedArgs( argResults, argResults.rest, packageGraph.root.name, this); @override Future<int> run() async { var options = readOptions(); var handler = await watch( builderApplications, deleteFilesByDefault: options.deleteFilesByDefault, enableLowResourcesMode: options.enableLowResourcesMode, configKey: options.configKey, buildDirs: options.buildDirs, outputSymlinksOnly: options.outputSymlinksOnly, packageGraph: packageGraph, trackPerformance: options.trackPerformance, skipBuildScriptCheck: options.skipBuildScriptCheck, verbose: options.verbose, builderConfigOverrides: options.builderConfigOverrides, isReleaseBuild: options.isReleaseBuild, logPerformanceDir: options.logPerformanceDir, directoryWatcherFactory: options.directoryWatcherFactory, buildFilters: options.buildFilters, ); if (handler == null) return ExitCode.config.code; final completer = Completer<int>(); handleBuildResultsStream(handler.buildResults, completer); return completer.future; } /// Listens to [buildResults], handling certain types of errors and completing /// [completer] appropriately. void handleBuildResultsStream( Stream<BuildResult> buildResults, Completer<int> completer) async { var subscription = buildResults.listen((result) { if (completer.isCompleted) return; if (result.status == BuildStatus.failure) { if (result.failureType == FailureType.buildScriptChanged) { completer.completeError(BuildScriptChangedException()); } else if (result.failureType == FailureType.buildConfigChanged) { completer.completeError(BuildConfigChangedException()); } } }); await subscription.asFuture(); if (!completer.isCompleted) completer.complete(ExitCode.success.code); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/entrypoint/test.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:async/async.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import 'package:path/path.dart' as p; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import '../generate/build.dart'; import 'base_command.dart'; import 'options.dart'; /// A command that does a single build and then runs tests using the compiled /// assets. class TestCommand extends BuildRunnerCommand { TestCommand(PackageGraph packageGraph) : super( // Use symlinks by default, if package:test supports it. symlinksDefault: _packageTestSupportsSymlinks(packageGraph) && !Platform.isWindows, ); @override String get invocation => '${super.invocation.replaceFirst('[arguments]', '[build-arguments]')} ' '[-- [test-arguments]]'; @override String get name => 'test'; @override String get description => 'Performs a single build of the test directory only and then runs tests ' 'using the compiled assets.'; @override SharedOptions readOptions() { // This command doesn't allow specifying directories to build, instead it // always builds the `test` directory. // // Here we validate that [argResults.rest] is exactly equal to all the // arguments after the `--`. if (argResults.rest.isNotEmpty) { void throwUsageException() { throw UsageException( 'The `test` command does not support positional args before the, ' '`--` separator, which should separate build args from test args.', usage); } var separatorPos = argResults.arguments.indexOf('--'); if (separatorPos < 0) { throwUsageException(); } var expectedRest = argResults.arguments.skip(separatorPos + 1).toList(); if (argResults.rest.length != expectedRest.length) { throwUsageException(); } for (var i = 0; i < argResults.rest.length; i++) { if (expectedRest[i] != argResults.rest[i]) { throwUsageException(); } } } return SharedOptions.fromParsedArgs( argResults, ['test'], packageGraph.root.name, this); } @override Future<int> run() async { SharedOptions options; // We always run our tests in a temp dir. var tempPath = Directory.systemTemp .createTempSync('build_runner_test') .absolute .uri .toFilePath(); try { _ensureBuildTestDependency(packageGraph); options = readOptions(); var buildDirs = (options.buildDirs ?? <BuildDirectory>{}) // Build test by default. ..add(BuildDirectory('test', outputLocation: OutputLocation(tempPath, useSymlinks: options.outputSymlinksOnly, hoist: false))); var result = await build( builderApplications, deleteFilesByDefault: options.deleteFilesByDefault, enableLowResourcesMode: options.enableLowResourcesMode, configKey: options.configKey, buildDirs: buildDirs, outputSymlinksOnly: options.outputSymlinksOnly, packageGraph: packageGraph, trackPerformance: options.trackPerformance, skipBuildScriptCheck: options.skipBuildScriptCheck, verbose: options.verbose, builderConfigOverrides: options.builderConfigOverrides, isReleaseBuild: options.isReleaseBuild, logPerformanceDir: options.logPerformanceDir, buildFilters: options.buildFilters, ); if (result.status == BuildStatus.failure) { stdout.writeln('Skipping tests due to build failure'); return result.failureType.exitCode; } return await _runTests(tempPath); } on _BuildTestDependencyError catch (e) { stdout.writeln(e); return ExitCode.config.code; } finally { // Clean up the output dir. await Directory(tempPath).delete(recursive: true); } } /// Runs tests using [precompiledPath] as the precompiled test directory. Future<int> _runTests(String precompiledPath) async { stdout.writeln('Running tests...\n'); var extraTestArgs = argResults.rest; var testProcess = await Process.start( pubBinary, [ 'run', 'test', '--precompiled', precompiledPath, ...extraTestArgs, ], mode: ProcessStartMode.inheritStdio); _ensureProcessExit(testProcess); return testProcess.exitCode; } } bool _packageTestSupportsSymlinks(PackageGraph packageGraph) { var testPackage = packageGraph['test']; if (testPackage == null) return false; var pubspecPath = p.join(testPackage.path, 'pubspec.yaml'); var pubspec = Pubspec.parse(File(pubspecPath).readAsStringSync()); if (pubspec.version == null) return false; return pubspec.version >= Version(1, 3, 0); } void _ensureBuildTestDependency(PackageGraph packageGraph) { if (!packageGraph.allPackages.containsKey('build_test')) { throw _BuildTestDependencyError(); } } void _ensureProcessExit(Process process) { var signalsSub = _exitProcessSignals.listen((signal) async { stdout.writeln('waiting for subprocess to exit...'); }); process.exitCode.then((_) { signalsSub?.cancel(); signalsSub = null; }); } Stream<ProcessSignal> get _exitProcessSignals => Platform.isWindows ? ProcessSignal.sigint.watch() : StreamGroup.merge( [ProcessSignal.sigterm.watch(), ProcessSignal.sigint.watch()]); class _BuildTestDependencyError extends StateError { _BuildTestDependencyError() : super(''' Missing dev dependency on package:build_test, which is required to run tests. Please update your dev_dependencies section of your pubspec.yaml: dev_dependencies: build_runner: any build_test: any # If you need to run web tests, you will also need this dependency. build_web_compilers: any '''); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/path_to_asset_id.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build/build.dart'; import 'package:path/path.dart' as p; AssetId pathToAssetId( String rootPackage, String rootDir, List<String> pathSegments) { var packagesIndex = pathSegments.indexOf('packages'); rootDir ??= ''; return packagesIndex >= 0 ? AssetId(pathSegments[packagesIndex + 1], p.join('lib', p.joinAll(pathSegments.sublist(packagesIndex + 2)))) : AssetId(rootPackage, p.joinAll([rootDir].followedBy(pathSegments))); } /// Returns null for paths that neither a lib nor starts from a rootDir String assetIdToPath(AssetId assetId, String rootDir) => assetId.path.startsWith('lib/') ? assetId.path.replaceFirst('lib/', 'packages/${assetId.package}/') : assetId.path.startsWith('$rootDir/') ? assetId.path.substring(rootDir.length + 1) : null;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/server.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:build/build.dart'; import 'package:build_runner/src/entrypoint/options.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/generate/performance_tracker.dart'; import 'package:crypto/crypto.dart'; import 'package:glob/glob.dart'; import 'package:logging/logging.dart'; import 'package:mime/mime.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart' as shelf; import 'package:shelf_web_socket/shelf_web_socket.dart'; import 'package:timing/timing.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import '../generate/watch_impl.dart'; import 'asset_graph_handler.dart'; import 'path_to_asset_id.dart'; const _performancePath = r'$perf'; final _graphPath = r'$graph'; final _assetsDigestPath = r'$assetDigests'; final _buildUpdatesProtocol = r'$buildUpdates'; final entrypointExtensionMarker = '/* ENTRYPOINT_EXTENTION_MARKER */'; final _logger = Logger('Serve'); enum PerfSortOrder { startTimeAsc, startTimeDesc, stopTimeAsc, stopTimeDesc, durationAsc, durationDesc, innerDurationAsc, innerDurationDesc } ServeHandler createServeHandler(WatchImpl watch) { var rootPackage = watch.packageGraph.root.name; var assetGraphHanderCompleter = Completer<AssetGraphHandler>(); var assetHandlerCompleter = Completer<AssetHandler>(); watch.ready.then((_) async { assetHandlerCompleter.complete(AssetHandler(watch.reader, rootPackage)); assetGraphHanderCompleter.complete( AssetGraphHandler(watch.reader, rootPackage, watch.assetGraph)); }); return ServeHandler._(watch, assetHandlerCompleter.future, assetGraphHanderCompleter.future, rootPackage); } class ServeHandler implements BuildState { final WatchImpl _state; BuildResult _lastBuildResult; final String _rootPackage; final Future<AssetHandler> _assetHandler; final Future<AssetGraphHandler> _assetGraphHandler; final BuildUpdatesWebSocketHandler _webSocketHandler; ServeHandler._(this._state, this._assetHandler, this._assetGraphHandler, this._rootPackage) : _webSocketHandler = BuildUpdatesWebSocketHandler(_state) { _state.buildResults.listen((result) { _lastBuildResult = result; _webSocketHandler.emitUpdateMessage(result); }).onDone(_webSocketHandler.close); } @override Future<BuildResult> get currentBuild => _state.currentBuild; @override Stream<BuildResult> get buildResults => _state.buildResults; shelf.Handler handlerFor(String rootDir, {bool logRequests, BuildUpdatesOption buildUpdates}) { buildUpdates ??= BuildUpdatesOption.none; logRequests ??= false; if (p.url.split(rootDir).length != 1 || rootDir == '.') { throw ArgumentError.value( rootDir, 'directory', 'Only top level directories such as `web` or `test` can be served, got', ); } _state.currentBuild.then((_) { // If the first build fails with a handled exception, we might not have // an asset graph and can't do this check. if (_state.assetGraph == null) return; _warnForEmptyDirectory(rootDir); }); var cascade = shelf.Cascade(); if (buildUpdates != BuildUpdatesOption.none) { cascade = cascade.add(_webSocketHandler.createHandlerByRootDir(rootDir)); } cascade = cascade.add(_blockOnCurrentBuild).add((shelf.Request request) async { if (request.url.path == _performancePath) { return _performanceHandler(request); } if (request.url.path == _assetsDigestPath) { return _assetsDigestHandler(request, rootDir); } if (request.url.path.startsWith(_graphPath)) { var graphHandler = await _assetGraphHandler; return await graphHandler.handle( request.change(path: _graphPath), rootDir); } var assetHandler = await _assetHandler; return assetHandler.handle(request, rootDir: rootDir); }); var pipeline = shelf.Pipeline(); if (logRequests) { pipeline = pipeline.addMiddleware(_logRequests); } switch (buildUpdates) { case BuildUpdatesOption.liveReload: pipeline = pipeline.addMiddleware(_injectLiveReloadClientCode); break; case BuildUpdatesOption.hotReload: pipeline = pipeline.addMiddleware(_injectHotReloadClientCode); break; case BuildUpdatesOption.none: break; } return pipeline.addHandler(cascade.handler); } Future<shelf.Response> _blockOnCurrentBuild(void _) async { await currentBuild; return shelf.Response.notFound(''); } shelf.Response _performanceHandler(shelf.Request request) { var hideSkipped = false; var detailedSlices = false; var slicesResolution = 5; var sortOrder = PerfSortOrder.startTimeAsc; var filter = request.url.queryParameters['filter'] ?? ''; if (request.url.queryParameters['hideSkipped']?.toLowerCase() == 'true') { hideSkipped = true; } if (request.url.queryParameters['detailedSlices']?.toLowerCase() == 'true') { detailedSlices = true; } if (request.url.queryParameters.containsKey('slicesResolution')) { slicesResolution = int.parse(request.url.queryParameters['slicesResolution']); } if (request.url.queryParameters.containsKey('sortOrder')) { sortOrder = PerfSortOrder .values[int.parse(request.url.queryParameters['sortOrder'])]; } return shelf.Response.ok( _renderPerformance(_lastBuildResult.performance, hideSkipped, detailedSlices, slicesResolution, sortOrder, filter), headers: {HttpHeaders.contentTypeHeader: 'text/html'}); } Future<shelf.Response> _assetsDigestHandler( shelf.Request request, String rootDir) async { var assertPathList = (jsonDecode(await request.readAsString()) as List).cast<String>(); var rootPackage = _state.packageGraph.root.name; var results = <String, String>{}; for (final path in assertPathList) { try { var assetId = pathToAssetId(rootPackage, rootDir, p.url.split(path)); var digest = await _state.reader.digest(assetId); results[path] = digest.toString(); } on AssetNotFoundException { results.remove(path); } } return shelf.Response.ok(jsonEncode(results), headers: {HttpHeaders.contentTypeHeader: 'application/json'}); } void _warnForEmptyDirectory(String rootDir) { if (!_state.assetGraph .packageNodes(_rootPackage) .any((n) => n.id.path.startsWith('$rootDir/'))) { _logger.warning('Requested a server for `$rootDir` but this directory ' 'has no assets in the build. You may need to add some sources or ' 'include this directory in some target in your `build.yaml`'); } } } /// Class that manages web socket connection handler to inform clients about /// build updates class BuildUpdatesWebSocketHandler { final connectionsByRootDir = <String, List<WebSocketChannel>>{}; final shelf.Handler Function(Function, {Iterable<String> protocols}) _handlerFactory; final _internalHandlers = <String, shelf.Handler>{}; final WatchImpl _state; BuildUpdatesWebSocketHandler(this._state, [this._handlerFactory = webSocketHandler]); shelf.Handler createHandlerByRootDir(String rootDir) { if (!_internalHandlers.containsKey(rootDir)) { var closureForRootDir = (WebSocketChannel webSocket, String protocol) => _handleConnection(webSocket, protocol, rootDir); _internalHandlers[rootDir] = _handlerFactory(closureForRootDir, protocols: [_buildUpdatesProtocol]); } return _internalHandlers[rootDir]; } Future emitUpdateMessage(BuildResult buildResult) async { if (buildResult.status != BuildStatus.success) return; var digests = <AssetId, String>{}; for (var assetId in buildResult.outputs) { var digest = await _state.reader.digest(assetId); digests[assetId] = digest.toString(); } for (var rootDir in connectionsByRootDir.keys) { var resultMap = <String, String>{}; for (var assetId in digests.keys) { var path = assetIdToPath(assetId, rootDir); if (path != null) { resultMap[path] = digests[assetId]; } } for (var connection in connectionsByRootDir[rootDir]) { connection.sink.add(jsonEncode(resultMap)); } } } void _handleConnection( WebSocketChannel webSocket, String protocol, String rootDir) async { if (!connectionsByRootDir.containsKey(rootDir)) { connectionsByRootDir[rootDir] = []; } connectionsByRootDir[rootDir].add(webSocket); await webSocket.stream.drain(); connectionsByRootDir[rootDir].remove(webSocket); if (connectionsByRootDir[rootDir].isEmpty) { connectionsByRootDir.remove(rootDir); } } Future<void> close() { return Future.wait(connectionsByRootDir.values .expand((x) => x) .map((connection) => connection.sink.close())); } } shelf.Handler Function(shelf.Handler) _injectBuildUpdatesClientCode( String scriptName) => (innerHandler) { return (shelf.Request request) async { if (!request.url.path.endsWith('.js')) { return innerHandler(request); } var response = await innerHandler(request); // TODO: Find a way how to check and/or modify body without reading it // whole. var body = await response.readAsString(); if (body.startsWith(entrypointExtensionMarker)) { body += _buildUpdatesInjectedJS(scriptName); var originalEtag = response.headers[HttpHeaders.etagHeader]; if (originalEtag != null) { var newEtag = base64.encode(md5.convert(body.codeUnits).bytes); var newHeaders = Map.of(response.headers); newHeaders[HttpHeaders.etagHeader] = newEtag; if (request.headers[HttpHeaders.ifNoneMatchHeader] == newEtag) { return shelf.Response.notModified(headers: newHeaders); } response = response.change(headers: newHeaders); } } return response.change(body: body); }; }; final _injectHotReloadClientCode = _injectBuildUpdatesClientCode('hot_reload_client.dart'); final _injectLiveReloadClientCode = _injectBuildUpdatesClientCode('live_reload_client'); /// Hot-/live- reload config /// /// Listen WebSocket for updates in build results String _buildUpdatesInjectedJS(String scriptName) => '''\n // Injected by build_runner for build updates support window.\$dartLoader.forceLoadModule('packages/build_runner/src/server/build_updates_client/$scriptName'); '''; class AssetHandler { final FinalizedReader _reader; final String _rootPackage; final _typeResolver = MimeTypeResolver(); AssetHandler(this._reader, this._rootPackage); Future<shelf.Response> handle(shelf.Request request, {String rootDir}) => (request.url.path.endsWith('/') || request.url.path.isEmpty) ? _handle( request.headers, pathToAssetId( _rootPackage, rootDir, request.url.pathSegments .followedBy(const ['index.html']).toList()), fallbackToDirectoryList: true) : _handle(request.headers, pathToAssetId(_rootPackage, rootDir, request.url.pathSegments)); Future<shelf.Response> _handle( Map<String, String> requestHeaders, AssetId assetId, {bool fallbackToDirectoryList = false}) async { try { if (!await _reader.canRead(assetId)) { var reason = await _reader.unreadableReason(assetId); switch (reason) { case UnreadableReason.failed: return shelf.Response.internalServerError( body: 'Build failed for $assetId'); case UnreadableReason.notOutput: return shelf.Response.notFound('$assetId was not output'); case UnreadableReason.notFound: if (fallbackToDirectoryList) { return shelf.Response.notFound(await _findDirectoryList(assetId)); } return shelf.Response.notFound('Not Found'); default: return shelf.Response.notFound('Not Found'); } } } on ArgumentError catch (_) { return shelf.Response.notFound('Not Found'); } var etag = base64.encode((await _reader.digest(assetId)).bytes); var contentType = _typeResolver.lookup(assetId.path); if (contentType == 'text/x-dart') contentType += '; charset=utf-8'; var headers = { HttpHeaders.contentTypeHeader: contentType, HttpHeaders.etagHeader: etag, // We always want this revalidated, which requires specifying both // max-age=0 and must-revalidate. // // See spec https://goo.gl/Lhvttg for more info about this header. HttpHeaders.cacheControlHeader: 'max-age=0, must-revalidate', }; if (requestHeaders[HttpHeaders.ifNoneMatchHeader] == etag) { // This behavior is still useful for cases where a file is hit // without a cache-busting query string. return shelf.Response.notModified(headers: headers); } var bytes = await _reader.readAsBytes(assetId); headers[HttpHeaders.contentLengthHeader] = '${bytes.length}'; return shelf.Response.ok(bytes, headers: headers); } Future<String> _findDirectoryList(AssetId from) async { var directoryPath = p.url.dirname(from.path); var glob = p.url.join(directoryPath, '*'); var result = await _reader.findAssets(Glob(glob)).map((a) => a.path).toList(); var message = StringBuffer('Could not find ${from.path}'); if (result.isEmpty) { message.write(' or any files in $directoryPath. '); } else { message ..write('. $directoryPath contains:') ..writeAll(result, '\n') ..writeln(); } message .write(' See https://github.com/dart-lang/build/blob/master/docs/faq.md' '#why-cant-i-see-a-file-i-know-exists'); return '$message'; } } String _renderPerformance( BuildPerformance performance, bool hideSkipped, bool detailedSlices, int slicesResolution, PerfSortOrder sortOrder, String filter) { try { var rows = StringBuffer(); final resolution = Duration(milliseconds: slicesResolution); var count = 0, maxSlices = 1, max = 0, min = performance.stopTime.millisecondsSinceEpoch - performance.startTime.millisecondsSinceEpoch; void writeRow(BuilderActionPerformance action, BuilderActionStagePerformance stage, TimeSlice slice) { var actionKey = '${action.builderKey}:${action.primaryInput}'; var tooltip = '<div class=perf-tooltip>' '<p><b>Builder:</b> ${action.builderKey}</p>' '<p><b>Input:</b> ${action.primaryInput}</p>' '<p><b>Stage:</b> ${stage.label}</p>' '<p><b>Stage time:</b> ' '${stage.startTime.difference(performance.startTime).inMilliseconds / 1000}s - ' '${stage.stopTime.difference(performance.startTime).inMilliseconds / 1000}s</p>' '<p><b>Stage real duration:</b> ${stage.duration.inMilliseconds / 1000} seconds</p>' '<p><b>Stage user duration:</b> ${stage.innerDuration.inMilliseconds / 1000} seconds</p>'; if (slice != stage) { tooltip += '<p><b>Slice time:</b> ' '${slice.startTime.difference(performance.startTime).inMilliseconds / 1000}s - ' '${slice.stopTime.difference(performance.startTime).inMilliseconds / 1000}s</p>' '<p><b>Slice duration:</b> ${slice.duration.inMilliseconds / 1000} seconds</p>'; } tooltip += '</div>'; var start = slice.startTime.millisecondsSinceEpoch - performance.startTime.millisecondsSinceEpoch; var end = slice.stopTime.millisecondsSinceEpoch - performance.startTime.millisecondsSinceEpoch; if (min > start) min = start; if (max < end) max = end; rows.writeln( ' ["$actionKey", "${stage.label}", "$tooltip", $start, $end],'); ++count; } final filterRegex = filter.isNotEmpty ? RegExp(filter) : null; final actions = performance.actions .where((action) => !hideSkipped || action.stages.any((stage) => stage.label == 'Build')) .where((action) => filterRegex == null || filterRegex.hasMatch('${action.builderKey}:${action.primaryInput}')) .toList(); int Function(BuilderActionPerformance, BuilderActionPerformance) comparator; switch (sortOrder) { case PerfSortOrder.startTimeAsc: comparator = (a1, a2) => a1.startTime.compareTo(a2.startTime); break; case PerfSortOrder.startTimeDesc: comparator = (a1, a2) => a2.startTime.compareTo(a1.startTime); break; case PerfSortOrder.stopTimeAsc: comparator = (a1, a2) => a1.stopTime.compareTo(a2.stopTime); break; case PerfSortOrder.stopTimeDesc: comparator = (a1, a2) => a2.stopTime.compareTo(a1.stopTime); break; case PerfSortOrder.durationAsc: comparator = (a1, a2) => a1.duration.compareTo(a2.duration); break; case PerfSortOrder.durationDesc: comparator = (a1, a2) => a2.duration.compareTo(a1.duration); break; case PerfSortOrder.innerDurationAsc: comparator = (a1, a2) => a1.innerDuration.compareTo(a2.innerDuration); break; case PerfSortOrder.innerDurationDesc: comparator = (a1, a2) => a2.innerDuration.compareTo(a1.innerDuration); break; } actions.sort(comparator); for (var action in actions) { if (hideSkipped && !action.stages.any((stage) => stage.label == 'Build')) { continue; } for (var stage in action.stages) { if (!detailedSlices) { writeRow(action, stage, stage); continue; } var slices = stage.slices.fold<List<TimeSlice>>([], (list, slice) { if (list.isNotEmpty && slice.startTime.difference(list.last.stopTime) < resolution) { // concat with previous if gap less than resolution list.last = TimeSlice(list.last.startTime, slice.stopTime); } else { if (list.length > 1 && list.last.duration < resolution) { // remove previous if its duration less than resolution list.last = slice; } else { list.add(slice); } } return list; }); if (slices.isNotEmpty) { for (var slice in slices) { writeRow(action, stage, slice); } } else { writeRow(action, stage, stage); } if (maxSlices < slices.length) maxSlices = slices.length; } } if (max - min < 1000) { rows.writeln(' [' '"https://github.com/google/google-visualization-issues/issues/2269"' ', "", "", $min, ${min + 1000}]'); } return ''' <html> <head> <script src="https://www.gstatic.com/charts/loader.js"></script> <script> google.charts.load('current', {'packages':['timeline']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('timeline'); var chart = new google.visualization.Timeline(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({ type: 'string', id: 'ActionKey' }); dataTable.addColumn({ type: 'string', id: 'Stage' }); dataTable.addColumn({ type: 'string', role: 'tooltip', p: { html: true } }); dataTable.addColumn({ type: 'number', id: 'Start' }); dataTable.addColumn({ type: 'number', id: 'End' }); dataTable.addRows([ $rows ]); console.log('rendering', $count, 'blocks, max', $maxSlices, 'slices in stage, resolution', $slicesResolution, 'ms'); var options = { tooltip: { isHtml: true } }; var statusText = document.getElementById('status'); var timeoutId; var updateFunc = function () { if (timeoutId) { // don't schedule more than one at a time return; } statusText.innerText = 'Drawing table...'; console.time('draw-time'); timeoutId = setTimeout(function () { chart.draw(dataTable, options); console.timeEnd('draw-time'); statusText.innerText = ''; timeoutId = null; }); }; updateFunc(); window.addEventListener('resize', updateFunc); } </script> <style> html, body { width: 100%; height: 100%; margin: 0; } body { display: flex; flex-direction: column; } #timeline { display: flex; flex-direction: row; flex: 1; } .controls-header p { display: inline-block; margin: 0.5em; } .perf-tooltip { margin: 0.5em; } </style> </head> <body> <form class="controls-header" action="/$_performancePath" onchange="this.submit()"> <p><label><input type="checkbox" name="hideSkipped" value="true" ${hideSkipped ? 'checked' : ''}> Hide Skipped Actions</label></p> <p><label><input type="checkbox" name="detailedSlices" value="true" ${detailedSlices ? 'checked' : ''}> Show Async Slices</label></p> <p>Sort by: <select name="sortOrder"> <option value="0" ${sortOrder.index == 0 ? 'selected' : ''}>Start Time Asc</option> <option value="1" ${sortOrder.index == 1 ? 'selected' : ''}>Start Time Desc</option> <option value="2" ${sortOrder.index == 2 ? 'selected' : ''}>Stop Time Asc</option> <option value="3" ${sortOrder.index == 3 ? 'selected' : ''}>Stop Time Desc</option> <option value="5" ${sortOrder.index == 4 ? 'selected' : ''}>Real Duration Asc</option> <option value="5" ${sortOrder.index == 5 ? 'selected' : ''}>Real Duration Desc</option> <option value="6" ${sortOrder.index == 6 ? 'selected' : ''}>User Duration Asc</option> <option value="7" ${sortOrder.index == 7 ? 'selected' : ''}>User Duration Desc</option> </select></p> <p>Slices Resolution: <select name="slicesResolution"> <option value="0" ${slicesResolution == 0 ? 'selected' : ''}>0</option> <option value="1" ${slicesResolution == 1 ? 'selected' : ''}>1</option> <option value="3" ${slicesResolution == 3 ? 'selected' : ''}>3</option> <option value="5" ${slicesResolution == 5 ? 'selected' : ''}>5</option> <option value="10" ${slicesResolution == 10 ? 'selected' : ''}>10</option> <option value="15" ${slicesResolution == 15 ? 'selected' : ''}>15</option> <option value="20" ${slicesResolution == 20 ? 'selected' : ''}>20</option> <option value="25" ${slicesResolution == 25 ? 'selected' : ''}>25</option> </select></p> <p>Filter (RegExp): <input type="text" name="filter" value="$filter"></p> <p id="status"></p> </form> <div id="timeline"></div> </body> </html> '''; } on UnimplementedError catch (_) { return _enablePerformanceTracking; } on UnsupportedError catch (_) { return _enablePerformanceTracking; } } final _enablePerformanceTracking = ''' <html> <body> <p> Performance information not available, you must pass the `--track-performance` command line arg to enable performance tracking. </p> <body> </html> '''; /// [shelf.Middleware] that logs all requests, inspired by [shelf.logRequests]. shelf.Handler _logRequests(shelf.Handler innerHandler) { return (shelf.Request request) { var startTime = DateTime.now(); var watch = Stopwatch()..start(); return Future.sync(() => innerHandler(request)).then((response) { var logFn = response.statusCode >= 500 ? _logger.warning : _logger.info; var msg = _getMessage(startTime, response.statusCode, request.requestedUri, request.method, watch.elapsed); logFn(msg); return response; }, onError: (dynamic error, StackTrace stackTrace) { if (error is shelf.HijackException) throw error; var msg = _getMessage( startTime, 500, request.requestedUri, request.method, watch.elapsed); _logger.severe('$msg\r\n$error\r\n$stackTrace', true); throw error; }); }; } String _getMessage(DateTime requestTime, int statusCode, Uri requestedUri, String method, Duration elapsedTime) { return '${requestTime.toIso8601String()} ' '${humanReadable(elapsedTime)} ' '$method [$statusCode] ' '${requestedUri.path}${_formatQuery(requestedUri.query)}\r\n'; } String _formatQuery(String query) { return query == '' ? '' : '?$query'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/asset_graph_handler.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:build/build.dart'; import 'package:glob/glob.dart'; import 'package:shelf/shelf.dart' as shelf; import 'package:build_runner_core/src/asset_graph/graph.dart'; import 'package:build_runner_core/src/asset_graph/node.dart'; import 'path_to_asset_id.dart'; /// A handler for `/$graph` requests under a specific `rootDir`. class AssetGraphHandler { final AssetReader _reader; final String _rootPackage; final AssetGraph _assetGraph; AssetGraphHandler(this._reader, this._rootPackage, this._assetGraph); /// Returns a response with the information about a specific node in the /// graph. /// /// For an empty path, returns the HTML page to render the graph. /// /// For queries with `q=QUERY` will look for the assetNode referenced. /// QUERY can be an [AssetId] or a path. /// /// [AssetId] as `package|path` /// /// path as: /// - `packages/<package>/<path_under_lib>` /// - `<path_under_root_package>` /// - `<path_under_rootDir>` /// /// There may be some ambiguity between paths which are under the top-level of /// the root package, and those which are under the rootDir. Preference is /// given to the asset (if it exists) which is not under the implicit /// `rootDir`. For instance if the request is `$graph/web/main.dart` this will /// prefer to serve `<package>|web/main.dart`, but if it does not exist will /// fall back to `<package>|web/web/main.dart`. FutureOr<shelf.Response> handle(shelf.Request request, String rootDir) async { switch (request.url.path) { case '': if (!request.url.hasQuery) { return shelf.Response.ok( await _reader.readAsString( AssetId('build_runner', 'lib/src/server/graph_viz.html')), headers: {HttpHeaders.contentTypeHeader: 'text/html'}); } var query = request.url.queryParameters['q']?.trim(); if (query != null && query.isNotEmpty) { var filter = request.url.queryParameters['f']?.trim(); return _handleQuery(query, rootDir, filter: filter); } break; case 'assets.json': return _jsonResponse(_assetGraph.serialize()); } return shelf.Response.notFound('Bad request: "${request.url}".'); } Future<shelf.Response> _handleQuery(String query, String rootDir, {String filter}) async { var filterGlob = filter != null ? Glob(filter) : null; var pipeIndex = query.indexOf('|'); AssetId assetId; if (pipeIndex < 0) { var querySplit = query.split('/'); assetId = pathToAssetId( _rootPackage, querySplit.first, querySplit.skip(1).toList()); if (!_assetGraph.contains(assetId)) { var secondTry = pathToAssetId(_rootPackage, rootDir, querySplit); if (!_assetGraph.contains(secondTry)) { return shelf.Response.notFound( 'Could not find asset for path "$query". Tried:\n' '- $assetId\n' '- $secondTry'); } assetId = secondTry; } } else { assetId = AssetId.parse(query); if (!_assetGraph.contains(assetId)) { return shelf.Response.notFound( 'Could not find asset in build graph: $assetId'); } } var node = _assetGraph.get(assetId); var currentEdge = 0; var nodes = [ {'id': '${node.id}', 'label': '${node.id}'} ]; var edges = <Map<String, String>>[]; for (final output in node.outputs) { if (filterGlob != null && !filterGlob.matches(output.toString())) { continue; } edges.add( {'from': '${node.id}', 'to': '$output', 'id': 'e${currentEdge++}'}); nodes.add({'id': '$output', 'label': '$output'}); } if (node is NodeWithInputs) { for (final input in node.inputs) { if (filterGlob != null && !filterGlob.matches(input.toString())) { continue; } edges.add( {'from': '$input', 'to': '${node.id}', 'id': 'e${currentEdge++}'}); nodes.add({'id': '$input', 'label': '$input'}); } } var result = <String, dynamic>{ 'primary': { 'id': '${node.id}', 'hidden': node is GeneratedAssetNode ? node.isHidden : null, 'state': node is NodeWithInputs ? '${node.state}' : null, 'wasOutput': node is GeneratedAssetNode ? node.wasOutput : null, 'isFailure': node is GeneratedAssetNode ? node.isFailure : null, 'phaseNumber': node is NodeWithInputs ? node.phaseNumber : null, 'type': node.runtimeType.toString(), 'glob': node is GlobAssetNode ? node.glob.pattern : null, 'lastKnownDigest': node.lastKnownDigest.toString(), }, 'edges': edges, 'nodes': nodes, }; return _jsonResponse(_jsonUtf8Encoder.convert(result)); } } final _jsonUtf8Encoder = JsonUtf8Encoder(); shelf.Response _jsonResponse(List<int> body) => shelf.Response.ok(body, headers: {HttpHeaders.contentTypeHeader: 'application/json'});
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/build_updates_client/reloading_manager.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'package:graphs/graphs.dart' as graphs; import 'module.dart'; class HotReloadFailedException implements Exception { HotReloadFailedException(this._s); @override String toString() => "HotReloadFailedException: '$_s'"; final String _s; } /// Handles reloading order and hooks invocation class ReloadingManager { final Future<Module> Function(String) _reloadModule; final Module Function(String) _moduleLibraries; final void Function() _reloadPage; final List<String> Function(String moduleId) _moduleParents; final Iterable<String> Function() _allModules; final Map<String, int> _moduleOrdering = {}; SplayTreeSet<String> _dirtyModules; Completer<void> _running = Completer()..complete(); int moduleTopologicalCompare(String module1, String module2) { var topological = Comparable.compare(_moduleOrdering[module2], _moduleOrdering[module1]); // If modules are in cycle (same strongly connected component) compare their // string id, to ensure total ordering for SplayTreeSet uniqueness. return topological != 0 ? topological : module1.compareTo(module2); } void updateGraph() { var allModules = _allModules(); var stronglyConnectedComponents = graphs.stronglyConnectedComponents(allModules, _moduleParents); _moduleOrdering.clear(); for (var i = 0; i < stronglyConnectedComponents.length; i++) { for (var module in stronglyConnectedComponents[i]) { _moduleOrdering[module] = i; } } } ReloadingManager(this._reloadModule, this._moduleLibraries, this._reloadPage, this._moduleParents, this._allModules) { _dirtyModules = SplayTreeSet(moduleTopologicalCompare); } Future<void> reload(List<String> modules) async { _dirtyModules.addAll(modules); // As function is async, it can potentially be called second time while // first invocation is still running. In this case just mark as dirty and // wait until loop from the first call will do the work if (!_running.isCompleted) return await _running.future; _running = Completer(); var reloadedModules = 0; try { while (_dirtyModules.isNotEmpty) { var moduleId = _dirtyModules.first; _dirtyModules.remove(moduleId); ++reloadedModules; var existing = _moduleLibraries(moduleId); var data = existing.onDestroy(); var newVersion = await _reloadModule(moduleId); var success = newVersion.onSelfUpdate(data); if (success == true) continue; if (success == false) { print("Module '$moduleId' is marked as unreloadable. " 'Firing full page reload.'); _reloadPage(); _running.complete(); return; } var parentIds = _moduleParents(moduleId); if (parentIds == null || parentIds.isEmpty) { print("Module reloading wasn't handled by any of parents. " 'Firing full page reload.'); _reloadPage(); _running.complete(); return; } parentIds.sort(moduleTopologicalCompare); for (var parentId in parentIds) { var parentModule = _moduleLibraries(parentId); success = parentModule.onChildUpdate(moduleId, newVersion, data); if (success == true) continue; if (success == false) { print("Module '$moduleId' is marked as unreloadable. " 'Firing full page reload.'); _reloadPage(); _running.complete(); return; } _dirtyModules.add(parentId); } } print('$reloadedModules modules were hot-reloaded.'); } on HotReloadFailedException catch (e) { print('Error during script reloading. Firing full page reload. $e'); _reloadPage(); } _running.complete(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/build_updates_client/reload_handler.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'reloading_manager.dart'; /// Provides [listener] to handle web socket connection and reload invalidated /// modules using [ReloadingManager] class ReloadHandler { final String Function(String) _moduleIdByPath; final Map<String, String> _digests; final ReloadingManager _reloadingManager; ReloadHandler(this._digests, this._moduleIdByPath, this._reloadingManager); void listener(String data) async { var updatedAssetDigests = json.decode(data) as Map<String, dynamic>; var moduleIdsToReload = <String>[]; for (var path in updatedAssetDigests.keys) { if (_digests[path] == updatedAssetDigests[path]) { continue; } var moduleId = _moduleIdByPath(path); if (_digests.containsKey(path) && moduleId != null) { moduleIdsToReload.add(moduleId); } _digests[path] = updatedAssetDigests[path] as String; } if (moduleIdsToReload.isNotEmpty) { _reloadingManager.updateGraph(); await _reloadingManager.reload(moduleIdsToReload); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/server/build_updates_client/module.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. abstract class Library { Object onDestroy(); bool onSelfUpdate([Object data]); bool onChildUpdate(String childId, Library child, [Object data]); } /// Used for representation of amd modules that wraps several dart libraries /// inside class Module { /// Grouped by absolute library path starting with `package:` final Map<String, Library> libraries; Module(this.libraries); /// Calls onDestroy on each of underlined libraries and combines returned data Map<String, Object> onDestroy() { var data = <String, Object>{}; for (var key in libraries.keys) { data[key] = libraries[key].onDestroy(); } return data; } /// Calls onSelfUpdate on each of underlined libraries, returns aggregated /// result as "maximum" assuming true < null < false. Stops execution on first /// false result bool onSelfUpdate(Map<String, Object> data) { var result = true; for (var key in libraries.keys) { var success = libraries[key].onSelfUpdate(data[key]); if (success == false) { return false; } else if (success == null) { result = success; } } return result; } /// Calls onChildUpdate on each of underlined libraries, returns aggregated /// result as "maximum" assuming true < null < false. Stops execution on first /// false result bool onChildUpdate(String childId, Module child, Map<String, Object> data) { var result = true; // TODO(inayd): This is a rought implementation with lots of false positive // reloads. In current implementation every library in parent module should // know how to handle each library in child module. Also [roughLibraryKeyDecode] // depends on unreliable implementation details. Proper implementation // should rely on inner graph of dependencies between libraries in module, // to require only parent libraries which really depend on child ones to // handle it's updates. See dart-lang/build#1767. for (var parentKey in libraries.keys) { for (var childKey in child.libraries.keys) { var success = libraries[parentKey] .onChildUpdate(childKey, child.libraries[childKey], data[childKey]); if (success == false) { return false; } else if (success == null) { result = success; } } } return result; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/build_script_generate/build_script_generate.dart
// 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:build/build.dart' show BuilderOptions; import 'package:build_config/build_config.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:code_builder/code_builder.dart'; import 'package:dart_style/dart_style.dart'; import 'package:graphs/graphs.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import '../package_graph/build_config_overrides.dart'; import 'builder_ordering.dart'; const scriptLocation = '$entryPointDir/build.dart'; const scriptSnapshotLocation = '$scriptLocation.snapshot'; final _log = Logger('Entrypoint'); Future<String> generateBuildScript() => logTimedAsync(_log, 'Generating build script', _generateBuildScript); Future<String> _generateBuildScript() async { final builders = await _findBuilderApplications(); final library = Library((b) => b.body.addAll([ literalList( builders, refer('BuilderApplication', 'package:build_runner_core/build_runner_core.dart')) .assignFinal('_builders') .statement, _main() ])); final emitter = DartEmitter(Allocator.simplePrefixing()); try { return DartFormatter().format(''' // ignore_for_file: directives_ordering ${library.accept(emitter)}'''); } on FormatterException { _log.severe('Generated build script could not be parsed.\n' 'This is likely caused by a misconfigured builder definition.'); throw CannotBuildException(); } } /// Finds expressions to create all the `BuilderApplication` instances that /// should be applied packages in the build. /// /// Adds `apply` expressions based on the BuildefDefinitions from any package /// which has a `build.yaml`. Future<Iterable<Expression>> _findBuilderApplications() async { final builderApplications = <Expression>[]; final packageGraph = await PackageGraph.forThisPackage(); final orderedPackages = stronglyConnectedComponents<PackageNode>( [packageGraph.root], (node) => node.dependencies, equals: (a, b) => a.name == b.name, hashCode: (n) => n.name.hashCode, ).expand((c) => c); final buildConfigOverrides = await findBuildConfigOverrides(packageGraph, null); Future<BuildConfig> _packageBuildConfig(PackageNode package) async { if (buildConfigOverrides.containsKey(package.name)) { return buildConfigOverrides[package.name]; } try { return await BuildConfig.fromBuildConfigDir( package.name, package.dependencies.map((n) => n.name), package.path); } on ArgumentError catch (_) { // During the build an error will be logged. return BuildConfig.useDefault( package.name, package.dependencies.map((n) => n.name)); } } bool _isValidDefinition(dynamic definition) { // Filter out builderDefinitions with relative imports that aren't // from the root package, because they will never work. if (definition.import.startsWith('package:') as bool) return true; return definition.package == packageGraph.root.name; } final orderedConfigs = await Future.wait(orderedPackages.map(_packageBuildConfig)); final builderDefinitions = orderedConfigs .expand((c) => c.builderDefinitions.values) .where(_isValidDefinition); final orderedBuilders = findBuilderOrder(builderDefinitions).toList(); builderApplications.addAll(orderedBuilders.map(_applyBuilder)); final postProcessBuilderDefinitions = orderedConfigs .expand((c) => c.postProcessBuilderDefinitions.values) .where(_isValidDefinition); builderApplications .addAll(postProcessBuilderDefinitions.map(_applyPostProcessBuilder)); return builderApplications; } /// A method forwarding to `run`. Method _main() => Method((b) => b ..name = 'main' ..returns = refer('void') ..modifier = MethodModifier.async ..requiredParameters.add(Parameter((b) => b ..name = 'args' ..type = TypeReference((b) => b ..symbol = 'List' ..types.add(refer('String'))))) ..optionalParameters.add(Parameter((b) => b ..name = 'sendPort' ..type = refer('SendPort', 'dart:isolate'))) ..body = Block.of([ refer('run', 'package:build_runner/build_runner.dart') .call([refer('args'), refer('_builders')]) .awaited .assignVar('result') .statement, refer('sendPort') .nullSafeProperty('send') .call([refer('result')]).statement, refer('exitCode', 'dart:io').assign(refer('result')).statement, ])); /// An expression calling `apply` with appropriate setup for a Builder. Expression _applyBuilder(BuilderDefinition definition) { final namedArgs = <String, Expression>{}; if (definition.isOptional) { namedArgs['isOptional'] = literalTrue; } if (definition.buildTo == BuildTo.cache) { namedArgs['hideOutput'] = literalTrue; } else { namedArgs['hideOutput'] = literalFalse; } if (!identical(definition.defaults?.generateFor, InputSet.anything)) { final inputSetArgs = <String, Expression>{}; if (definition.defaults.generateFor.include != null) { inputSetArgs['include'] = literalConstList(definition.defaults.generateFor.include); } if (definition.defaults.generateFor.exclude != null) { inputSetArgs['exclude'] = literalConstList(definition.defaults.generateFor.exclude); } namedArgs['defaultGenerateFor'] = refer('InputSet', 'package:build_config/build_config.dart') .constInstance([], inputSetArgs); } if (definition.defaults?.options?.isNotEmpty ?? false) { namedArgs['defaultOptions'] = _constructBuilderOptions(definition.defaults.options); } if (definition.defaults?.devOptions?.isNotEmpty ?? false) { namedArgs['defaultDevOptions'] = _constructBuilderOptions(definition.defaults.devOptions); } if (definition.defaults?.releaseOptions?.isNotEmpty ?? false) { namedArgs['defaultReleaseOptions'] = _constructBuilderOptions(definition.defaults.releaseOptions); } if (definition.appliesBuilders.isNotEmpty) { namedArgs['appliesBuilders'] = literalList(definition.appliesBuilders); } var import = _buildScriptImport(definition.import); return refer('apply', 'package:build_runner_core/build_runner_core.dart') .call([ literalString(definition.key), literalList( definition.builderFactories.map((f) => refer(f, import)).toList()), _findToExpression(definition), ], namedArgs); } /// An expression calling `applyPostProcess` with appropriate setup for a /// PostProcessBuilder. Expression _applyPostProcessBuilder(PostProcessBuilderDefinition definition) { final namedArgs = <String, Expression>{}; if (definition.defaults?.generateFor != null) { final inputSetArgs = <String, Expression>{}; if (definition.defaults.generateFor.include != null) { inputSetArgs['include'] = literalConstList(definition.defaults.generateFor.include); } if (definition.defaults.generateFor.exclude != null) { inputSetArgs['exclude'] = literalConstList(definition.defaults.generateFor.exclude); } if (definition.defaults?.options?.isNotEmpty ?? false) { namedArgs['defaultOptions'] = _constructBuilderOptions(definition.defaults.options); } if (definition.defaults?.devOptions?.isNotEmpty ?? false) { namedArgs['defaultDevOptions'] = _constructBuilderOptions(definition.defaults.devOptions); } if (definition.defaults?.releaseOptions?.isNotEmpty ?? false) { namedArgs['defaultReleaseOptions'] = _constructBuilderOptions(definition.defaults.releaseOptions); } namedArgs['defaultGenerateFor'] = refer('InputSet', 'package:build_config/build_config.dart') .constInstance([], inputSetArgs); } var import = _buildScriptImport(definition.import); return refer('applyPostProcess', 'package:build_runner_core/build_runner_core.dart') .call([ literalString(definition.key), refer(definition.builderFactory, import), ], namedArgs); } /// Returns the actual import to put in the generated script based on an import /// found in the build.yaml. String _buildScriptImport(String import) { if (import.startsWith('package:')) { return import; } else if (import.startsWith('../') || import.startsWith('/')) { _log.warning('The `../` import syntax in build.yaml is now deprecated, ' 'instead do a normal relative import as if it was from the root of ' 'the package. Found `$import` in your `build.yaml` file.'); return import; } else { return p.url.relative(import, from: p.url.dirname(scriptLocation)); } } Expression _findToExpression(BuilderDefinition definition) { switch (definition.autoApply) { case AutoApply.none: return refer('toNoneByDefault', 'package:build_runner_core/build_runner_core.dart') .call([]); case AutoApply.dependents: return refer('toDependentsOf', 'package:build_runner_core/build_runner_core.dart') .call([literalString(definition.package)]); case AutoApply.allPackages: return refer('toAllPackages', 'package:build_runner_core/build_runner_core.dart') .call([]); case AutoApply.rootPackage: return refer('toRoot', 'package:build_runner_core/build_runner_core.dart') .call([]); } throw ArgumentError('Unhandled AutoApply type: ${definition.autoApply}'); } /// An expression creating a [BuilderOptions] from a json string. Expression _constructBuilderOptions(Map<String, dynamic> options) => refer('BuilderOptions', 'package:build/build.dart') .newInstance([literalMap(options)]);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/build_script_generate/builder_ordering.dart
// 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 'package:build_config/build_config.dart'; import 'package:graphs/graphs.dart'; /// Put [builders] into an order such that any builder which specifies /// [BuilderDefinition.requiredInputs] will come after any builder which /// produces a desired output. /// /// Builders will be ordered such that their `required_inputs` and `runs_before` /// constraints are met, but the rest of the ordering is arbitrary. Iterable<BuilderDefinition> findBuilderOrder( Iterable<BuilderDefinition> builders) { final consistentOrderBuilders = builders.toList() ..sort((a, b) => a.key.compareTo(b.key)); Iterable<BuilderDefinition> dependencies(BuilderDefinition parent) => consistentOrderBuilders.where((child) => _hasInputDependency(parent, child) || _mustRunBefore(parent, child)); var components = stronglyConnectedComponents<BuilderDefinition>( consistentOrderBuilders, dependencies, equals: (a, b) => a.key == b.key, hashCode: (b) => b.key.hashCode, ); return components.map((component) { if (component.length > 1) { throw ArgumentError('Required input cycle for ${component.toList()}'); } return component.single; }).toList(); } /// Whether [parent] has a `required_input` that wants to read outputs produced /// by [child]. bool _hasInputDependency(BuilderDefinition parent, BuilderDefinition child) { final childOutputs = child.buildExtensions.values.expand((v) => v).toSet(); return parent.requiredInputs .any((input) => childOutputs.any((output) => output.endsWith(input))); } /// Whether [child] specifies that it wants to run before [parent]. bool _mustRunBefore(BuilderDefinition parent, BuilderDefinition child) => child.runsBefore.contains(parent.key);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/build_script_generate/bootstrap.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:isolate'; import 'package:build_runner/src/build_script_generate/build_script_generate.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/io.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:stack_trace/stack_trace.dart'; final _logger = Logger('Bootstrap'); /// Generates the build script, snapshots it if needed, and runs it. /// /// Will retry once on [IsolateSpawnException]s to handle SDK updates. /// /// Returns the exit code from running the build script. /// /// If an exit code of 75 is returned, this function should be re-ran. Future<int> generateAndRun(List<String> args, {Logger logger}) async { logger ??= _logger; ReceivePort exitPort; ReceivePort errorPort; ReceivePort messagePort; StreamSubscription errorListener; int scriptExitCode; var tryCount = 0; var succeeded = false; while (tryCount < 2 && !succeeded) { tryCount++; exitPort?.close(); errorPort?.close(); messagePort?.close(); await errorListener?.cancel(); try { var buildScript = File(scriptLocation); var oldContents = ''; if (buildScript.existsSync()) { oldContents = buildScript.readAsStringSync(); } var newContents = await generateBuildScript(); // Only trigger a build script update if necessary. if (newContents != oldContents) { buildScript ..createSync(recursive: true) ..writeAsStringSync(newContents); } } on CannotBuildException { return ExitCode.config.code; } scriptExitCode = await _createSnapshotIfNeeded(logger); if (scriptExitCode != 0) return scriptExitCode; exitPort = ReceivePort(); errorPort = ReceivePort(); messagePort = ReceivePort(); errorListener = errorPort.listen((e) { final error = e[0]; final trace = e[1] as String; stderr ..writeln('\n\nYou have hit a bug in build_runner') ..writeln('Please file an issue with reproduction steps at ' 'https://github.com/dart-lang/build/issues\n\n') ..writeln(error) ..writeln(Trace.parse(trace).terse); if (scriptExitCode == 0) scriptExitCode = 1; }); try { await Isolate.spawnUri(Uri.file(p.absolute(scriptSnapshotLocation)), args, messagePort.sendPort, errorsAreFatal: true, onExit: exitPort.sendPort, onError: errorPort.sendPort); succeeded = true; } on IsolateSpawnException catch (e) { if (tryCount > 1) { logger.severe( 'Failed to spawn build script after retry. ' 'This is likely due to a misconfigured builder definition. ' 'See the generated script at $scriptLocation to find errors.', e); messagePort.sendPort.send(ExitCode.config.code); exitPort.sendPort.send(null); } else { logger.warning( 'Error spawning build script isolate, this is likely due to a Dart ' 'SDK update. Deleting snapshot and retrying...'); } await File(scriptSnapshotLocation).delete(); } } StreamSubscription exitCodeListener; exitCodeListener = messagePort.listen((isolateExitCode) { if (isolateExitCode is int) { scriptExitCode = isolateExitCode; } else { throw StateError( 'Bad response from isolate, expected an exit code but got ' '$isolateExitCode'); } exitCodeListener.cancel(); exitCodeListener = null; }); await exitPort.first; await errorListener.cancel(); await exitCodeListener?.cancel(); return scriptExitCode; } /// Creates a script snapshot for the build script in necessary. /// /// A snapshot is generated if: /// /// - It doesn't exist currently /// - Either build_runner or build_daemon point at a different location than /// they used to, see https://github.com/dart-lang/build/issues/1929. /// /// Returns zero for success or a number for failure which should be set to the /// exit code. Future<int> _createSnapshotIfNeeded(Logger logger) async { var assetGraphFile = File(assetGraphPathFor(scriptSnapshotLocation)); var snapshotFile = File(scriptSnapshotLocation); if (await snapshotFile.exists()) { // If we failed to serialize an asset graph for the snapshot, then we don't // want to re-use it because we can't check if it is up to date. if (!await assetGraphFile.exists()) { await snapshotFile.delete(); logger.warning('Deleted previous snapshot due to missing asset graph.'); } else if (!await _checkImportantPackageDeps()) { await snapshotFile.delete(); logger.warning('Deleted previous snapshot due to core package update'); } } String stderr; if (!await snapshotFile.exists()) { var mode = stdin.hasTerminal ? ProcessStartMode.normal : ProcessStartMode.detachedWithStdio; await logTimedAsync(logger, 'Creating build script snapshot...', () async { var snapshot = await Process.start(Platform.executable, ['--snapshot=$scriptSnapshotLocation', scriptLocation], mode: mode); stderr = (await snapshot.stderr .transform(utf8.decoder) .transform(LineSplitter()) .toList()) .join(''); }); if (!await snapshotFile.exists()) { logger.severe('Failed to snapshot build script $scriptLocation.\n' 'This is likely caused by a misconfigured builder definition.'); if (stderr.isNotEmpty) { logger.severe(stderr); } return ExitCode.config.code; } // Create _previousLocationsFile. await _checkImportantPackageDeps(); } return 0; } const _importantPackages = [ 'build_daemon', 'build_runner', ]; final _previousLocationsFile = File( p.url.join(p.url.dirname(scriptSnapshotLocation), '.packageLocations')); /// Returns whether the [_importantPackages] are all pointing at same locations /// from the previous run. /// /// Also updates the [_previousLocationsFile] with the new locations if not. /// /// This is used to detect potential changes to the user facing api and /// pre-emptively resolve them by resnapshotting, see /// https://github.com/dart-lang/build/issues/1929. Future<bool> _checkImportantPackageDeps() async { var currentLocations = await Future.wait(_importantPackages.map((pkg) => Isolate.resolvePackageUri( Uri(scheme: 'package', path: '$pkg/fake.dart')))); var currentLocationsContent = currentLocations.join('\n'); if (!_previousLocationsFile.existsSync()) { _logger.fine('Core package locations file does not exist'); _previousLocationsFile.writeAsStringSync(currentLocationsContent); return false; } if (currentLocationsContent != _previousLocationsFile.readAsStringSync()) { _logger.fine('Core packages locations have changed'); _previousLocationsFile.writeAsStringSync(currentLocationsContent); return false; } return true; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/logging/std_io_logging.dart
// 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:convert'; import 'dart:io'; import 'package:io/ansi.dart'; import 'package:logging/logging.dart'; import 'package:stack_trace/stack_trace.dart'; void Function(LogRecord) stdIOLogListener({bool assumeTty, bool verbose}) => (record) => overrideAnsiOutput(assumeTty == true || ansiOutputEnabled, () { _stdIOLogListener(record, verbose: verbose ?? false); }); StringBuffer colorLog(LogRecord record, {bool verbose}) { AnsiCode color; if (record.level < Level.WARNING) { color = cyan; } else if (record.level < Level.SEVERE) { color = yellow; } else { color = red; } final level = color.wrap('[${record.level}]'); final eraseLine = ansiOutputEnabled && !verbose ? '\x1b[2K\r' : ''; var lines = <Object>[ '$eraseLine$level ${_recordHeader(record, verbose)}${record.message}' ]; if (record.error != null) { lines.add(record.error); } if (record.stackTrace != null && verbose) { var trace = Trace.from(record.stackTrace).foldFrames((f) { return f.package == 'build_runner' || f.package == 'build'; }, terse: true); lines.add(trace); } var message = StringBuffer(lines.join('\n')); // We always add an extra newline at the end of each message, so it // isn't multiline unless we see > 2 lines. var multiLine = LineSplitter.split(message.toString()).length > 2; if (record.level > Level.INFO || !ansiOutputEnabled || multiLine || verbose) { // Add an extra line to the output so the last line isn't written over. message.writeln(''); } return message; } void _stdIOLogListener(LogRecord record, {bool verbose}) => stdout.write(colorLog(record, verbose: verbose)); /// Filter out the Logger names which aren't coming from specific builders and /// splits the header for levels >= WARNING. String _recordHeader(LogRecord record, bool verbose) { var maybeSplit = record.level >= Level.WARNING ? '\n' : ''; return verbose || record.loggerName.contains(' ') ? '${record.loggerName}:$maybeSplit' : ''; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/graph_watcher.dart
// 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 'dart:io'; import 'package:async/async.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'asset_change.dart'; import 'node_watcher.dart'; PackageNodeWatcher _default(PackageNode node) => PackageNodeWatcher(node); /// Allows watching an entire graph of packages to schedule rebuilds. class PackageGraphWatcher { // TODO: Consider pulling logging out and providing hooks instead. final Logger _logger; final PackageNodeWatcher Function(PackageNode) _strategy; final PackageGraph _graph; final _readyCompleter = Completer<void>(); Future<void> get ready => _readyCompleter.future; bool _isWatching = false; /// Creates a new watcher for a [PackageGraph]. /// /// May optionally specify a [watch] strategy, otherwise will attempt a /// reasonable default based on the current platform. PackageGraphWatcher( this._graph, { Logger logger, PackageNodeWatcher Function(PackageNode node) watch, }) : _logger = logger ?? Logger('build_runner'), _strategy = watch ?? _default; /// Returns a stream of records for assets that changed in the package graph. Stream<AssetChange> watch() { assert(!_isWatching); _isWatching = true; return LazyStream( () => logTimedSync(_logger, 'Setting up file watchers', _watch)); } Stream<AssetChange> _watch() { final allWatchers = _graph.allPackages.values .where((node) => node.dependencyType == DependencyType.path) .map(_strategy) .toList(); final filteredEvents = allWatchers .map((w) => w .watch() .where(_nestedPathFilter(w.node)) .handleError((dynamic e, StackTrace s) { _logger.severe( 'Error from directory watcher for package:${w.node.name}\n\n' 'If you see this consistently then it is recommended that ' 'you enable the polling file watcher with ' '--use-polling-watcher.'); throw e; })) .toList(); // Asynchronously complete the `_readyCompleter` once all the watchers // are done. () async { await Future.wait( allWatchers.map((nodeWatcher) => nodeWatcher.watcher.ready)); _readyCompleter.complete(); }(); return StreamGroup.merge(filteredEvents); } bool Function(AssetChange) _nestedPathFilter(PackageNode rootNode) { final ignorePaths = _nestedPaths(rootNode); return (change) => !ignorePaths.any(change.id.path.startsWith); } // Returns a set of all package paths that are "nested" within a node. // // This allows the watcher to optimize and avoid duplicate events. List<String> _nestedPaths(PackageNode rootNode) { return _graph.allPackages.values .where((node) { return node.path.length > rootNode.path.length && node.path.startsWith(rootNode.path); }) .map((node) => node.path.substring(rootNode.path.length + 1) + Platform.pathSeparator) .toList(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/node_watcher.dart
// 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:build_runner_core/build_runner_core.dart'; import 'package:watcher/watcher.dart'; import 'asset_change.dart'; Watcher _default(String path) => Watcher(path); /// Allows watching significant files and directories in a given package. class PackageNodeWatcher { final Watcher Function(String) _strategy; final PackageNode node; /// The actual watcher instance. Watcher _watcher; Watcher get watcher => _watcher; /// Creates a new watcher for a [PackageNode]. /// /// May optionally specify a [watch] strategy, otherwise will attempt a /// reasonable default based on the current platform and the type of path /// (i.e. a file versus directory). PackageNodeWatcher( this.node, { Watcher Function(String path) watch, }) : _strategy = watch ?? _default; /// Returns a stream of records for assets that change recursively. Stream<AssetChange> watch() { assert(_watcher == null); _watcher = _strategy(node.path); final events = _watcher.events; return events.map((e) => AssetChange.fromEvent(node, e)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/change_filter.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:build_runner/src/watcher/asset_change.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/asset_graph/graph.dart'; import 'package:build_runner_core/src/asset_graph/node.dart'; import 'package:watcher/watcher.dart'; /// Returns if a given asset change should be considered for building. FutureOr<bool> shouldProcess( AssetChange change, AssetGraph assetGraph, BuildOptions buildOptions, bool willCreateOutputDir, Set<AssetId> expectedDeletes, AssetReader reader, ) { if (_isCacheFile(change) && !assetGraph.contains(change.id)) return false; var node = assetGraph.get(change.id); if (node != null) { if (!willCreateOutputDir && !node.isInteresting) return false; if (_isAddOrEditOnGeneratedFile(node, change.type)) return false; if (change.type == ChangeType.MODIFY) { // Was it really modified or just touched? return reader .digest(change.id) .then((newDigest) => node.lastKnownDigest != newDigest); } } else { if (change.type != ChangeType.ADD) return false; if (!buildOptions.targetGraph.anyMatchesAsset(change.id)) return false; } if (_isExpectedDelete(change, expectedDeletes)) return false; return true; } bool _isAddOrEditOnGeneratedFile(AssetNode node, ChangeType changeType) => node.isGenerated && changeType != ChangeType.REMOVE; bool _isCacheFile(AssetChange change) => change.id.path.startsWith(cacheDir); bool _isExpectedDelete(AssetChange change, Set<AssetId> expectedDeletes) => expectedDeletes.remove(change.id);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/delete_writer.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:build/build.dart'; import 'package:build_runner_core/build_runner_core.dart'; /// A [RunnerAssetWriter] that forwards delete events to [_onDelete]; class OnDeleteWriter implements RunnerAssetWriter { final RunnerAssetWriter _writer; final void Function(AssetId id) _onDelete; OnDeleteWriter(this._writer, this._onDelete); @override Future delete(AssetId id) { _onDelete(id); return _writer.delete(id); } @override Future writeAsBytes(AssetId id, List<int> bytes) => _writer.writeAsBytes(id, bytes); @override Future writeAsString(AssetId id, String contents, {Encoding encoding = utf8}) => _writer.writeAsString(id, contents, encoding: encoding); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/asset_change.dart
// 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 'package:build/build.dart'; import 'package:path/path.dart' as p; import 'package:watcher/watcher.dart'; import 'package:build_runner_core/build_runner_core.dart'; /// Represents an [id] that was modified on disk as a result of [type]. class AssetChange { /// Asset that was changed. final AssetId id; /// What caused the asset to be detected as changed. final ChangeType type; const AssetChange(this.id, this.type); /// Creates a new change record in [package] from an existing watcher [event]. factory AssetChange.fromEvent(PackageNode package, WatchEvent event) { return AssetChange( AssetId( package.name, _normalizeRelativePath(package, event), ), event.type, ); } static String _normalizeRelativePath(PackageNode package, WatchEvent event) { final pkgPath = package.path; var absoluteEventPath = p.isAbsolute(event.path) ? event.path : p.absolute(event.path); if (!p.isWithin(pkgPath, absoluteEventPath)) { throw ArgumentError('"$absoluteEventPath" is not in "$pkgPath".'); } return p.relative(absoluteEventPath, from: pkgPath); } @override int get hashCode => id.hashCode ^ type.hashCode; @override bool operator ==(Object other) => other is AssetChange && other.id == id && other.type == type; @override String toString() => 'AssetChange {asset: $id, type: $type}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/watcher/collect_changes.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build/build.dart'; import 'package:build_runner/src/watcher/asset_change.dart'; import 'package:watcher/watcher.dart'; /// Merges [AssetChange] events. /// /// For example, if an asset was added then immediately deleted, no event will /// be recorded for the given asset. Map<AssetId, ChangeType> collectChanges(List<List<AssetChange>> changes) { var changeMap = <AssetId, ChangeType>{}; for (var change in changes.expand((l) => l)) { var originalChangeType = changeMap[change.id]; if (originalChangeType != null) { switch (originalChangeType) { case ChangeType.ADD: if (change.type == ChangeType.REMOVE) { // ADD followed by REMOVE, just remove the change. changeMap.remove(change.id); } break; case ChangeType.REMOVE: if (change.type == ChangeType.ADD) { // REMOVE followed by ADD, convert to a MODIFY changeMap[change.id] = ChangeType.MODIFY; } else if (change.type == ChangeType.MODIFY) { // REMOVE followed by MODIFY isn't sensible, just throw. throw StateError( 'Internal error, got REMOVE event followed by MODIFY event for ' '${change.id}.'); } break; case ChangeType.MODIFY: if (change.type == ChangeType.REMOVE) { // MODIFY followed by REMOVE, convert to REMOVE changeMap[change.id] = change.type; } else if (change.type == ChangeType.ADD) { // MODIFY followed by ADD isn't sensible, just throw. throw StateError( 'Internal error, got MODIFY event followed by ADD event for ' '${change.id}.'); } break; } } else { changeMap[change.id] = change.type; } } return changeMap; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner/src/package_graph/build_config_overrides.dart
// 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 'dart:io'; import 'package:build_config/build_config.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:glob/glob.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; final _log = Logger('BuildConfigOverrides'); Future<Map<String, BuildConfig>> findBuildConfigOverrides( PackageGraph packageGraph, String configKey) async { final configs = <String, BuildConfig>{}; final configFiles = Glob('*.build.yaml').list(); await for (final file in configFiles) { if (file is File) { final packageName = p.basename(file.path).split('.').first; final packageNode = packageGraph.allPackages[packageName]; if (packageNode == null) { _log.warning('A build config override is provided for $packageName but ' 'that package does not exist. ' 'Remove the ${p.basename(file.path)} override or add a dependency ' 'on $packageName.'); continue; } final yaml = file.readAsStringSync(); final config = BuildConfig.parse( packageName, packageNode.dependencies.map((n) => n.name), yaml, configYamlPath: file.path, ); configs[packageName] = config; } } if (configKey != null) { final file = File('build.$configKey.yaml'); if (!file.existsSync()) { _log.warning('Cannot find build.$configKey.yaml for specified config.'); throw CannotBuildException(); } final yaml = file.readAsStringSync(); final config = BuildConfig.parse( packageGraph.root.name, packageGraph.root.dependencies.map((n) => n.name), yaml, configYamlPath: file.path, ); configs[packageGraph.root.name] = config; } return configs; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers/build_resolvers.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/resolver.dart' show AnalyzerResolvers;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers/src/human_readable_duration.dart
// 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. /// Returns a human readable string for a duration. /// /// Handles durations that span up to hours - this will not be a good fit for /// durations that are longer than days. /// /// Always attempts 2 'levels' of precision. Will show hours/minutes, /// minutes/seconds, seconds/tenths of a second, or milliseconds depending on /// the largest level that needs to be displayed. /// // TODO: This is copied from `package:build_runner_core`, at some point we // may want to move this to a shared dependency. String humanReadable(Duration duration) { if (duration < const Duration(seconds: 1)) { return '${duration.inMilliseconds}ms'; } if (duration < const Duration(minutes: 1)) { return '${(duration.inMilliseconds / 1000.0).toStringAsFixed(1)}s'; } if (duration < const Duration(hours: 1)) { final minutes = duration.inMinutes; final remaining = duration - Duration(minutes: minutes); return '${minutes}m ${remaining.inSeconds}s'; } final hours = duration.inHours; final remaining = duration - Duration(hours: hours); return '${hours}h ${remaining.inMinutes}m'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers/src/resolver.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'package:analyzer/src/summary/summary_file_builder.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/file_system/file_system.dart' hide File; import 'package:analyzer/file_system/physical_file_system.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/dart/analysis/driver.dart' show AnalysisDriver; import 'package:analyzer/src/dart/sdk/sdk.dart'; import 'package:analyzer/src/generated/engine.dart' hide Logger; import 'package:build/build.dart'; import 'package:logging/logging.dart'; import 'package:package_resolver/package_resolver.dart'; import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; import 'analysis_driver.dart'; import 'build_asset_uri_resolver.dart'; import 'human_readable_duration.dart'; final _logger = Logger('build_resolvers'); /// Implements [Resolver.libraries] and [Resolver.findLibraryByName] by crawling /// down from entrypoints. class PerActionResolver implements ReleasableResolver { final ReleasableResolver _delegate; final Iterable<AssetId> _entryPoints; PerActionResolver(this._delegate, this._entryPoints); @override Stream<LibraryElement> get libraries async* { final seen = Set<LibraryElement>(); final toVisit = Queue<LibraryElement>(); for (final entryPoint in _entryPoints) { if (!await _delegate.isLibrary(entryPoint)) continue; final library = await _delegate.libraryFor(entryPoint); toVisit.add(library); seen.add(library); } while (toVisit.isNotEmpty) { final current = toVisit.removeFirst(); // TODO - avoid crawling or returning libraries which are not visible via // `BuildStep.canRead`. They'd still be reachable by crawling the element // model manually. yield current; final toCrawl = current.importedLibraries .followedBy(current.exportedLibraries) .where((l) => !seen.contains(l)) .toSet(); toVisit.addAll(toCrawl); seen.addAll(toCrawl); } } @override Future<LibraryElement> findLibraryByName(String libraryName) async => libraries.firstWhere((l) => l.name == libraryName, orElse: () => null); @override Future<bool> isLibrary(AssetId assetId) => _delegate.isLibrary(assetId); @override Future<LibraryElement> libraryFor(AssetId assetId) => _delegate.libraryFor(assetId); @override void release() => _delegate.release(); @override Future<AssetId> assetIdForElement(Element element) => _delegate.assetIdForElement(element); } class AnalyzerResolver implements ReleasableResolver { final BuildAssetUriResolver _uriResolver; final AnalysisDriver _driver; AnalyzerResolver(this._driver, this._uriResolver); @override Future<bool> isLibrary(AssetId assetId) async { var source = _driver.sourceFactory.forUri2(assetId.uri); return source != null && (await _driver.getSourceKind(assetPath(assetId))) == SourceKind.LIBRARY; } @override Future<LibraryElement> libraryFor(AssetId assetId) async { var path = assetPath(assetId); var uri = assetId.uri; var source = _driver.sourceFactory.forUri2(uri); if (source == null) throw ArgumentError('missing source for $uri'); var kind = await _driver.getSourceKind(path); if (kind != SourceKind.LIBRARY) return null; return _driver.getLibraryByUri(assetId.uri.toString()); } @override // Do nothing void release() {} @override Stream<LibraryElement> get libraries { // We don't know what libraries to expose without leaking libraries written // by later phases. throw UnimplementedError(); } @override Future<LibraryElement> findLibraryByName(String libraryName) { // We don't know what libraries to expose without leaking libraries written // by later phases. throw UnimplementedError(); } @override Future<AssetId> assetIdForElement(Element element) async { final uri = element.source.uri; if (!uri.isScheme('package') && !uri.isScheme('asset')) { throw UnresolvableAssetException( '${element.name} in ${element.source.uri}'); } return AssetId.resolve('${element.source.uri}'); } } class AnalyzerResolvers implements Resolvers { /// Nullable, the default analysis options are used if not provided. final AnalysisOptions _analysisOptions; /// A function that returns the path to the SDK summary when invoked. /// /// Defaults to [_defaultSdkSummaryGenerator]. final Future<String> Function() _sdkSummaryGenerator; // Lazy, all access must be preceded by a call to `_ensureInitialized`. AnalyzerResolver _resolver; BuildAssetUriResolver _uriResolver; /// Nullable, should not be accessed outside of [_ensureInitialized]. Future<void> _initialized; AnalyzerResolvers( [this._analysisOptions, Future<String> Function() sdkSummaryGenerator]) : _sdkSummaryGenerator = sdkSummaryGenerator ?? _defaultSdkSummaryGenerator; /// Create a Resolvers backed by an [AnalysisContext] using options /// [_analysisOptions]. Future<void> _ensureInitialized() { return _initialized ??= () async { _uriResolver = BuildAssetUriResolver(); var driver = analysisDriver( _uriResolver, _analysisOptions, await _sdkSummaryGenerator()); _resolver = AnalyzerResolver(driver, _uriResolver); }(); } @override Future<ReleasableResolver> get(BuildStep buildStep) async { await _ensureInitialized(); await _uriResolver.performResolve( buildStep, [buildStep.inputId], _resolver._driver); return PerActionResolver(_resolver, [buildStep.inputId]); } /// Must be called between each build. @override void reset() { _uriResolver?.seenAssets?.clear(); } } /// Lazily creates a summary of the users SDK and caches it under /// `.dart_tool/build_resolvers`. /// /// This is only intended for use in typical dart packages, which must /// have an already existing `.dart_tool` directory (this is how we /// validate we are running under a typical dart package and not a custom /// environment). Future<String> _defaultSdkSummaryGenerator() async { var dartToolPath = '.dart_tool'; if (!await Directory(dartToolPath).exists()) { throw StateError( 'The default analyzer resolver can only be used when the current ' 'working directory is a standard pub package.'); } var cacheDir = p.join(dartToolPath, 'build_resolvers'); var summaryPath = p.join(cacheDir, 'sdk.sum'); var depsFile = File('$summaryPath.deps'); var summaryFile = File(summaryPath); var currentDeps = { 'sdk': Platform.version, for (var package in _packageDepsToCheck) package: await PackageResolver.current.packagePath(package), }; // Invalidate existing summary/version/analyzer files if present. if (await depsFile.exists()) { if (!await _checkDeps(depsFile, currentDeps)) { await depsFile.delete(); if (await summaryFile.exists()) await summaryFile.delete(); } } else if (await summaryFile.exists()) { // Fallback for cases where we could not do a proper version check. await summaryFile.delete(); } // Generate the summary and version files if necessary. if (!await summaryFile.exists()) { var watch = Stopwatch()..start(); _logger.info('Generating SDK summary...'); await summaryFile.create(recursive: true); var sdkPath = p.dirname(p.dirname(Platform.resolvedExecutable)); await summaryFile.writeAsBytes(_buildSdkSummary(sdkPath)); await _createDepsFile(depsFile, currentDeps); watch.stop(); _logger.info('Generating SDK summary completed, took ' '${humanReadable(watch.elapsed)}\n'); } return p.absolute(summaryPath); } final _packageDepsToCheck = ['analyzer', 'build_resolvers']; Future<bool> _checkDeps( File versionsFile, Map<String, Object> currentDeps) async { var previous = jsonDecode(await versionsFile.readAsString()) as Map<String, Object>; if (previous.keys.length != currentDeps.keys.length) return false; for (var entry in previous.entries) { if (entry.value != currentDeps[entry.key]) return false; } return true; } Future<void> _createDepsFile( File depsFile, Map<String, Object> currentDeps) async { await depsFile.create(recursive: true); await depsFile.writeAsString(jsonEncode(currentDeps)); } List<int> _buildSdkSummary(String dartSdkPath) { var resourceProvider = PhysicalResourceProvider.INSTANCE; var dartSdkFolder = resourceProvider.getFolder(dartSdkPath); var sdk = FolderBasedDartSdk(resourceProvider, dartSdkFolder, true) ..useSummary = false ..analysisOptions = AnalysisOptionsImpl(); if (_isFlutter) _addFlutterLibraries(sdk, resourceProvider, dartSdkPath); var sdkSources = { for (var library in sdk.sdkLibraries) sdk.mapDartUri(library.shortName), }; return SummaryBuilder(sdkSources, sdk.context).build(); } /// Loads the flutter engine _embedder.yaml file and adds any new libraries to /// [sdk]. void _addFlutterLibraries(AbstractDartSdk sdk, ResourceProvider resourceProvider, String dartSdkPath) { var embedderSdkPath = p.join(p.dirname(dartSdkPath), 'pkg', 'sky_engine', 'lib'); var embedderYamlFile = resourceProvider.getFile(p.join(embedderSdkPath, '_embedder.yaml')); if (!embedderYamlFile.exists) { throw StateError('Unable to find flutter libraries, please run ' '`flutter precache` and try again.'); } var embedderYaml = loadYaml(embedderYamlFile.readAsStringSync()) as YamlMap; var flutterSdk = EmbedderSdk(resourceProvider, {resourceProvider.getFolder(embedderSdkPath): embedderYaml}); for (var library in flutterSdk.sdkLibraries) { if (sdk.libraryMap.getLibrary(library.shortName) != null) continue; sdk.libraryMap.setLibrary(library.shortName, library as SdkLibraryImpl); } } final _isFlutter = Platform.version.contains('flutter');
0