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/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/string_serializer.dart
// Copyright (c) 2015, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class StringSerializer implements PrimitiveSerializer<String> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([String]); @override final String wireName = 'String'; @override Object serialize(Serializers serializers, String string, {FullType specifiedType = FullType.unspecified}) { return string; } @override String deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return serialized as String; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/int64_serializer.dart
// Copyright (c) 2017, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'package:fixnum/fixnum.dart'; class Int64Serializer implements PrimitiveSerializer<Int64> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([Int64]); @override final String wireName = 'Int64'; @override Object serialize(Serializers serializers, Int64 int64, {FullType specifiedType = FullType.unspecified}) { return int64.toString(); } @override Int64 deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return Int64.parseInt(serialized as String); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/regexp_serializer.dart
// Copyright (c) 2019, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Runtime type for [RegExp] private implementation. final _runtimeType = RegExp('').runtimeType; class RegExpSerializer implements PrimitiveSerializer<RegExp> { @override final Iterable<Type> types = BuiltList<Type>([RegExp, _runtimeType]); @override final String wireName = 'RegExp'; @override Object serialize(Serializers serializers, RegExp value, {FullType specifiedType = FullType.unspecified}) { return value.pattern; } @override RegExp deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return RegExp(serialized as String); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_set_serializer.dart
// Copyright (c) 2015, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BuiltSetSerializer implements StructuredSerializer<BuiltSet> { final bool structured = true; @override final Iterable<Type> types = BuiltList<Type>([BuiltSet, BuiltSet<Object>().runtimeType]); @override final String wireName = 'set'; @override Iterable serialize(Serializers serializers, BuiltSet builtSet, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; if (!isUnderspecified) serializers.expectBuilder(specifiedType); var elementType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; return builtSet .map((item) => serializers.serialize(item, specifiedType: elementType)); } @override BuiltSet deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; var elementType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var result = isUnderspecified ? SetBuilder<Object>() : serializers.newBuilder(specifiedType) as SetBuilder; result.replace(serialized.map( (item) => serializers.deserialize(item, specifiedType: elementType))); return result.build(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_json_serializers.dart
// Copyright (c) 2015, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Default implementation of [Serializers]. class BuiltJsonSerializers implements Serializers { final BuiltMap<Type, Serializer> _typeToSerializer; // Implementation note: wire name is what gets sent in the JSON, type name is // the runtime type name. Type name is complicated for two reasons: // // 1. Built Value classes have two types, the abstract class and the // generated implementation. // // 2. When compiled to javascript the runtime type names are obfuscated. final BuiltMap<String, Serializer> _wireNameToSerializer; final BuiltMap<String, Serializer> _typeNameToSerializer; @override final BuiltMap<FullType, Function> builderFactories; final BuiltList<SerializerPlugin> _plugins; BuiltJsonSerializers._(this._typeToSerializer, this._wireNameToSerializer, this._typeNameToSerializer, this.builderFactories, this._plugins); @override Iterable<Serializer> get serializers => _wireNameToSerializer.values; @override T deserializeWith<T>(Serializer<T> serializer, Object serialized) { return deserialize(serialized, specifiedType: FullType(serializer.types.first)) as T; } @override Object serializeWith<T>(Serializer<T> serializer, T object) { return serialize(object, specifiedType: FullType(serializer.types.first)); } @override Object serialize(Object object, {FullType specifiedType = FullType.unspecified}) { var transformedObject = object; for (var plugin in _plugins) { transformedObject = plugin.beforeSerialize(transformedObject, specifiedType); } var result = _serialize(transformedObject, specifiedType); for (var plugin in _plugins) { result = plugin.afterSerialize(result, specifiedType); } return result; } Object _serialize(Object object, FullType specifiedType) { if (specifiedType.isUnspecified) { final serializer = serializerForType(object.runtimeType); if (serializer == null) { throw StateError("No serializer for '${object.runtimeType}'."); } if (serializer is StructuredSerializer) { final result = <Object>[serializer.wireName]; return result..addAll(serializer.serialize(this, object)); } else if (serializer is PrimitiveSerializer) { return <Object>[ serializer.wireName, serializer.serialize(this, object) ]; } else { throw StateError( 'serializer must be StructuredSerializer or PrimitiveSerializer'); } } else { final serializer = serializerForType(specifiedType.root); if (serializer == null) { // Might be an interface; try resolving using the runtime type. return serialize(object); } if (serializer is StructuredSerializer) { return serializer .serialize(this, object, specifiedType: specifiedType) .toList(); } else if (serializer is PrimitiveSerializer) { return serializer.serialize(this, object, specifiedType: specifiedType); } else { throw StateError( 'serializer must be StructuredSerializer or PrimitiveSerializer'); } } } @override Object deserialize(Object object, {FullType specifiedType = FullType.unspecified}) { var transformedObject = object; for (var plugin in _plugins) { transformedObject = plugin.beforeDeserialize(transformedObject, specifiedType); } var result = _deserialize(object, transformedObject, specifiedType); for (var plugin in _plugins) { result = plugin.afterDeserialize(result, specifiedType); } return result; } Object _deserialize( Object objectBeforePlugins, Object object, FullType specifiedType) { if (specifiedType.isUnspecified) { final wireName = (object as List).first as String; final serializer = serializerForWireName(wireName); if (serializer == null) { throw StateError("No serializer for '$wireName'."); } if (serializer is StructuredSerializer) { try { return serializer.deserialize(this, (object as List).sublist(1)); } on Error catch (error) { throw DeserializationError(object, specifiedType, error); } } else if (serializer is PrimitiveSerializer) { try { return serializer.deserialize(this, (object as List)[1]); } on Error catch (error) { throw DeserializationError(object, specifiedType, error); } } else { throw StateError( 'serializer must be StructuredSerializer or PrimitiveSerializer'); } } else { final serializer = serializerForType(specifiedType.root); if (serializer == null) { if (object is List && object.first is String) { // Might be an interface; try resolving using the type on the wire. return deserialize(objectBeforePlugins); } else { throw StateError("No serializer for '${specifiedType.root}'."); } } if (serializer is StructuredSerializer) { try { return serializer.deserialize(this, object as Iterable, specifiedType: specifiedType); } on Error catch (error) { throw DeserializationError(object, specifiedType, error); } } else if (serializer is PrimitiveSerializer) { try { return serializer.deserialize(this, object, specifiedType: specifiedType); } on Error catch (error) { throw DeserializationError(object, specifiedType, error); } } else { throw StateError( 'serializer must be StructuredSerializer or PrimitiveSerializer'); } } } @override Serializer serializerForType(Type type) => _typeToSerializer[type] ?? _typeNameToSerializer[_getRawName(type)]; @override Serializer serializerForWireName(String wireName) => _wireNameToSerializer[wireName]; @override Object newBuilder(FullType fullType) { var builderFactory = builderFactories[fullType]; if (builderFactory == null) _throwMissingBuilderFactory(fullType); return builderFactory(); } @override void expectBuilder(FullType fullType) { if (!hasBuilder(fullType)) _throwMissingBuilderFactory(fullType); } void _throwMissingBuilderFactory(FullType fullType) { throw StateError('No builder factory for $fullType. ' 'Fix by adding one, see SerializersBuilder.addBuilderFactory.'); } @override bool hasBuilder(FullType fullType) { return builderFactories.containsKey(fullType); } @override SerializersBuilder toBuilder() { return BuiltJsonSerializersBuilder._( _typeToSerializer.toBuilder(), _wireNameToSerializer.toBuilder(), _typeNameToSerializer.toBuilder(), builderFactories.toBuilder(), _plugins.toBuilder()); } } /// Default implementation of [SerializersBuilder]. class BuiltJsonSerializersBuilder implements SerializersBuilder { final MapBuilder<Type, Serializer> _typeToSerializer; final MapBuilder<String, Serializer> _wireNameToSerializer; final MapBuilder<String, Serializer> _typeNameToSerializer; final MapBuilder<FullType, Function> _builderFactories; final ListBuilder<SerializerPlugin> _plugins; factory BuiltJsonSerializersBuilder() => BuiltJsonSerializersBuilder._( MapBuilder<Type, Serializer>(), MapBuilder<String, Serializer>(), MapBuilder<String, Serializer>(), MapBuilder<FullType, Function>(), ListBuilder<SerializerPlugin>()); BuiltJsonSerializersBuilder._( this._typeToSerializer, this._wireNameToSerializer, this._typeNameToSerializer, this._builderFactories, this._plugins); @override void add(Serializer serializer) { if (serializer is! StructuredSerializer && serializer is! PrimitiveSerializer) { throw ArgumentError( 'serializer must be StructuredSerializer or PrimitiveSerializer'); } _wireNameToSerializer[serializer.wireName] = serializer; for (var type in serializer.types) { _typeToSerializer[type] = serializer; _typeNameToSerializer[_getRawName(type)] = serializer; } } @override void addAll(Iterable<Serializer> serializers) { serializers.forEach(add); } @override void addBuilderFactory(FullType types, Function function) { _builderFactories[types] = function; } @override void merge(Serializers serializers) { addAll(serializers.serializers); _builderFactories.addAll(serializers.builderFactories.asMap()); } @override void mergeAll(Iterable<Serializers> serializersIterable) { for (var serializers in serializersIterable) { merge(serializers); } } @override void addPlugin(SerializerPlugin plugin) { _plugins.add(plugin); } @override Serializers build() { return BuiltJsonSerializers._( _typeToSerializer.build(), _wireNameToSerializer.build(), _typeNameToSerializer.build(), _builderFactories.build(), _plugins.build()); } } String _getRawName(Type type) { var name = type.toString(); var genericsStart = name.indexOf('<'); return genericsStart == -1 ? name : name.substring(0, genericsStart); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/int_serializer.dart
// Copyright (c) 2015, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class IntSerializer implements PrimitiveSerializer<int> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([int]); @override final String wireName = 'int'; @override Object serialize(Serializers serializers, int integer, {FullType specifiedType = FullType.unspecified}) { return integer; } @override int deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return serialized as int; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_list_multimap_serializer.dart
// Copyright (c) 2016, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BuiltListMultimapSerializer implements StructuredSerializer<BuiltListMultimap> { final bool structured = true; @override final Iterable<Type> types = BuiltList<Type>( [BuiltListMultimap, BuiltListMultimap<Object, Object>().runtimeType]); @override final String wireName = 'listMultimap'; @override Iterable serialize( Serializers serializers, BuiltListMultimap builtListMultimap, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; if (!isUnderspecified) serializers.expectBuilder(specifiedType); var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = <Object>[]; for (var key in builtListMultimap.keys) { result.add(serializers.serialize(key, specifiedType: keyType)); result.add(builtListMultimap[key] .map( (value) => serializers.serialize(value, specifiedType: valueType)) .toList()); } return result; } @override BuiltListMultimap deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = isUnderspecified ? ListMultimapBuilder<Object, Object>() : serializers.newBuilder(specifiedType) as ListMultimapBuilder; if (serialized.length % 2 == 1) { throw ArgumentError('odd length'); } for (var i = 0; i != serialized.length; i += 2) { final key = serializers.deserialize(serialized.elementAt(i), specifiedType: keyType); final values = serialized.elementAt(i + 1).map( (value) => serializers.deserialize(value, specifiedType: valueType)); for (var value in values) { result.add(key, value); } } return result.build(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/bool_serializer.dart
// Copyright (c) 2015, Google Inc. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BoolSerializer implements PrimitiveSerializer<bool> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([bool]); @override final String wireName = 'bool'; @override Object serialize(Serializers serializers, bool boolean, {FullType specifiedType = FullType.unspecified}) { return boolean; } @override bool deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return serialized as bool; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/parser.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:math' as math; import 'package:source_span/source_span.dart'; import 'src/messages.dart'; import 'src/preprocessor_options.dart'; import 'visitor.dart'; export 'src/messages.dart' show Message, MessageLevel; export 'src/preprocessor_options.dart'; part 'src/analyzer.dart'; part 'src/polyfill.dart'; part 'src/property.dart'; part 'src/token.dart'; part 'src/token_kind.dart'; part 'src/tokenizer.dart'; part 'src/tokenizer_base.dart'; enum ClauseType { none, conjunction, disjunction, } /// Used for parser lookup ahead (used for nested selectors Less support). class ParserState extends TokenizerState { final Token peekToken; final Token previousToken; ParserState(this.peekToken, this.previousToken, Tokenizer tokenizer) : super(tokenizer); } // TODO(jmesserly): this should not be global void _createMessages({List<Message> errors, PreprocessorOptions options}) { errors ??= []; options ??= PreprocessorOptions(useColors: false, inputFile: 'memory'); messages = Messages(options: options, printHandler: errors.add); } /// CSS checked mode enabled. bool get isChecked => messages.options.checked; // TODO(terry): Remove nested name parameter. /// Parse and analyze the CSS file. StyleSheet compile(input, {List<Message> errors, PreprocessorOptions options, bool nested = true, bool polyfill = false, List<StyleSheet> includes}) { includes ??= []; var source = _inputAsString(input); _createMessages(errors: errors, options: options); var file = SourceFile.fromString(source); var tree = _Parser(file, source).parse(); analyze([tree], errors: errors, options: options); if (polyfill) { var processCss = PolyFill(messages); processCss.process(tree, includes: includes); } return tree; } /// Analyze the CSS file. void analyze(List<StyleSheet> styleSheets, {List<Message> errors, PreprocessorOptions options}) { _createMessages(errors: errors, options: options); Analyzer(styleSheets, messages).run(); } /// Parse the [input] CSS stylesheet into a tree. The [input] can be a [String], /// or [List<int>] of bytes and returns a [StyleSheet] AST. The optional /// [errors] list will contain each error/warning as a [Message]. StyleSheet parse(input, {List<Message> errors, PreprocessorOptions options}) { var source = _inputAsString(input); _createMessages(errors: errors, options: options); var file = SourceFile.fromString(source); return _Parser(file, source).parse(); } /// Parse the [input] CSS selector into a tree. The [input] can be a [String], /// or [List<int>] of bytes and returns a [StyleSheet] AST. The optional /// [errors] list will contain each error/warning as a [Message]. // TODO(jmesserly): should rename "parseSelector" and return Selector StyleSheet selector(input, {List<Message> errors}) { var source = _inputAsString(input); _createMessages(errors: errors); var file = SourceFile.fromString(source); return (_Parser(file, source)..tokenizer.inSelector = true).parseSelector(); } SelectorGroup parseSelectorGroup(input, {List<Message> errors}) { var source = _inputAsString(input); _createMessages(errors: errors); var file = SourceFile.fromString(source); return (_Parser(file, source) // TODO(jmesserly): this fix should be applied to the parser. It's // tricky because by the time the flag is set one token has already // been fetched. ..tokenizer.inSelector = true) .processSelectorGroup(); } String _inputAsString(input) { String source; if (input is String) { source = input; } else if (input is List) { // TODO(terry): The parse function needs an "encoding" argument and will // default to whatever encoding CSS defaults to. // // Here's some info about CSS encodings: // http://www.w3.org/International/questions/qa-css-charset.en.php // // As JMesserly suggests it will probably need a "preparser" html5lib // (encoding_parser.dart) that interprets the bytes as ASCII and scans for // @charset. But for now an "encoding" argument would work. Often the // HTTP header will indicate the correct encoding. // // See encoding helpers at: package:html5lib/lib/src/char_encodings.dart // These helpers can decode in different formats given an encoding name // (mostly unicode, ascii, windows-1252 which is html5 default encoding). source = String.fromCharCodes(input as List<int>); } else { // TODO(terry): Support RandomAccessFile using console. throw ArgumentError("'source' must be a String or " 'List<int> (of bytes). RandomAccessFile not supported from this ' 'simple interface'); } return source; } // TODO(terry): Consider removing this class when all usages can be eliminated // or replaced with compile API. /// Public parsing interface for csslib. class Parser { final _Parser _parser; // TODO(jmesserly): having file and text is redundant. // TODO(rnystrom): baseUrl isn't used. Remove from API. Parser(SourceFile file, String text, {int start = 0, String baseUrl}) : _parser = _Parser(file, text, start: start); StyleSheet parse() => _parser.parse(); } // CSS2.1 pseudo-elements which were defined with a single ':'. const _legacyPseudoElements = <String>{ 'after', 'before', 'first-letter', 'first-line', }; /// A simple recursive descent parser for CSS. class _Parser { final Tokenizer tokenizer; /// File containing the source being parsed, used to report errors with /// source-span locations. final SourceFile file; Token _previousToken; Token _peekToken; _Parser(this.file, String text, {int start = 0}) : tokenizer = Tokenizer(file, text, true, start) { _peekToken = tokenizer.next(); } /// Main entry point for parsing an entire CSS file. StyleSheet parse() { var productions = <TreeNode>[]; var start = _peekToken.span; while (!_maybeEat(TokenKind.END_OF_FILE) && !_peekKind(TokenKind.RBRACE)) { // TODO(terry): Need to handle charset. final rule = processRule(); if (rule != null) { productions.add(rule); } else { break; } } checkEndOfFile(); return StyleSheet(productions, _makeSpan(start)); } /// Main entry point for parsing a simple selector sequence. StyleSheet parseSelector() { var productions = <TreeNode>[]; var start = _peekToken.span; while (!_maybeEat(TokenKind.END_OF_FILE) && !_peekKind(TokenKind.RBRACE)) { var selector = processSelector(); if (selector != null) { productions.add(selector); } else { break; // Prevent infinite loop if we can't parse something. } } checkEndOfFile(); return StyleSheet.selector(productions, _makeSpan(start)); } /// Generate an error if [file] has not been completely consumed. void checkEndOfFile() { if (!(_peekKind(TokenKind.END_OF_FILE) || _peekKind(TokenKind.INCOMPLETE_COMMENT))) { _error('premature end of file unknown CSS', _peekToken.span); } } /// Guard to break out of parser when an unexpected end of file is found. // TODO(jimhug): Failure to call this method can lead to inifinite parser // loops. Consider embracing exceptions for more errors to reduce // the danger here. bool isPrematureEndOfFile() { if (_maybeEat(TokenKind.END_OF_FILE)) { _error('unexpected end of file', _peekToken.span); return true; } else { return false; } } /////////////////////////////////////////////////////////////////// // Basic support methods /////////////////////////////////////////////////////////////////// int _peek() { return _peekToken.kind; } Token _next({bool unicodeRange = false}) { _previousToken = _peekToken; _peekToken = tokenizer.next(unicodeRange: unicodeRange); return _previousToken; } bool _peekKind(int kind) { return _peekToken.kind == kind; } // Is the next token a legal identifier? This includes pseudo-keywords. bool _peekIdentifier() { return TokenKind.isIdentifier(_peekToken.kind); } /// Marks the parser/tokenizer look ahead to support Less nested selectors. ParserState get _mark => ParserState(_peekToken, _previousToken, tokenizer); /// Restores the parser/tokenizer state to state remembered by _mark. void _restore(ParserState markedData) { tokenizer.restore(markedData); _peekToken = markedData.peekToken; _previousToken = markedData.previousToken; } bool _maybeEat(int kind, {bool unicodeRange = false}) { if (_peekToken.kind == kind) { _previousToken = _peekToken; _peekToken = tokenizer.next(unicodeRange: unicodeRange); return true; } else { return false; } } void _eat(int kind, {bool unicodeRange = false}) { if (!_maybeEat(kind, unicodeRange: unicodeRange)) { _errorExpected(TokenKind.kindToString(kind)); } } void _errorExpected(String expected) { var tok = _next(); String message; try { message = 'expected $expected, but found $tok'; } catch (e) { message = 'parsing error expected $expected'; } _error(message, tok.span); } void _error(String message, SourceSpan location) { location ??= _peekToken.span; messages.error(message, location); } void _warning(String message, SourceSpan location) { location ??= _peekToken.span; messages.warning(message, location); } SourceSpan _makeSpan(FileSpan start) { // TODO(terry): there are places where we are creating spans before we eat // the tokens, so using _previousToken is not always valid. // TODO(nweiz): use < rather than compareTo when SourceSpan supports it. if (_previousToken == null || _previousToken.span.compareTo(start) < 0) { return start; } return start.expand(_previousToken.span); } /////////////////////////////////////////////////////////////////// // Top level productions /////////////////////////////////////////////////////////////////// /// The media_query_list production below replaces the media_list production /// from CSS2 the new grammar is: /// /// media_query_list /// : S* [media_query [ ',' S* media_query ]* ]? /// media_query /// : [ONLY | NOT]? S* media_type S* [ AND S* expression ]* /// | expression [ AND S* expression ]* /// media_type /// : IDENT /// expression /// : '(' S* media_feature S* [ ':' S* expr ]? ')' S* /// media_feature /// : IDENT List<MediaQuery> processMediaQueryList() { var mediaQueries = <MediaQuery>[]; do { var mediaQuery = processMediaQuery(); if (mediaQuery != null) { mediaQueries.add(mediaQuery); } else { break; } } while (_maybeEat(TokenKind.COMMA)); return mediaQueries; } MediaQuery processMediaQuery() { // Grammar: [ONLY | NOT]? S* media_type S* // [ AND S* MediaExpr ]* | MediaExpr [ AND S* MediaExpr ]* var start = _peekToken.span; // Is it a unary media operator? var op = _peekToken.text; var opLen = op.length; var unaryOp = TokenKind.matchMediaOperator(op, 0, opLen); if (unaryOp != -1) { if (isChecked) { if (unaryOp != TokenKind.MEDIA_OP_NOT || unaryOp != TokenKind.MEDIA_OP_ONLY) { _warning('Only the unary operators NOT and ONLY allowed', _makeSpan(start)); } } _next(); start = _peekToken.span; } Identifier type; // Get the media type. if (_peekIdentifier()) type = identifier(); var exprs = <MediaExpression>[]; while (true) { // Parse AND if query has a media_type or previous expression. var andOp = exprs.isNotEmpty || type != null; if (andOp) { op = _peekToken.text; opLen = op.length; if (TokenKind.matchMediaOperator(op, 0, opLen) != TokenKind.MEDIA_OP_AND) { break; } _next(); } var expr = processMediaExpression(andOp); if (expr == null) break; exprs.add(expr); } if (unaryOp != -1 || type != null || exprs.isNotEmpty) { return MediaQuery(unaryOp, type, exprs, _makeSpan(start)); } return null; } MediaExpression processMediaExpression([bool andOperator = false]) { var start = _peekToken.span; // Grammar: '(' S* media_feature S* [ ':' S* expr ]? ')' S* if (_maybeEat(TokenKind.LPAREN)) { if (_peekIdentifier()) { var feature = identifier(); // Media feature. var exprs = _maybeEat(TokenKind.COLON) ? processExpr() : Expressions(_makeSpan(_peekToken.span)); if (_maybeEat(TokenKind.RPAREN)) { return MediaExpression(andOperator, feature, exprs, _makeSpan(start)); } else if (isChecked) { _warning( 'Missing parenthesis around media expression', _makeSpan(start)); return null; } } else if (isChecked) { _warning('Missing media feature in media expression', _makeSpan(start)); } } return null; } /// Directive grammar: /// /// import: '@import' [string | URI] media_list? /// media: '@media' media_query_list '{' ruleset '}' /// page: '@page' [':' IDENT]? '{' declarations '}' /// stylet: '@stylet' IDENT '{' ruleset '}' /// media_query_list: IDENT [',' IDENT] /// keyframes: '@-webkit-keyframes ...' (see grammar below). /// font_face: '@font-face' '{' declarations '}' /// namespace: '@namespace name url("xmlns") /// host: '@host '{' ruleset '}' /// mixin: '@mixin name [(args,...)] '{' declarations/ruleset '}' /// include: '@include name [(@arg,@arg1)] /// '@include name [(@arg...)] /// content: '@content' /// -moz-document: '@-moz-document' [ <url> | url-prefix(<string>) | /// domain(<string>) | regexp(<string) ]# '{' /// declarations /// '}' /// supports: '@supports' supports_condition group_rule_body Directive processDirective() { var start = _peekToken.span; var tokId = processVariableOrDirective(); if (tokId is VarDefinitionDirective) return tokId; switch (tokId) { case TokenKind.DIRECTIVE_IMPORT: _next(); // @import "uri_string" or @import url("uri_string") are identical; only // a url can follow an @import. String importStr; if (_peekIdentifier()) { var func = processFunction(identifier()); if (func is UriTerm) { importStr = func.text; } } else { importStr = processQuotedString(false); } // Any medias? var medias = processMediaQueryList(); if (importStr == null) { _error('missing import string', _peekToken.span); } return ImportDirective(importStr.trim(), medias, _makeSpan(start)); case TokenKind.DIRECTIVE_MEDIA: _next(); // Any medias? var media = processMediaQueryList(); var rules = <TreeNode>[]; if (_maybeEat(TokenKind.LBRACE)) { while (!_maybeEat(TokenKind.END_OF_FILE)) { final rule = processRule(); if (rule == null) break; rules.add(rule); } if (!_maybeEat(TokenKind.RBRACE)) { _error('expected } after ruleset for @media', _peekToken.span); } } else { _error('expected { after media before ruleset', _peekToken.span); } return MediaDirective(media, rules, _makeSpan(start)); case TokenKind.DIRECTIVE_HOST: _next(); var rules = <TreeNode>[]; if (_maybeEat(TokenKind.LBRACE)) { while (!_maybeEat(TokenKind.END_OF_FILE)) { final rule = processRule(); if (rule == null) break; rules.add(rule); } if (!_maybeEat(TokenKind.RBRACE)) { _error('expected } after ruleset for @host', _peekToken.span); } } else { _error('expected { after host before ruleset', _peekToken.span); } return HostDirective(rules, _makeSpan(start)); case TokenKind.DIRECTIVE_PAGE: // @page S* IDENT? pseudo_page? // S* '{' S* // [ declaration | margin ]? // [ ';' S* [ declaration | margin ]? ]* '}' S* // // pseudo_page : // ':' [ "left" | "right" | "first" ] // // margin : // margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S* // // margin_sym : @top-left-corner, @top-left, @bottom-left, etc. // // See http://www.w3.org/TR/css3-page/#CSS21 _next(); // Page name Identifier name; if (_peekIdentifier()) { name = identifier(); } // Any pseudo page? Identifier pseudoPage; if (_maybeEat(TokenKind.COLON)) { if (_peekIdentifier()) { pseudoPage = identifier(); // TODO(terry): Normalize pseudoPage to lowercase. if (isChecked && !(pseudoPage.name == 'left' || pseudoPage.name == 'right' || pseudoPage.name == 'first')) { _warning( 'Pseudo page must be left, top or first', pseudoPage.span); return null; } } } var pseudoName = pseudoPage is Identifier ? pseudoPage.name : ''; var ident = name is Identifier ? name.name : ''; return PageDirective( ident, pseudoName, processMarginsDeclarations(), _makeSpan(start)); case TokenKind.DIRECTIVE_CHARSET: // @charset S* STRING S* ';' _next(); var charEncoding = processQuotedString(false); if (isChecked && charEncoding == null) { // Missing character encoding. _warning('missing character encoding string', _makeSpan(start)); } return CharsetDirective(charEncoding, _makeSpan(start)); // TODO(terry): Workaround Dart2js bug continue not implemented in switch // see https://code.google.com/p/dart/issues/detail?id=8270 /* case TokenKind.DIRECTIVE_MS_KEYFRAMES: // TODO(terry): For now only IE 10 (are base level) supports @keyframes, // -moz- has only been optional since Oct 2012 release of Firefox, not // all versions of webkit support @keyframes and opera doesn't yet // support w/o -o- prefix. Add more warnings for other prefixes when // they become optional. if (isChecked) { _warning('@-ms-keyframes should be @keyframes', _makeSpan(start)); } continue keyframeDirective; keyframeDirective: */ case TokenKind.DIRECTIVE_KEYFRAMES: case TokenKind.DIRECTIVE_WEB_KIT_KEYFRAMES: case TokenKind.DIRECTIVE_MOZ_KEYFRAMES: case TokenKind.DIRECTIVE_O_KEYFRAMES: // TODO(terry): Remove workaround when bug 8270 is fixed. case TokenKind.DIRECTIVE_MS_KEYFRAMES: if (tokId == TokenKind.DIRECTIVE_MS_KEYFRAMES && isChecked) { _warning('@-ms-keyframes should be @keyframes', _makeSpan(start)); } // TODO(terry): End of workaround. // Key frames grammar: // // @[browser]? keyframes [IDENT|STRING] '{' keyframes-blocks '}'; // // browser: [-webkit-, -moz-, -ms-, -o-] // // keyframes-blocks: // [keyframe-selectors '{' declarations '}']* ; // // keyframe-selectors: // ['from'|'to'|PERCENTAGE] [',' ['from'|'to'|PERCENTAGE] ]* ; _next(); Identifier name; if (_peekIdentifier()) { name = identifier(); } _eat(TokenKind.LBRACE); var keyframe = KeyFrameDirective(tokId, name, _makeSpan(start)); do { var selectors = Expressions(_makeSpan(start)); do { var term = processTerm(); // TODO(terry): Only allow from, to and PERCENTAGE ... selectors.add(term); } while (_maybeEat(TokenKind.COMMA)); keyframe.add(KeyFrameBlock( selectors, processDeclarations(), _makeSpan(start))); } while (!_maybeEat(TokenKind.RBRACE) && !isPrematureEndOfFile()); return keyframe; case TokenKind.DIRECTIVE_FONTFACE: _next(); return FontFaceDirective(processDeclarations(), _makeSpan(start)); case TokenKind.DIRECTIVE_STYLET: // Stylet grammar: // // @stylet IDENT '{' // ruleset // '}' _next(); dynamic name; if (_peekIdentifier()) { name = identifier(); } _eat(TokenKind.LBRACE); var productions = <TreeNode>[]; start = _peekToken.span; while (!_maybeEat(TokenKind.END_OF_FILE)) { final rule = processRule(); if (rule == null) { break; } productions.add(rule); } _eat(TokenKind.RBRACE); return StyletDirective(name, productions, _makeSpan(start)); case TokenKind.DIRECTIVE_NAMESPACE: // Namespace grammar: // // @namespace S* [namespace_prefix S*]? [STRING|URI] S* ';' S* // namespace_prefix : IDENT _next(); Identifier prefix; if (_peekIdentifier()) { prefix = identifier(); } // The namespace URI can be either a quoted string url("uri_string") // are identical. String namespaceUri; if (_peekIdentifier()) { var func = processFunction(identifier()); if (func is UriTerm) { namespaceUri = func.text; } } else { if (prefix != null && prefix.name == 'url') { var func = processFunction(prefix); if (func is UriTerm) { // @namespace url(""); namespaceUri = func.text; prefix = null; } } else { namespaceUri = processQuotedString(false); } } return NamespaceDirective( prefix != null ? prefix.name : '', namespaceUri, _makeSpan(start)); case TokenKind.DIRECTIVE_MIXIN: return processMixin(); case TokenKind.DIRECTIVE_INCLUDE: return processInclude(_makeSpan(start)); case TokenKind.DIRECTIVE_CONTENT: // TODO(terry): TBD _warning('@content not implemented.', _makeSpan(start)); return null; case TokenKind.DIRECTIVE_MOZ_DOCUMENT: return processDocumentDirective(); case TokenKind.DIRECTIVE_SUPPORTS: return processSupportsDirective(); case TokenKind.DIRECTIVE_VIEWPORT: case TokenKind.DIRECTIVE_MS_VIEWPORT: return processViewportDirective(); } return null; } /// Parse the mixin beginning token offset [start]. Returns a /// [MixinDefinition] node. /// /// Mixin grammar: /// /// @mixin IDENT [(args,...)] '{' /// [ruleset | property | directive]* /// '}' MixinDefinition processMixin() { _next(); var name = identifier(); var params = <TreeNode>[]; // Any parameters? if (_maybeEat(TokenKind.LPAREN)) { var mustHaveParam = false; var keepGoing = true; while (keepGoing) { var varDef = processVariableOrDirective(mixinParameter: true); if (varDef is VarDefinitionDirective || varDef is VarDefinition) { params.add(varDef); } else if (mustHaveParam) { _warning('Expecting parameter', _makeSpan(_peekToken.span)); keepGoing = false; } if (_maybeEat(TokenKind.COMMA)) { mustHaveParam = true; continue; } keepGoing = !_maybeEat(TokenKind.RPAREN); } } _eat(TokenKind.LBRACE); var productions = <TreeNode>[]; MixinDefinition mixinDirective; var start = _peekToken.span; while (!_maybeEat(TokenKind.END_OF_FILE)) { var directive = processDirective(); if (directive != null) { productions.add(directive); continue; } var declGroup = processDeclarations(checkBrace: false); if (declGroup.declarations.any((decl) { return decl is Declaration && decl is! IncludeMixinAtDeclaration; })) { var newDecls = <Declaration>[]; productions.forEach((include) { // If declGroup has items that are declarations then we assume // this mixin is a declaration mixin not a top-level mixin. if (include is IncludeDirective) { newDecls.add(IncludeMixinAtDeclaration(include, include.span)); } else { _warning('Error mixing of top-level vs declarations mixins', _makeSpan(include.span)); } }); declGroup.declarations.insertAll(0, newDecls); productions = []; } else { // Declarations are just @includes make it a list of productions // not a declaration group (anything else is a ruleset). Make it a // list of productions, not a declaration group. for (var decl in declGroup.declarations) { productions .add(decl is IncludeMixinAtDeclaration ? decl.include : decl); } ; declGroup.declarations.clear(); } if (declGroup.declarations.isNotEmpty) { if (productions.isEmpty) { mixinDirective = MixinDeclarationDirective( name.name, params, false, declGroup, _makeSpan(start)); break; } else { for (var decl in declGroup.declarations) { productions .add(decl is IncludeMixinAtDeclaration ? decl.include : decl); } } } else { mixinDirective = MixinRulesetDirective( name.name, params, false, productions, _makeSpan(start)); break; } } if (productions.isNotEmpty) { mixinDirective = MixinRulesetDirective( name.name, params, false, productions, _makeSpan(start)); } _eat(TokenKind.RBRACE); return mixinDirective; } /// Returns a VarDefinitionDirective or VarDefinition if a varaible otherwise /// return the token id of a directive or -1 if neither. dynamic // VarDefinitionDirective | VarDefinition | int processVariableOrDirective({bool mixinParameter = false}) { var start = _peekToken.span; var tokId = _peek(); // Handle case for @ directive (where there's a whitespace between the @ // sign and the directive name. Technically, it's not valid grammar but // a number of CSS tests test for whitespace between @ and name. if (tokId == TokenKind.AT) { _next(); tokId = _peek(); if (_peekIdentifier()) { // Is it a directive? var directive = _peekToken.text; var directiveLen = directive.length; tokId = TokenKind.matchDirectives(directive, 0, directiveLen); if (tokId == -1) { tokId = TokenKind.matchMarginDirectives(directive, 0, directiveLen); } } if (tokId == -1) { if (messages.options.lessSupport) { // Less compatibility: // @name: value; => var-name: value; (VarDefinition) // property: @name; => property: var(name); (VarUsage) Identifier name; if (_peekIdentifier()) { name = identifier(); } Expressions exprs; if (mixinParameter && _maybeEat(TokenKind.COLON)) { exprs = processExpr(); } else if (!mixinParameter) { _eat(TokenKind.COLON); exprs = processExpr(); } var span = _makeSpan(start); return VarDefinitionDirective(VarDefinition(name, exprs, span), span); } else if (isChecked) { _error('unexpected directive @$_peekToken', _peekToken.span); } } } else if (mixinParameter && _peekToken.kind == TokenKind.VAR_DEFINITION) { _next(); Identifier definedName; if (_peekIdentifier()) definedName = identifier(); Expressions exprs; if (_maybeEat(TokenKind.COLON)) { exprs = processExpr(); } return VarDefinition(definedName, exprs, _makeSpan(start)); } return tokId; } IncludeDirective processInclude(SourceSpan span, {bool eatSemiColon = true}) { // Stylet grammar: // // @include IDENT [(args,...)]; _next(); Identifier name; if (_peekIdentifier()) { name = identifier(); } var params = <List<Expression>>[]; // Any parameters? Parameters can be multiple terms per argument e.g., // 3px solid yellow, green is two parameters: // 1. 3px solid yellow // 2. green // the first has 3 terms and the second has 1 term. if (_maybeEat(TokenKind.LPAREN)) { var terms = <Expression>[]; dynamic expr; var keepGoing = true; while (keepGoing && (expr = processTerm()) != null) { // VarUsage is returns as a list terms.add(expr is List ? expr[0] : expr); keepGoing = !_peekKind(TokenKind.RPAREN); if (keepGoing) { if (_maybeEat(TokenKind.COMMA)) { params.add(terms); terms = []; } } } params.add(terms); _maybeEat(TokenKind.RPAREN); } if (eatSemiColon) { _eat(TokenKind.SEMICOLON); } return IncludeDirective(name.name, params, span); } DocumentDirective processDocumentDirective() { var start = _peekToken.span; _next(); // '@-moz-document' var functions = <LiteralTerm>[]; do { LiteralTerm function; // Consume function token: IDENT '(' var ident = identifier(); _eat(TokenKind.LPAREN); // Consume function arguments. if (ident.name == 'url-prefix' || ident.name == 'domain') { // @-moz-document allows the 'url-prefix' and 'domain' functions to // omit quotations around their argument, contrary to the standard // in which they must be strings. To support this we consume a // string with optional quotation marks, then reapply quotation // marks so they're present in the emitted CSS. var argumentStart = _peekToken.span; var value = processQuotedString(true); // Don't quote the argument if it's empty. '@-moz-document url-prefix()' // is a common pattern used for browser detection. var argument = value.isNotEmpty ? '"$value"' : ''; var argumentSpan = _makeSpan(argumentStart); _eat(TokenKind.RPAREN); var arguments = Expressions(_makeSpan(argumentSpan)) ..add(LiteralTerm(argument, argument, argumentSpan)); function = FunctionTerm( ident.name, ident.name, arguments, _makeSpan(ident.span)); } else { function = processFunction(ident); } functions.add(function); } while (_maybeEat(TokenKind.COMMA)); _eat(TokenKind.LBRACE); var groupRuleBody = processGroupRuleBody(); _eat(TokenKind.RBRACE); return DocumentDirective(functions, groupRuleBody, _makeSpan(start)); } SupportsDirective processSupportsDirective() { var start = _peekToken.span; _next(); // '@supports' var condition = processSupportsCondition(); _eat(TokenKind.LBRACE); var groupRuleBody = processGroupRuleBody(); _eat(TokenKind.RBRACE); return SupportsDirective(condition, groupRuleBody, _makeSpan(start)); } SupportsCondition processSupportsCondition() { if (_peekKind(TokenKind.IDENTIFIER)) { return processSupportsNegation(); } var start = _peekToken.span; var conditions = <SupportsConditionInParens>[]; var clauseType = ClauseType.none; while (true) { conditions.add(processSupportsConditionInParens()); ClauseType type; var text = _peekToken.text.toLowerCase(); if (text == 'and') { type = ClauseType.conjunction; } else if (text == 'or') { type = ClauseType.disjunction; } else { break; // Done parsing clause. } if (clauseType == ClauseType.none) { clauseType = type; // First operand and operator of clause. } else if (clauseType != type) { _error("Operators can't be mixed without a layer of parentheses", _peekToken.span); break; } _next(); // Consume operator. } if (clauseType == ClauseType.conjunction) { return SupportsConjunction(conditions, _makeSpan(start)); } else if (clauseType == ClauseType.disjunction) { return SupportsDisjunction(conditions, _makeSpan(start)); } else { return conditions.first; } } SupportsNegation processSupportsNegation() { var start = _peekToken.span; var text = _peekToken.text.toLowerCase(); if (text != 'not') return null; _next(); // 'not' var condition = processSupportsConditionInParens(); return SupportsNegation(condition, _makeSpan(start)); } SupportsConditionInParens processSupportsConditionInParens() { var start = _peekToken.span; _eat(TokenKind.LPAREN); // Try to parse a condition. var condition = processSupportsCondition(); if (condition != null) { _eat(TokenKind.RPAREN); return SupportsConditionInParens.nested(condition, _makeSpan(start)); } // Otherwise, parse a declaration. var declaration = processDeclaration([]); _eat(TokenKind.RPAREN); return SupportsConditionInParens(declaration, _makeSpan(start)); } ViewportDirective processViewportDirective() { var start = _peekToken.span; var name = _next().text; var declarations = processDeclarations(); return ViewportDirective(name, declarations, _makeSpan(start)); } TreeNode processRule([SelectorGroup selectorGroup]) { if (selectorGroup == null) { final directive = processDirective(); if (directive != null) { _maybeEat(TokenKind.SEMICOLON); return directive; } selectorGroup = processSelectorGroup(); } if (selectorGroup != null) { return RuleSet(selectorGroup, processDeclarations(), selectorGroup.span); } return null; } List<TreeNode> processGroupRuleBody() { var nodes = <TreeNode>[]; while (!(_peekKind(TokenKind.RBRACE) || _peekKind(TokenKind.END_OF_FILE))) { var rule = processRule(); if (rule != null) { nodes.add(rule); continue; } break; } return nodes; } /// Look ahead to see if what should be a declaration is really a selector. /// If it's a selector than it's a nested selector. This support's Less' /// nested selector syntax (requires a look ahead). E.g., /// /// div { /// width : 20px; /// span { /// color: red; /// } /// } /// /// Two tag name selectors div and span equivalent to: /// /// div { /// width: 20px; /// } /// div span { /// color: red; /// } /// /// Return [:null:] if no selector or [SelectorGroup] if a selector was /// parsed. SelectorGroup _nestedSelector() { var oldMessages = messages; _createMessages(); var markedData = _mark; // Look a head do we have a nested selector instead of a declaration? var selGroup = processSelectorGroup(); var nestedSelector = selGroup != null && _peekKind(TokenKind.LBRACE) && messages.messages.isEmpty; if (!nestedSelector) { // Not a selector so restore the world. _restore(markedData); messages = oldMessages; return null; } else { // Remember any messages from look ahead. oldMessages.mergeMessages(messages); messages = oldMessages; return selGroup; } } DeclarationGroup processDeclarations({bool checkBrace = true}) { var start = _peekToken.span; if (checkBrace) _eat(TokenKind.LBRACE); var decls = <TreeNode>[]; var dartStyles = <DartStyleExpression>[]; // List of latest styles exposed to Dart. do { var selectorGroup = _nestedSelector(); while (selectorGroup != null) { // Nested selector so process as a ruleset. var ruleset = processRule(selectorGroup); decls.add(ruleset); selectorGroup = _nestedSelector(); } var decl = processDeclaration(dartStyles); if (decl != null) { if (decl.hasDartStyle) { var newDartStyle = decl.dartStyle; // Replace or add latest Dart style. var replaced = false; for (var i = 0; i < dartStyles.length; i++) { var dartStyle = dartStyles[i]; if (dartStyle.isSame(newDartStyle)) { dartStyles[i] = newDartStyle; replaced = true; break; } } if (!replaced) { dartStyles.add(newDartStyle); } } decls.add(decl); } } while (_maybeEat(TokenKind.SEMICOLON)); if (checkBrace) _eat(TokenKind.RBRACE); // Fixup declaration to only have dartStyle that are live for this set of // declarations. for (var decl in decls) { if (decl is Declaration) { if (decl.hasDartStyle && !dartStyles.contains(decl.dartStyle)) { // Dart style not live, ignore these styles in this Declarations. decl.dartStyle = null; } } } return DeclarationGroup(decls, _makeSpan(start)); } List<DeclarationGroup> processMarginsDeclarations() { var groups = <DeclarationGroup>[]; var start = _peekToken.span; _eat(TokenKind.LBRACE); var decls = <Declaration>[]; var dartStyles = <DartStyleExpression>[]; // List of latest styles exposed to Dart. do { switch (_peek()) { case TokenKind.MARGIN_DIRECTIVE_TOPLEFTCORNER: case TokenKind.MARGIN_DIRECTIVE_TOPLEFT: case TokenKind.MARGIN_DIRECTIVE_TOPCENTER: case TokenKind.MARGIN_DIRECTIVE_TOPRIGHT: case TokenKind.MARGIN_DIRECTIVE_TOPRIGHTCORNER: case TokenKind.MARGIN_DIRECTIVE_BOTTOMLEFTCORNER: case TokenKind.MARGIN_DIRECTIVE_BOTTOMLEFT: case TokenKind.MARGIN_DIRECTIVE_BOTTOMCENTER: case TokenKind.MARGIN_DIRECTIVE_BOTTOMRIGHT: case TokenKind.MARGIN_DIRECTIVE_BOTTOMRIGHTCORNER: case TokenKind.MARGIN_DIRECTIVE_LEFTTOP: case TokenKind.MARGIN_DIRECTIVE_LEFTMIDDLE: case TokenKind.MARGIN_DIRECTIVE_LEFTBOTTOM: case TokenKind.MARGIN_DIRECTIVE_RIGHTTOP: case TokenKind.MARGIN_DIRECTIVE_RIGHTMIDDLE: case TokenKind.MARGIN_DIRECTIVE_RIGHTBOTTOM: // Margin syms processed. // margin : // margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S* // // margin_sym : @top-left-corner, @top-left, @bottom-left, etc. var marginSym = _peek(); _next(); var declGroup = processDeclarations(); if (declGroup != null) { groups.add(MarginGroup( marginSym, declGroup.declarations, _makeSpan(start))); } break; default: var decl = processDeclaration(dartStyles); if (decl != null) { if (decl.hasDartStyle) { var newDartStyle = decl.dartStyle; // Replace or add latest Dart style. var replaced = false; for (var i = 0; i < dartStyles.length; i++) { var dartStyle = dartStyles[i]; if (dartStyle.isSame(newDartStyle)) { dartStyles[i] = newDartStyle; replaced = true; break; } } if (!replaced) { dartStyles.add(newDartStyle); } } decls.add(decl); } _maybeEat(TokenKind.SEMICOLON); break; } } while (!_maybeEat(TokenKind.RBRACE) && !isPrematureEndOfFile()); // Fixup declaration to only have dartStyle that are live for this set of // declarations. for (var decl in decls) { if (decl.hasDartStyle && !dartStyles.contains(decl.dartStyle)) { // Dart style not live, ignore these styles in this Declarations. decl.dartStyle = null; } } if (decls.isNotEmpty) { groups.add(DeclarationGroup(decls, _makeSpan(start))); } return groups; } SelectorGroup processSelectorGroup() { var selectors = <Selector>[]; var start = _peekToken.span; tokenizer.inSelector = true; do { var selector = processSelector(); if (selector != null) { selectors.add(selector); } } while (_maybeEat(TokenKind.COMMA)); tokenizer.inSelector = false; if (selectors.isNotEmpty) { return SelectorGroup(selectors, _makeSpan(start)); } return null; } /// Return list of selectors Selector processSelector() { var simpleSequences = <SimpleSelectorSequence>[]; var start = _peekToken.span; while (true) { // First item is never descendant make sure it's COMBINATOR_NONE. var selectorItem = simpleSelectorSequence(simpleSequences.isEmpty); if (selectorItem != null) { simpleSequences.add(selectorItem); } else { break; } } if (simpleSequences.isEmpty) return null; return Selector(simpleSequences, _makeSpan(start)); } /// Same as [processSelector] but reports an error for each combinator. /// /// This is a quick fix for parsing <compound-selectors> until the parser /// supports Selector Level 4 grammar: /// https://drafts.csswg.org/selectors-4/#typedef-compound-selector Selector processCompoundSelector() { var selector = processSelector(); if (selector != null) { for (var sequence in selector.simpleSelectorSequences) { if (!sequence.isCombinatorNone) { _error('compound selector can not contain combinator', sequence.span); } } } return selector; } SimpleSelectorSequence simpleSelectorSequence(bool forceCombinatorNone) { var start = _peekToken.span; var combinatorType = TokenKind.COMBINATOR_NONE; var thisOperator = false; switch (_peek()) { case TokenKind.PLUS: _eat(TokenKind.PLUS); combinatorType = TokenKind.COMBINATOR_PLUS; break; case TokenKind.GREATER: _eat(TokenKind.GREATER); combinatorType = TokenKind.COMBINATOR_GREATER; break; case TokenKind.TILDE: _eat(TokenKind.TILDE); combinatorType = TokenKind.COMBINATOR_TILDE; break; case TokenKind.AMPERSAND: _eat(TokenKind.AMPERSAND); thisOperator = true; break; } // Check if WHITESPACE existed between tokens if so we're descendent. if (combinatorType == TokenKind.COMBINATOR_NONE && !forceCombinatorNone) { if (_previousToken != null && _previousToken.end != _peekToken.start) { combinatorType = TokenKind.COMBINATOR_DESCENDANT; } } var span = _makeSpan(start); var simpleSel = thisOperator ? ElementSelector(ThisOperator(span), span) : simpleSelector(); if (simpleSel == null && (combinatorType == TokenKind.COMBINATOR_PLUS || combinatorType == TokenKind.COMBINATOR_GREATER || combinatorType == TokenKind.COMBINATOR_TILDE)) { // For "+ &", "~ &" or "> &" a selector sequence with no name is needed // so that the & will have a combinator too. This is needed to // disambiguate selector expressions: // .foo&:hover combinator before & is NONE // .foo & combinator before & is DESCDENDANT // .foo > & combinator before & is GREATER simpleSel = ElementSelector(Identifier('', span), span); } if (simpleSel != null) { return SimpleSelectorSequence(simpleSel, span, combinatorType); } return null; } /// Simple selector grammar: /// /// simple_selector_sequence /// : [ type_selector | universal ] /// [ HASH | class | attrib | pseudo | negation ]* /// | [ HASH | class | attrib | pseudo | negation ]+ /// type_selector /// : [ namespace_prefix ]? element_name /// namespace_prefix /// : [ IDENT | '*' ]? '|' /// element_name /// : IDENT /// universal /// : [ namespace_prefix ]? '*' /// class /// : '.' IDENT SimpleSelector simpleSelector() { // TODO(terry): Natalie makes a good point parsing of namespace and element // are essentially the same (asterisk or identifier) other // than the error message for element. Should consolidate the // code. // TODO(terry): Need to handle attribute namespace too. dynamic first; var start = _peekToken.span; switch (_peek()) { case TokenKind.ASTERISK: // Mark as universal namespace. var tok = _next(); first = Wildcard(_makeSpan(tok.span)); break; case TokenKind.IDENTIFIER: first = identifier(); break; default: // Expecting simple selector. // TODO(terry): Could be a synthesized token like value, etc. if (TokenKind.isKindIdentifier(_peek())) { first = identifier(); } else if (_peekKind(TokenKind.SEMICOLON)) { // Can't be a selector if we found a semi-colon. return null; } break; } if (_maybeEat(TokenKind.NAMESPACE)) { TreeNode element; switch (_peek()) { case TokenKind.ASTERISK: // Mark as universal element var tok = _next(); element = Wildcard(_makeSpan(tok.span)); break; case TokenKind.IDENTIFIER: element = identifier(); break; default: _error('expected element name or universal(*), but found $_peekToken', _peekToken.span); break; } return NamespaceSelector( first, ElementSelector(element, element.span), _makeSpan(start)); } else if (first != null) { return ElementSelector(first, _makeSpan(start)); } else { // Check for HASH | class | attrib | pseudo | negation return simpleSelectorTail(); } } bool _anyWhiteSpaceBeforePeekToken(int kind) { if (_previousToken != null && _peekToken != null && _previousToken.kind == kind) { // If end of previous token isn't same as the start of peek token then // there's something between these tokens probably whitespace. return _previousToken.end != _peekToken.start; } return false; } /// type_selector | universal | HASH | class | attrib | pseudo SimpleSelector simpleSelectorTail() { // Check for HASH | class | attrib | pseudo | negation var start = _peekToken.span; switch (_peek()) { case TokenKind.HASH: _eat(TokenKind.HASH); if (_anyWhiteSpaceBeforePeekToken(TokenKind.HASH)) { _error('Not a valid ID selector expected #id', _makeSpan(start)); return null; } return IdSelector(identifier(), _makeSpan(start)); case TokenKind.DOT: _eat(TokenKind.DOT); if (_anyWhiteSpaceBeforePeekToken(TokenKind.DOT)) { _error('Not a valid class selector expected .className', _makeSpan(start)); return null; } return ClassSelector(identifier(), _makeSpan(start)); case TokenKind.COLON: // :pseudo-class ::pseudo-element return processPseudoSelector(start); case TokenKind.LBRACK: return processAttribute(); case TokenKind.DOUBLE: _error('name must start with a alpha character, but found a number', _peekToken.span); _next(); break; } return null; } SimpleSelector processPseudoSelector(FileSpan start) { // :pseudo-class ::pseudo-element // TODO(terry): '::' should be token. _eat(TokenKind.COLON); var pseudoElement = _maybeEat(TokenKind.COLON); // TODO(terry): If no identifier specified consider optimizing out the // : or :: and making this a normal selector. For now, // create an empty pseudoName. Identifier pseudoName; if (_peekIdentifier()) { pseudoName = identifier(); } else { return null; } var name = pseudoName.name.toLowerCase(); // Functional pseudo? if (_peekToken.kind == TokenKind.LPAREN) { if (!pseudoElement && name == 'not') { _eat(TokenKind.LPAREN); // Negation : ':NOT(' S* negation_arg S* ')' var negArg = simpleSelector(); _eat(TokenKind.RPAREN); return NegationSelector(negArg, _makeSpan(start)); } else if (!pseudoElement && (name == 'host' || name == 'host-context')) { _eat(TokenKind.LPAREN); var selector = processCompoundSelector(); if (selector == null) { _errorExpected('a selector argument'); return null; } _eat(TokenKind.RPAREN); var span = _makeSpan(start); return PseudoClassFunctionSelector(pseudoName, selector, span); } else { // Special parsing for expressions in pseudo functions. Minus is used // as operator not identifier. // TODO(jmesserly): we need to flip this before we eat the "(" as the // next token will be fetched when we do that. I think we should try to // refactor so we don't need this boolean; it seems fragile. tokenizer.inSelectorExpression = true; _eat(TokenKind.LPAREN); // Handle function expression. var span = _makeSpan(start); var expr = processSelectorExpression(); tokenizer.inSelectorExpression = false; // Used during selector look-a-head if not a SelectorExpression is // bad. if (expr is SelectorExpression) { _eat(TokenKind.RPAREN); return (pseudoElement) ? PseudoElementFunctionSelector(pseudoName, expr, span) : PseudoClassFunctionSelector(pseudoName, expr, span); } else { _errorExpected('CSS expression'); return null; } } } // Treat CSS2.1 pseudo-elements defined with pseudo class syntax as pseudo- // elements for backwards compatibility. return pseudoElement || _legacyPseudoElements.contains(name) ? PseudoElementSelector(pseudoName, _makeSpan(start), isLegacy: !pseudoElement) : PseudoClassSelector(pseudoName, _makeSpan(start)); } /// In CSS3, the expressions are identifiers, strings, or of the form "an+b". /// /// : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+ /// /// num [0-9]+|[0-9]*\.[0-9]+ /// PLUS '+' /// DIMENSION {num}{ident} /// NUMBER {num} TreeNode /* SelectorExpression | LiteralTerm */ processSelectorExpression() { var start = _peekToken.span; var expressions = <Expression>[]; Token termToken; dynamic value; var keepParsing = true; while (keepParsing) { switch (_peek()) { case TokenKind.PLUS: start = _peekToken.span; termToken = _next(); expressions.add(OperatorPlus(_makeSpan(start))); break; case TokenKind.MINUS: start = _peekToken.span; termToken = _next(); expressions.add(OperatorMinus(_makeSpan(start))); break; case TokenKind.INTEGER: termToken = _next(); value = int.parse(termToken.text); break; case TokenKind.DOUBLE: termToken = _next(); value = double.parse(termToken.text); break; case TokenKind.SINGLE_QUOTE: value = processQuotedString(false); value = "'${_escapeString(value, single: true)}'"; return LiteralTerm(value, value, _makeSpan(start)); case TokenKind.DOUBLE_QUOTE: value = processQuotedString(false); value = '"${_escapeString(value)}"'; return LiteralTerm(value, value, _makeSpan(start)); case TokenKind.IDENTIFIER: value = identifier(); // Snarf up the ident we'll remap, maybe. break; default: keepParsing = false; } if (keepParsing && value != null) { var unitTerm = processDimension(termToken, value, _makeSpan(start)); expressions.add(unitTerm); value = null; } } return SelectorExpression(expressions, _makeSpan(start)); } // Attribute grammar: // // attributes : // '[' S* IDENT S* [ ATTRIB_MATCHES S* [ IDENT | STRING ] S* ]? ']' // // ATTRIB_MATCHES : // [ '=' | INCLUDES | DASHMATCH | PREFIXMATCH | SUFFIXMATCH | SUBSTRMATCH ] // // INCLUDES: '~=' // // DASHMATCH: '|=' // // PREFIXMATCH: '^=' // // SUFFIXMATCH: '$=' // // SUBSTRMATCH: '*=' AttributeSelector processAttribute() { var start = _peekToken.span; if (_maybeEat(TokenKind.LBRACK)) { var attrName = identifier(); int op; switch (_peek()) { case TokenKind.EQUALS: case TokenKind.INCLUDES: // ~= case TokenKind.DASH_MATCH: // |= case TokenKind.PREFIX_MATCH: // ^= case TokenKind.SUFFIX_MATCH: // $= case TokenKind.SUBSTRING_MATCH: // *= op = _peek(); _next(); break; default: op = TokenKind.NO_MATCH; } dynamic value; if (op != TokenKind.NO_MATCH) { // Operator hit so we require a value too. if (_peekIdentifier()) { value = identifier(); } else { value = processQuotedString(false); } if (value == null) { _error('expected attribute value string or ident', _peekToken.span); } } _eat(TokenKind.RBRACK); return AttributeSelector(attrName, op, value, _makeSpan(start)); } return null; } // Declaration grammar: // // declaration: property ':' expr prio? // // property: IDENT [or IE hacks] // prio: !important // expr: (see processExpr) // // Here are the ugly IE hacks we need to support: // property: expr prio? \9; - IE8 and below property, /9 before semi-colon // *IDENT - IE7 or below // _IDENT - IE6 property (automatically a valid ident) Declaration processDeclaration(List<DartStyleExpression> dartStyles) { Declaration decl; var start = _peekToken.span; // IE7 hack of * before property name if so the property is IE7 or below. var ie7 = _peekKind(TokenKind.ASTERISK); if (ie7) { _next(); } // IDENT ':' expr '!important'? if (TokenKind.isIdentifier(_peekToken.kind)) { var propertyIdent = identifier(); var ieFilterProperty = propertyIdent.name.toLowerCase() == 'filter'; _eat(TokenKind.COLON); var exprs = processExpr(ieFilterProperty); var dartComposite = _styleForDart(propertyIdent, exprs, dartStyles); // Handle !important (prio) var importantPriority = _maybeEat(TokenKind.IMPORTANT); decl = Declaration(propertyIdent, exprs, dartComposite, _makeSpan(start), important: importantPriority, ie7: ie7); } else if (_peekToken.kind == TokenKind.VAR_DEFINITION) { _next(); Identifier definedName; if (_peekIdentifier()) definedName = identifier(); _eat(TokenKind.COLON); var exprs = processExpr(); decl = VarDefinition(definedName, exprs, _makeSpan(start)); } else if (_peekToken.kind == TokenKind.DIRECTIVE_INCLUDE) { // @include mixinName in the declaration area. var span = _makeSpan(start); var include = processInclude(span, eatSemiColon: false); decl = IncludeMixinAtDeclaration(include, span); } else if (_peekToken.kind == TokenKind.DIRECTIVE_EXTEND) { var simpleSequences = <TreeNode>[]; _next(); var span = _makeSpan(start); var selector = simpleSelector(); if (selector == null) { _warning('@extends expecting simple selector name', span); } else { simpleSequences.add(selector); } if (_peekKind(TokenKind.COLON)) { var pseudoSelector = processPseudoSelector(_peekToken.span); if (pseudoSelector is PseudoElementSelector || pseudoSelector is PseudoClassSelector) { simpleSequences.add(pseudoSelector); } else { _warning('not a valid selector', span); } } decl = ExtendDeclaration(simpleSequences, span); } return decl; } /// List of styles exposed to the Dart UI framework. static const int _fontPartFont = 0; static const int _fontPartVariant = 1; static const int _fontPartWeight = 2; static const int _fontPartSize = 3; static const int _fontPartFamily = 4; static const int _fontPartStyle = 5; static const int _marginPartMargin = 6; static const int _marginPartLeft = 7; static const int _marginPartTop = 8; static const int _marginPartRight = 9; static const int _marginPartBottom = 10; static const int _lineHeightPart = 11; static const int _borderPartBorder = 12; static const int _borderPartLeft = 13; static const int _borderPartTop = 14; static const int _borderPartRight = 15; static const int _borderPartBottom = 16; static const int _borderPartWidth = 17; static const int _borderPartLeftWidth = 18; static const int _borderPartTopWidth = 19; static const int _borderPartRightWidth = 20; static const int _borderPartBottomWidth = 21; static const int _heightPart = 22; static const int _widthPart = 23; static const int _paddingPartPadding = 24; static const int _paddingPartLeft = 25; static const int _paddingPartTop = 26; static const int _paddingPartRight = 27; static const int _paddingPartBottom = 28; static const Map<String, int> _stylesToDart = { 'font': _fontPartFont, 'font-family': _fontPartFamily, 'font-size': _fontPartSize, 'font-style': _fontPartStyle, 'font-variant': _fontPartVariant, 'font-weight': _fontPartWeight, 'line-height': _lineHeightPart, 'margin': _marginPartMargin, 'margin-left': _marginPartLeft, 'margin-right': _marginPartRight, 'margin-top': _marginPartTop, 'margin-bottom': _marginPartBottom, 'border': _borderPartBorder, 'border-left': _borderPartLeft, 'border-right': _borderPartRight, 'border-top': _borderPartTop, 'border-bottom': _borderPartBottom, 'border-width': _borderPartWidth, 'border-left-width': _borderPartLeftWidth, 'border-top-width': _borderPartTopWidth, 'border-right-width': _borderPartRightWidth, 'border-bottom-width': _borderPartBottomWidth, 'height': _heightPart, 'width': _widthPart, 'padding': _paddingPartPadding, 'padding-left': _paddingPartLeft, 'padding-top': _paddingPartTop, 'padding-right': _paddingPartRight, 'padding-bottom': _paddingPartBottom }; static const Map<String, int> _nameToFontWeight = { 'bold': FontWeight.bold, 'normal': FontWeight.normal }; static int _findStyle(String styleName) => _stylesToDart[styleName]; DartStyleExpression _styleForDart(Identifier property, Expressions exprs, List<DartStyleExpression> dartStyles) { var styleType = _findStyle(property.name.toLowerCase()); if (styleType != null) { return buildDartStyleNode(styleType, exprs, dartStyles); } return null; } FontExpression _mergeFontStyles( FontExpression fontExpr, List<DartStyleExpression> dartStyles) { // Merge all font styles for this class selector. for (var dartStyle in dartStyles) { if (dartStyle.isFont) { fontExpr = FontExpression.merge(dartStyle, fontExpr); } } return fontExpr; } DartStyleExpression buildDartStyleNode( int styleType, Expressions exprs, List<DartStyleExpression> dartStyles) { switch (styleType) { // Properties in order: // // font-style font-variant font-weight font-size/line-height font-family // // The font-size and font-family values are required. If other values are // missing; a default, if it exist, will be used. case _fontPartFont: var processor = ExpressionsProcessor(exprs); return _mergeFontStyles(processor.processFont(), dartStyles); case _fontPartFamily: var processor = ExpressionsProcessor(exprs); try { return _mergeFontStyles(processor.processFontFamily(), dartStyles); } catch (fontException) { _error(fontException, _peekToken.span); } break; case _fontPartSize: var processor = ExpressionsProcessor(exprs); return _mergeFontStyles(processor.processFontSize(), dartStyles); case _fontPartStyle: // Possible style values: // normal [default] // italic // oblique // inherit // TODO(terry): TBD break; case _fontPartVariant: // Possible variant values: // normal [default] // small-caps // inherit // TODO(terry): TBD break; case _fontPartWeight: // Possible weight values: // normal [default] // bold // bolder // lighter // 100 - 900 // inherit // TODO(terry): Only 'normal', 'bold', or values of 100-900 supoorted // need to handle bolder, lighter, and inherit. See // https://github.com/dart-lang/csslib/issues/1 var expr = exprs.expressions[0]; if (expr is NumberTerm) { var fontExpr = FontExpression(expr.span, weight: expr.value); return _mergeFontStyles(fontExpr, dartStyles); } else if (expr is LiteralTerm) { var weight = _nameToFontWeight[expr.value.toString()]; if (weight != null) { var fontExpr = FontExpression(expr.span, weight: weight); return _mergeFontStyles(fontExpr, dartStyles); } } break; case _lineHeightPart: if (exprs.expressions.length == 1) { var expr = exprs.expressions[0]; if (expr is UnitTerm) { var unitTerm = expr; // TODO(terry): Need to handle other units and LiteralTerm normal // See https://github.com/dart-lang/csslib/issues/2. if (unitTerm.unit == TokenKind.UNIT_LENGTH_PX || unitTerm.unit == TokenKind.UNIT_LENGTH_PT) { var fontExpr = FontExpression(expr.span, lineHeight: LineHeight(expr.value, inPixels: true)); return _mergeFontStyles(fontExpr, dartStyles); } else if (isChecked) { _warning('Unexpected unit for line-height', expr.span); } } else if (expr is NumberTerm) { var fontExpr = FontExpression(expr.span, lineHeight: LineHeight(expr.value, inPixels: false)); return _mergeFontStyles(fontExpr, dartStyles); } else if (isChecked) { _warning('Unexpected value for line-height', expr.span); } } break; case _marginPartMargin: return MarginExpression.boxEdge(exprs.span, processFourNums(exprs)); case _borderPartBorder: for (var expr in exprs.expressions) { var v = marginValue(expr); if (v != null) { final box = BoxEdge.uniform(v); return BorderExpression.boxEdge(exprs.span, box); } } break; case _borderPartWidth: var v = marginValue(exprs.expressions[0]); if (v != null) { final box = BoxEdge.uniform(v); return BorderExpression.boxEdge(exprs.span, box); } break; case _paddingPartPadding: return PaddingExpression.boxEdge(exprs.span, processFourNums(exprs)); case _marginPartLeft: case _marginPartTop: case _marginPartRight: case _marginPartBottom: case _borderPartLeft: case _borderPartTop: case _borderPartRight: case _borderPartBottom: case _borderPartLeftWidth: case _borderPartTopWidth: case _borderPartRightWidth: case _borderPartBottomWidth: case _heightPart: case _widthPart: case _paddingPartLeft: case _paddingPartTop: case _paddingPartRight: case _paddingPartBottom: if (exprs.expressions.isNotEmpty) { return processOneNumber(exprs, styleType); } break; } return null; } // TODO(terry): Look at handling width of thin, thick, etc. any none numbers // to convert to a number. DartStyleExpression processOneNumber(Expressions exprs, int part) { var value = marginValue(exprs.expressions[0]); if (value != null) { switch (part) { case _marginPartLeft: return MarginExpression(exprs.span, left: value); case _marginPartTop: return MarginExpression(exprs.span, top: value); case _marginPartRight: return MarginExpression(exprs.span, right: value); case _marginPartBottom: return MarginExpression(exprs.span, bottom: value); case _borderPartLeft: case _borderPartLeftWidth: return BorderExpression(exprs.span, left: value); case _borderPartTop: case _borderPartTopWidth: return BorderExpression(exprs.span, top: value); case _borderPartRight: case _borderPartRightWidth: return BorderExpression(exprs.span, right: value); case _borderPartBottom: case _borderPartBottomWidth: return BorderExpression(exprs.span, bottom: value); case _heightPart: return HeightExpression(exprs.span, value); case _widthPart: return WidthExpression(exprs.span, value); case _paddingPartLeft: return PaddingExpression(exprs.span, left: value); case _paddingPartTop: return PaddingExpression(exprs.span, top: value); case _paddingPartRight: return PaddingExpression(exprs.span, right: value); case _paddingPartBottom: return PaddingExpression(exprs.span, bottom: value); } } return null; } /// Margins are of the format: /// /// * top,right,bottom,left (4 parameters) /// * top,right/left, bottom (3 parameters) /// * top/bottom,right/left (2 parameters) /// * top/right/bottom/left (1 parameter) /// /// The values of the margins can be a unit or unitless or auto. BoxEdge processFourNums(Expressions exprs) { num top; num right; num bottom; num left; var totalExprs = exprs.expressions.length; switch (totalExprs) { case 1: top = marginValue(exprs.expressions[0]); right = top; bottom = top; left = top; break; case 2: top = marginValue(exprs.expressions[0]); bottom = top; right = marginValue(exprs.expressions[1]); left = right; break; case 3: top = marginValue(exprs.expressions[0]); right = marginValue(exprs.expressions[1]); left = right; bottom = marginValue(exprs.expressions[2]); break; case 4: top = marginValue(exprs.expressions[0]); right = marginValue(exprs.expressions[1]); bottom = marginValue(exprs.expressions[2]); left = marginValue(exprs.expressions[3]); break; default: return null; } return BoxEdge.clockwiseFromTop(top, right, bottom, left); } // TODO(terry): Need to handle auto. num marginValue(Expression exprTerm) { if (exprTerm is UnitTerm) { return exprTerm.value as num; } else if (exprTerm is NumberTerm) { return exprTerm.value as num; } return null; } // Expression grammar: // // expression: term [ operator? term]* // // operator: '/' | ',' // term: (see processTerm) Expressions processExpr([bool ieFilter = false]) { var start = _peekToken.span; var expressions = Expressions(_makeSpan(start)); var keepGoing = true; dynamic expr; while (keepGoing && (expr = processTerm(ieFilter)) != null) { Expression op; var opStart = _peekToken.span; switch (_peek()) { case TokenKind.SLASH: op = OperatorSlash(_makeSpan(opStart)); break; case TokenKind.COMMA: op = OperatorComma(_makeSpan(opStart)); break; case TokenKind.BACKSLASH: // Backslash outside of string; detected IE8 or older signaled by \9 // at end of an expression. var ie8Start = _peekToken.span; _next(); if (_peekKind(TokenKind.INTEGER)) { var numToken = _next(); var value = int.parse(numToken.text); if (value == 9) { op = IE8Term(_makeSpan(ie8Start)); } else if (isChecked) { _warning( '\$value is not valid in an expression', _makeSpan(start)); } } break; } if (expr != null) { if (expr is List<Expression>) { for (var exprItem in expr) { expressions.add(exprItem); } } else { expressions.add(expr); } } else { keepGoing = false; } if (op != null) { expressions.add(op); if (op is IE8Term) { keepGoing = false; } else { _next(); } } } return expressions; } static const int MAX_UNICODE = 0x10FFFF; // Term grammar: // // term: // unary_operator? // [ term_value ] // | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor // // term_value: // NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | // TIME S* | FREQ S* | function // // NUMBER: {num} // PERCENTAGE: {num}% // LENGTH: {num}['px' | 'cm' | 'mm' | 'in' | 'pt' | 'pc'] // EMS: {num}'em' // EXS: {num}'ex' // ANGLE: {num}['deg' | 'rad' | 'grad'] // TIME: {num}['ms' | 's'] // FREQ: {num}['hz' | 'khz'] // function: IDENT '(' expr ')' // dynamic /* Expression | List<Expression> | ... */ processTerm( [bool ieFilter = false]) { var start = _peekToken.span; Token t; // token for term's value dynamic value; // value of term (numeric values) var unary = ''; switch (_peek()) { case TokenKind.HASH: _eat(TokenKind.HASH); if (!_anyWhiteSpaceBeforePeekToken(TokenKind.HASH)) { String hexText; if (_peekKind(TokenKind.INTEGER)) { var hexText1 = _peekToken.text; _next(); // Append identifier only if there's no delimiting whitespace. if (_peekIdentifier() && _previousToken.end == _peekToken.start) { hexText = '$hexText1${identifier().name}'; } else { hexText = hexText1; } } else if (_peekIdentifier()) { hexText = identifier().name; } if (hexText != null) { return _parseHex(hexText, _makeSpan(start)); } } if (isChecked) { _warning('Expected hex number', _makeSpan(start)); } // Construct the bad hex value with a #<space>number. return _parseHex(' ${processTerm().text}', _makeSpan(start)); case TokenKind.INTEGER: t = _next(); value = int.parse('${unary}${t.text}'); break; case TokenKind.DOUBLE: t = _next(); value = double.parse('${unary}${t.text}'); break; case TokenKind.SINGLE_QUOTE: value = processQuotedString(false); value = "'${_escapeString(value, single: true)}'"; return LiteralTerm(value, value, _makeSpan(start)); case TokenKind.DOUBLE_QUOTE: value = processQuotedString(false); value = '"${_escapeString(value)}"'; return LiteralTerm(value, value, _makeSpan(start)); case TokenKind.LPAREN: _next(); var group = GroupTerm(_makeSpan(start)); dynamic /* Expression | List<Expression> | ... */ term; do { term = processTerm(); if (term != null && term is LiteralTerm) { group.add(term); } } while (term != null && !_maybeEat(TokenKind.RPAREN) && !isPrematureEndOfFile()); return group; case TokenKind.LBRACK: _next(); var term = processTerm(); if (!(term is NumberTerm)) { _error('Expecting a positive number', _makeSpan(start)); } _eat(TokenKind.RBRACK); return ItemTerm(term.value, term.text, _makeSpan(start)); case TokenKind.IDENTIFIER: var nameValue = identifier(); // Snarf up the ident we'll remap, maybe. if (!ieFilter && _maybeEat(TokenKind.LPAREN)) { var calc = processCalc(nameValue); if (calc != null) return calc; // FUNCTION return processFunction(nameValue); } if (ieFilter) { if (_maybeEat(TokenKind.COLON) && nameValue.name.toLowerCase() == 'progid') { // IE filter:progid: return processIEFilter(start); } else { // Handle filter:<name> where name is any filter e.g., alpha, // chroma, Wave, blur, etc. return processIEFilter(start); } } // TODO(terry): Need to have a list of known identifiers today only // 'from' is special. if (nameValue.name == 'from') { return LiteralTerm(nameValue, nameValue.name, _makeSpan(start)); } // What kind of identifier is it, named color? var colorEntry = TokenKind.matchColorName(nameValue.name); if (colorEntry == null) { if (isChecked) { var propName = nameValue.name; var errMsg = TokenKind.isPredefinedName(propName) ? 'Improper use of property value ${propName}' : 'Unknown property value ${propName}'; _warning(errMsg, _makeSpan(start)); } return LiteralTerm(nameValue, nameValue.name, _makeSpan(start)); } // Yes, process the color as an RGB value. var rgbColor = TokenKind.decimalToHex(TokenKind.colorValue(colorEntry), 6); return _parseHex(rgbColor, _makeSpan(start)); case TokenKind.UNICODE_RANGE: String first; String second; int firstNumber; int secondNumber; _eat(TokenKind.UNICODE_RANGE, unicodeRange: true); if (_maybeEat(TokenKind.HEX_INTEGER, unicodeRange: true)) { first = _previousToken.text; firstNumber = int.parse('0x$first'); if (firstNumber > MAX_UNICODE) { _error('unicode range must be less than 10FFFF', _makeSpan(start)); } if (_maybeEat(TokenKind.MINUS, unicodeRange: true)) { if (_maybeEat(TokenKind.HEX_INTEGER, unicodeRange: true)) { second = _previousToken.text; secondNumber = int.parse('0x$second'); if (secondNumber > MAX_UNICODE) { _error( 'unicode range must be less than 10FFFF', _makeSpan(start)); } if (firstNumber > secondNumber) { _error('unicode first range can not be greater than last', _makeSpan(start)); } } } } else if (_maybeEat(TokenKind.HEX_RANGE, unicodeRange: true)) { first = _previousToken.text; } return UnicodeRangeTerm(first, second, _makeSpan(start)); case TokenKind.AT: if (messages.options.lessSupport) { _next(); var expr = processExpr(); if (isChecked && expr.expressions.length > 1) { _error('only @name for Less syntax', _peekToken.span); } var param = expr.expressions[0]; var varUsage = VarUsage((param as LiteralTerm).text, [], _makeSpan(start)); expr.expressions[0] = varUsage; return expr.expressions; } break; } return t != null ? processDimension(t, value, _makeSpan(start)) : null; } /// Process all dimension units. LiteralTerm processDimension(Token t, var value, SourceSpan span) { LiteralTerm term; var unitType = _peek(); switch (unitType) { case TokenKind.UNIT_EM: term = EmTerm(value, t.text, span); _next(); // Skip the unit break; case TokenKind.UNIT_EX: term = ExTerm(value, t.text, span); _next(); // Skip the unit break; case TokenKind.UNIT_LENGTH_PX: case TokenKind.UNIT_LENGTH_CM: case TokenKind.UNIT_LENGTH_MM: case TokenKind.UNIT_LENGTH_IN: case TokenKind.UNIT_LENGTH_PT: case TokenKind.UNIT_LENGTH_PC: term = LengthTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_ANGLE_DEG: case TokenKind.UNIT_ANGLE_RAD: case TokenKind.UNIT_ANGLE_GRAD: case TokenKind.UNIT_ANGLE_TURN: term = AngleTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_TIME_MS: case TokenKind.UNIT_TIME_S: term = TimeTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_FREQ_HZ: case TokenKind.UNIT_FREQ_KHZ: term = FreqTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.PERCENT: term = PercentageTerm(value, t.text, span); _next(); // Skip the % break; case TokenKind.UNIT_FRACTION: term = FractionTerm(value, t.text, span); _next(); // Skip the unit break; case TokenKind.UNIT_RESOLUTION_DPI: case TokenKind.UNIT_RESOLUTION_DPCM: case TokenKind.UNIT_RESOLUTION_DPPX: term = ResolutionTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_CH: term = ChTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_REM: term = RemTerm(value, t.text, span, unitType); _next(); // Skip the unit break; case TokenKind.UNIT_VIEWPORT_VW: case TokenKind.UNIT_VIEWPORT_VH: case TokenKind.UNIT_VIEWPORT_VMIN: case TokenKind.UNIT_VIEWPORT_VMAX: term = ViewportTerm(value, t.text, span, unitType); _next(); // Skip the unit break; default: if (value != null) { if (value is Identifier) { term = LiteralTerm(value, value.name, span); } else if (t != null) { term = NumberTerm(value, t.text, span); } } } return term; } String processQuotedString([bool urlString = false]) { var start = _peekToken.span; // URI term sucks up everything inside of quotes(' or ") or between parens var stopToken = urlString ? TokenKind.RPAREN : -1; // Note: disable skipping whitespace tokens inside a string. // TODO(jmesserly): the layering here feels wrong. var inString = tokenizer._inString; tokenizer._inString = false; switch (_peek()) { case TokenKind.SINGLE_QUOTE: stopToken = TokenKind.SINGLE_QUOTE; _next(); // Skip the SINGLE_QUOTE. start = _peekToken.span; break; case TokenKind.DOUBLE_QUOTE: stopToken = TokenKind.DOUBLE_QUOTE; _next(); // Skip the DOUBLE_QUOTE. start = _peekToken.span; break; default: if (urlString) { if (_peek() == TokenKind.LPAREN) { _next(); // Skip the LPAREN. start = _peekToken.span; } stopToken = TokenKind.RPAREN; } else { _error('unexpected string', _makeSpan(start)); } break; } // Gobble up everything until we hit our stop token. var stringValue = StringBuffer(); while (_peek() != stopToken && _peek() != TokenKind.END_OF_FILE) { stringValue.write(_next().text); } tokenizer._inString = inString; // All characters between quotes is the string. if (stopToken != TokenKind.RPAREN) { _next(); // Skip the SINGLE_QUOTE or DOUBLE_QUOTE; } return stringValue.toString(); } // TODO(terry): Should probably understand IE's non-standard filter syntax to // fully support calc, var(), etc. /// IE's filter property breaks CSS value parsing. IE's format can be: /// /// filter: progid:DXImageTransform.MS.gradient(Type=0, Color='#9d8b83'); /// /// We'll just parse everything after the 'progid:' look for the left paren /// then parse to the right paren ignoring everything in between. dynamic processIEFilter(FileSpan startAfterProgidColon) { // Support non-functional filters (i.e. filter: FlipH) var kind = _peek(); if (kind == TokenKind.SEMICOLON || kind == TokenKind.RBRACE) { var tok = tokenizer.makeIEFilter( startAfterProgidColon.start.offset, _peekToken.start); return LiteralTerm(tok.text, tok.text, tok.span); } var parens = 0; while (_peek() != TokenKind.END_OF_FILE) { switch (_peek()) { case TokenKind.LPAREN: _eat(TokenKind.LPAREN); parens++; break; case TokenKind.RPAREN: _eat(TokenKind.RPAREN); if (--parens == 0) { var tok = tokenizer.makeIEFilter( startAfterProgidColon.start.offset, _peekToken.start); return LiteralTerm(tok.text, tok.text, tok.span); } break; default: _eat(_peek()); } } } // TODO(terry): Hack to gobble up the calc expression as a string looking // for the matching RPAREN the expression is not parsed into the // AST. // // grammar should be: // // <calc()> = calc( <calc-sum> ) // <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* // <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* // <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> ) // String processCalcExpression() { var inString = tokenizer._inString; tokenizer._inString = false; // Gobble up everything until we hit our stop token. var stringValue = StringBuffer(); var left = 1; var matchingParens = false; while (_peek() != TokenKind.END_OF_FILE && !matchingParens) { var token = _peek(); if (token == TokenKind.LPAREN) { left++; } else if (token == TokenKind.RPAREN) left--; matchingParens = left == 0; if (!matchingParens) stringValue.write(_next().text); } if (!matchingParens) { _error('problem parsing function expected ), ', _peekToken.span); } tokenizer._inString = inString; return stringValue.toString(); } CalcTerm processCalc(Identifier func) { var start = _peekToken.span; var name = func.name; if (name == 'calc' || name == '-webkit-calc' || name == '-moz-calc') { // TODO(terry): Implement expression parsing properly. var expression = processCalcExpression(); var calcExpr = LiteralTerm(expression, expression, _makeSpan(start)); if (!_maybeEat(TokenKind.RPAREN)) { _error('problem parsing function expected ), ', _peekToken.span); } return CalcTerm(name, name, calcExpr, _makeSpan(start)); } return null; } // Function grammar: // // function: IDENT '(' expr ')' // TreeNode /* LiteralTerm | Expression */ processFunction(Identifier func) { var start = _peekToken.span; var name = func.name; switch (name) { case 'url': // URI term sucks up everything inside of quotes(' or ") or between // parens. var urlParam = processQuotedString(true); // TODO(terry): Better error message and checking for mismatched quotes. if (_peek() == TokenKind.END_OF_FILE) { _error('problem parsing URI', _peekToken.span); } if (_peek() == TokenKind.RPAREN) { _next(); } return UriTerm(urlParam, _makeSpan(start)); case 'var': // TODO(terry): Consider handling var in IE specific filter/progid. // This will require parsing entire IE specific syntax // e.g. `param = value` or `progid:com_id`, etc. // for example: // // var-blur: Blur(Add = 0, Direction = 225, Strength = 10); // var-gradient: progid:DXImageTransform.Microsoft.gradient" // (GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670'); var expr = processExpr(); if (!_maybeEat(TokenKind.RPAREN)) { _error('problem parsing var expected ), ', _peekToken.span); } if (isChecked && expr.expressions.whereType<OperatorComma>().length > 1) { _error('too many parameters to var()', _peekToken.span); } var paramName = (expr.expressions[0] as LiteralTerm).text; // [0] - var name, [1] - OperatorComma, [2] - default value. var defaultValues = expr.expressions.length >= 3 ? expr.expressions.sublist(2) : <Expression>[]; return VarUsage(paramName, defaultValues, _makeSpan(start)); default: var expr = processExpr(); if (!_maybeEat(TokenKind.RPAREN)) { _error('problem parsing function expected ), ', _peekToken.span); } return FunctionTerm(name, name, expr, _makeSpan(start)); } } Identifier identifier() { var tok = _next(); if (!TokenKind.isIdentifier(tok.kind) && !TokenKind.isKindIdentifier(tok.kind)) { if (isChecked) { _warning('expected identifier, but found $tok', tok.span); } return Identifier('', _makeSpan(tok.span)); } return Identifier(tok.text, _makeSpan(tok.span)); } // TODO(terry): Move this to base <= 36 and into shared code. static int _hexDigit(int c) { if (c >= 48 /*0*/ && c <= 57 /*9*/) { return c - 48; } else if (c >= 97 /*a*/ && c <= 102 /*f*/) { return c - 87; } else if (c >= 65 /*A*/ && c <= 70 /*F*/) { return c - 55; } else { return -1; } } HexColorTerm _parseHex(String hexText, SourceSpan span) { var hexValue = 0; for (var i = 0; i < hexText.length; i++) { var digit = _hexDigit(hexText.codeUnitAt(i)); if (digit < 0) { _warning('Bad hex number', span); return HexColorTerm(BAD_HEX_VALUE(), hexText, span); } hexValue = (hexValue << 4) + digit; } // Make 3 character hex value #RRGGBB => #RGB iff: // high/low nibble of RR is the same, high/low nibble of GG is the same and // high/low nibble of BB is the same. if (hexText.length == 6 && hexText[0] == hexText[1] && hexText[2] == hexText[3] && hexText[4] == hexText[5]) { hexText = '${hexText[0]}${hexText[2]}${hexText[4]}'; } else if (hexText.length == 4 && hexText[0] == hexText[1] && hexText[2] == hexText[3]) { hexText = '${hexText[0]}${hexText[2]}'; } else if (hexText.length == 2 && hexText[0] == hexText[1]) { hexText = '${hexText[0]}'; } return HexColorTerm(hexValue, hexText, span); } } class ExpressionsProcessor { final Expressions _exprs; int _index = 0; ExpressionsProcessor(this._exprs); // TODO(terry): Only handles ##px unit. FontExpression processFontSize() { // font-size[/line-height] // // Possible size values: // * xx-small // * small // * medium [default] // * large // * x-large // * xx-large // * smaller // * larger // * ##length in px, pt, etc. // * ##%, percent of parent elem's font-size // * inherit LengthTerm size; LineHeight lineHt; var nextIsLineHeight = false; for (; _index < _exprs.expressions.length; _index++) { var expr = _exprs.expressions[_index]; if (size == null && expr is LengthTerm) { // font-size part. size = expr; } else if (size != null) { if (expr is OperatorSlash) { // LineHeight could follow? nextIsLineHeight = true; } else if (nextIsLineHeight && expr is LengthTerm) { assert(expr.unit == TokenKind.UNIT_LENGTH_PX); lineHt = LineHeight(expr.value, inPixels: true); nextIsLineHeight = false; _index++; break; } else { break; } } else { break; } } return FontExpression(_exprs.span, size: size, lineHeight: lineHt); } FontExpression processFontFamily() { var family = <String>[]; // Possible family values: // * font-family: arial, Times new roman ,Lucida Sans Unicode,Courier; // * font-family: "Times New Roman", arial, Lucida Sans Unicode, Courier; var moreFamilies = false; for (; _index < _exprs.expressions.length; _index++) { var expr = _exprs.expressions[_index]; if (expr is LiteralTerm) { if (family.isEmpty || moreFamilies) { // It's font-family now. family.add(expr.toString()); moreFamilies = false; } else if (isChecked) { messages.warning('Only font-family can be a list', _exprs.span); } } else if (expr is OperatorComma && family.isNotEmpty) { moreFamilies = true; } else { break; } } return FontExpression(_exprs.span, family: family); } FontExpression processFont() { // Process all parts of the font expression. FontExpression fontSize; FontExpression fontFamily; for (; _index < _exprs.expressions.length; _index++) { // Order is font-size font-family fontSize ??= processFontSize(); fontFamily ??= processFontFamily(); //TODO(terry): Handle font-weight, font-style, and font-variant. See // https://github.com/dart-lang/csslib/issues/3 // https://github.com/dart-lang/csslib/issues/4 // https://github.com/dart-lang/csslib/issues/5 } return FontExpression(_exprs.span, size: fontSize.font.size, lineHeight: fontSize.font.lineHeight, family: fontFamily.font.family); } } /// Escapes [text] for use in a CSS string. /// [single] specifies single quote `'` vs double quote `"`. String _escapeString(String text, {bool single = false}) { StringBuffer result; for (var i = 0; i < text.length; i++) { var code = text.codeUnitAt(i); String replace; switch (code) { case 34 /*'"'*/ : if (!single) replace = r'\"'; break; case 39 /*"'"*/ : if (single) replace = r"\'"; break; } if (replace != null && result == null) { result = StringBuffer(text.substring(0, i)); } if (result != null) result.write(replace ?? text[i]); } return result == null ? text : result.toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/visitor.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:source_span/source_span.dart'; import 'parser.dart'; part 'src/css_printer.dart'; part 'src/tree.dart'; part 'src/tree_base.dart'; part 'src/tree_printer.dart'; abstract class VisitorBase { dynamic visitCalcTerm(CalcTerm node); dynamic visitCssComment(CssComment node); dynamic visitCommentDefinition(CommentDefinition node); dynamic visitStyleSheet(StyleSheet node); dynamic visitNoOp(NoOp node); dynamic visitTopLevelProduction(TopLevelProduction node); dynamic visitDirective(Directive node); dynamic visitDocumentDirective(DocumentDirective node); dynamic visitSupportsDirective(SupportsDirective node); dynamic visitSupportsConditionInParens(SupportsConditionInParens node); dynamic visitSupportsNegation(SupportsNegation node); dynamic visitSupportsConjunction(SupportsConjunction node); dynamic visitSupportsDisjunction(SupportsDisjunction node); dynamic visitViewportDirective(ViewportDirective node); dynamic visitMediaExpression(MediaExpression node); dynamic visitMediaQuery(MediaQuery node); dynamic visitMediaDirective(MediaDirective node); dynamic visitHostDirective(HostDirective node); dynamic visitPageDirective(PageDirective node); dynamic visitCharsetDirective(CharsetDirective node); dynamic visitImportDirective(ImportDirective node); dynamic visitKeyFrameDirective(KeyFrameDirective node); dynamic visitKeyFrameBlock(KeyFrameBlock node); dynamic visitFontFaceDirective(FontFaceDirective node); dynamic visitStyletDirective(StyletDirective node); dynamic visitNamespaceDirective(NamespaceDirective node); dynamic visitVarDefinitionDirective(VarDefinitionDirective node); dynamic visitMixinDefinition(MixinDefinition node); dynamic visitMixinRulesetDirective(MixinRulesetDirective node); dynamic visitMixinDeclarationDirective(MixinDeclarationDirective node); dynamic visitIncludeDirective(IncludeDirective node); dynamic visitContentDirective(ContentDirective node); dynamic visitRuleSet(RuleSet node); dynamic visitDeclarationGroup(DeclarationGroup node); dynamic visitMarginGroup(MarginGroup node); dynamic visitDeclaration(Declaration node); dynamic visitVarDefinition(VarDefinition node); dynamic visitIncludeMixinAtDeclaration(IncludeMixinAtDeclaration node); dynamic visitExtendDeclaration(ExtendDeclaration node); dynamic visitSelectorGroup(SelectorGroup node); dynamic visitSelector(Selector node); dynamic visitSimpleSelectorSequence(SimpleSelectorSequence node); dynamic visitSimpleSelector(SimpleSelector node); dynamic visitElementSelector(ElementSelector node); dynamic visitNamespaceSelector(NamespaceSelector node); dynamic visitAttributeSelector(AttributeSelector node); dynamic visitIdSelector(IdSelector node); dynamic visitClassSelector(ClassSelector node); dynamic visitPseudoClassSelector(PseudoClassSelector node); dynamic visitPseudoElementSelector(PseudoElementSelector node); dynamic visitPseudoClassFunctionSelector(PseudoClassFunctionSelector node); dynamic visitPseudoElementFunctionSelector( PseudoElementFunctionSelector node); dynamic visitNegationSelector(NegationSelector node); dynamic visitSelectorExpression(SelectorExpression node); dynamic visitUnicodeRangeTerm(UnicodeRangeTerm node); dynamic visitLiteralTerm(LiteralTerm node); dynamic visitHexColorTerm(HexColorTerm node); dynamic visitNumberTerm(NumberTerm node); dynamic visitUnitTerm(UnitTerm node); dynamic visitLengthTerm(LengthTerm node); dynamic visitPercentageTerm(PercentageTerm node); dynamic visitEmTerm(EmTerm node); dynamic visitExTerm(ExTerm node); dynamic visitAngleTerm(AngleTerm node); dynamic visitTimeTerm(TimeTerm node); dynamic visitFreqTerm(FreqTerm node); dynamic visitFractionTerm(FractionTerm node); dynamic visitUriTerm(UriTerm node); dynamic visitResolutionTerm(ResolutionTerm node); dynamic visitChTerm(ChTerm node); dynamic visitRemTerm(RemTerm node); dynamic visitViewportTerm(ViewportTerm node); dynamic visitFunctionTerm(FunctionTerm node); dynamic visitGroupTerm(GroupTerm node); dynamic visitItemTerm(ItemTerm node); dynamic visitIE8Term(IE8Term node); dynamic visitOperatorSlash(OperatorSlash node); dynamic visitOperatorComma(OperatorComma node); dynamic visitOperatorPlus(OperatorPlus node); dynamic visitOperatorMinus(OperatorMinus node); dynamic visitVarUsage(VarUsage node); dynamic visitExpressions(Expressions node); dynamic visitBinaryExpression(BinaryExpression node); dynamic visitUnaryExpression(UnaryExpression node); dynamic visitIdentifier(Identifier node); dynamic visitWildcard(Wildcard node); dynamic visitThisOperator(ThisOperator node); dynamic visitNegation(Negation node); dynamic visitDartStyleExpression(DartStyleExpression node); dynamic visitFontExpression(FontExpression node); dynamic visitBoxExpression(BoxExpression node); dynamic visitMarginExpression(MarginExpression node); dynamic visitBorderExpression(BorderExpression node); dynamic visitHeightExpression(HeightExpression node); dynamic visitPaddingExpression(PaddingExpression node); dynamic visitWidthExpression(WidthExpression node); } /// Base vistor class for the style sheet AST. class Visitor implements VisitorBase { /// Helper function to walk a list of nodes. void _visitNodeList(List<TreeNode> list) { // Don't use iterable otherwise the list can't grow while using Visitor. // It certainly can't have items deleted before the index being iterated // but items could be added after the index. for (var index = 0; index < list.length; index++) { list[index].visit(this); } } dynamic visitTree(StyleSheet tree) => visitStyleSheet(tree); @override dynamic visitStyleSheet(StyleSheet ss) { _visitNodeList(ss.topLevels); } @override dynamic visitNoOp(NoOp node) {} @override dynamic visitTopLevelProduction(TopLevelProduction node) {} @override dynamic visitDirective(Directive node) {} @override dynamic visitCalcTerm(CalcTerm node) { visitLiteralTerm(node); visitLiteralTerm(node.expr); } @override dynamic visitCssComment(CssComment node) {} @override dynamic visitCommentDefinition(CommentDefinition node) {} @override dynamic visitMediaExpression(MediaExpression node) { visitExpressions(node.exprs); } @override dynamic visitMediaQuery(MediaQuery node) { for (var mediaExpr in node.expressions) { visitMediaExpression(mediaExpr); } } @override dynamic visitDocumentDirective(DocumentDirective node) { _visitNodeList(node.functions); _visitNodeList(node.groupRuleBody); } @override dynamic visitSupportsDirective(SupportsDirective node) { node.condition.visit(this); _visitNodeList(node.groupRuleBody); } @override dynamic visitSupportsConditionInParens(SupportsConditionInParens node) { node.condition.visit(this); } @override dynamic visitSupportsNegation(SupportsNegation node) { node.condition.visit(this); } @override dynamic visitSupportsConjunction(SupportsConjunction node) { _visitNodeList(node.conditions); } @override dynamic visitSupportsDisjunction(SupportsDisjunction node) { _visitNodeList(node.conditions); } @override dynamic visitViewportDirective(ViewportDirective node) { node.declarations.visit(this); } @override dynamic visitMediaDirective(MediaDirective node) { _visitNodeList(node.mediaQueries); _visitNodeList(node.rules); } @override dynamic visitHostDirective(HostDirective node) { _visitNodeList(node.rules); } @override dynamic visitPageDirective(PageDirective node) { for (var declGroup in node._declsMargin) { if (declGroup is MarginGroup) { visitMarginGroup(declGroup); } else { visitDeclarationGroup(declGroup); } } } @override dynamic visitCharsetDirective(CharsetDirective node) {} @override dynamic visitImportDirective(ImportDirective node) { for (var mediaQuery in node.mediaQueries) { visitMediaQuery(mediaQuery); } } @override dynamic visitKeyFrameDirective(KeyFrameDirective node) { visitIdentifier(node.name); _visitNodeList(node._blocks); } @override dynamic visitKeyFrameBlock(KeyFrameBlock node) { visitExpressions(node._blockSelectors); visitDeclarationGroup(node._declarations); } @override dynamic visitFontFaceDirective(FontFaceDirective node) { visitDeclarationGroup(node._declarations); } @override dynamic visitStyletDirective(StyletDirective node) { _visitNodeList(node.rules); } @override dynamic visitNamespaceDirective(NamespaceDirective node) {} @override dynamic visitVarDefinitionDirective(VarDefinitionDirective node) { visitVarDefinition(node.def); } @override dynamic visitMixinRulesetDirective(MixinRulesetDirective node) { _visitNodeList(node.rulesets); } @override dynamic visitMixinDefinition(MixinDefinition node) {} @override dynamic visitMixinDeclarationDirective(MixinDeclarationDirective node) { visitDeclarationGroup(node.declarations); } @override dynamic visitIncludeDirective(IncludeDirective node) { for (var index = 0; index < node.args.length; index++) { var param = node.args[index]; _visitNodeList(param); } } @override dynamic visitContentDirective(ContentDirective node) { // TODO(terry): TBD } @override dynamic visitRuleSet(RuleSet node) { visitSelectorGroup(node._selectorGroup); visitDeclarationGroup(node._declarationGroup); } @override dynamic visitDeclarationGroup(DeclarationGroup node) { _visitNodeList(node.declarations); } @override dynamic visitMarginGroup(MarginGroup node) => visitDeclarationGroup(node); @override dynamic visitDeclaration(Declaration node) { visitIdentifier(node._property); if (node._expression != null) node._expression.visit(this); } @override dynamic visitVarDefinition(VarDefinition node) { visitIdentifier(node._property); if (node._expression != null) node._expression.visit(this); } @override dynamic visitIncludeMixinAtDeclaration(IncludeMixinAtDeclaration node) { visitIncludeDirective(node.include); } @override dynamic visitExtendDeclaration(ExtendDeclaration node) { _visitNodeList(node.selectors); } @override dynamic visitSelectorGroup(SelectorGroup node) { _visitNodeList(node.selectors); } @override dynamic visitSelector(Selector node) { _visitNodeList(node.simpleSelectorSequences); } @override dynamic visitSimpleSelectorSequence(SimpleSelectorSequence node) { node.simpleSelector.visit(this); } @override dynamic visitSimpleSelector(SimpleSelector node) => node._name.visit(this); @override dynamic visitNamespaceSelector(NamespaceSelector node) { if (node._namespace != null) node._namespace.visit(this); if (node.nameAsSimpleSelector != null) { node.nameAsSimpleSelector.visit(this); } } @override dynamic visitElementSelector(ElementSelector node) => visitSimpleSelector(node); @override dynamic visitAttributeSelector(AttributeSelector node) { visitSimpleSelector(node); } @override dynamic visitIdSelector(IdSelector node) => visitSimpleSelector(node); @override dynamic visitClassSelector(ClassSelector node) => visitSimpleSelector(node); @override dynamic visitPseudoClassSelector(PseudoClassSelector node) => visitSimpleSelector(node); @override dynamic visitPseudoElementSelector(PseudoElementSelector node) => visitSimpleSelector(node); @override dynamic visitPseudoClassFunctionSelector(PseudoClassFunctionSelector node) => visitSimpleSelector(node); @override dynamic visitPseudoElementFunctionSelector( PseudoElementFunctionSelector node) => visitSimpleSelector(node); @override dynamic visitNegationSelector(NegationSelector node) => visitSimpleSelector(node); @override dynamic visitSelectorExpression(SelectorExpression node) { _visitNodeList(node.expressions); } @override dynamic visitUnicodeRangeTerm(UnicodeRangeTerm node) {} @override dynamic visitLiteralTerm(LiteralTerm node) {} @override dynamic visitHexColorTerm(HexColorTerm node) {} @override dynamic visitNumberTerm(NumberTerm node) {} @override dynamic visitUnitTerm(UnitTerm node) {} @override dynamic visitLengthTerm(LengthTerm node) { visitUnitTerm(node); } @override dynamic visitPercentageTerm(PercentageTerm node) { visitLiteralTerm(node); } @override dynamic visitEmTerm(EmTerm node) { visitLiteralTerm(node); } @override dynamic visitExTerm(ExTerm node) { visitLiteralTerm(node); } @override dynamic visitAngleTerm(AngleTerm node) { visitUnitTerm(node); } @override dynamic visitTimeTerm(TimeTerm node) { visitUnitTerm(node); } @override dynamic visitFreqTerm(FreqTerm node) { visitUnitTerm(node); } @override dynamic visitFractionTerm(FractionTerm node) { visitLiteralTerm(node); } @override dynamic visitUriTerm(UriTerm node) { visitLiteralTerm(node); } @override dynamic visitResolutionTerm(ResolutionTerm node) { visitUnitTerm(node); } @override dynamic visitChTerm(ChTerm node) { visitUnitTerm(node); } @override dynamic visitRemTerm(RemTerm node) { visitUnitTerm(node); } @override dynamic visitViewportTerm(ViewportTerm node) { visitUnitTerm(node); } @override dynamic visitFunctionTerm(FunctionTerm node) { visitLiteralTerm(node); visitExpressions(node._params); } @override dynamic visitGroupTerm(GroupTerm node) { for (var term in node._terms) { term.visit(this); } } @override dynamic visitItemTerm(ItemTerm node) { visitNumberTerm(node); } @override dynamic visitIE8Term(IE8Term node) {} @override dynamic visitOperatorSlash(OperatorSlash node) {} @override dynamic visitOperatorComma(OperatorComma node) {} @override dynamic visitOperatorPlus(OperatorPlus node) {} @override dynamic visitOperatorMinus(OperatorMinus node) {} @override dynamic visitVarUsage(VarUsage node) { _visitNodeList(node.defaultValues); } @override dynamic visitExpressions(Expressions node) { _visitNodeList(node.expressions); } @override dynamic visitBinaryExpression(BinaryExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitUnaryExpression(UnaryExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitIdentifier(Identifier node) {} @override dynamic visitWildcard(Wildcard node) {} @override dynamic visitThisOperator(ThisOperator node) {} @override dynamic visitNegation(Negation node) {} @override dynamic visitDartStyleExpression(DartStyleExpression node) {} @override dynamic visitFontExpression(FontExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitBoxExpression(BoxExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitMarginExpression(MarginExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitBorderExpression(BorderExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitHeightExpression(HeightExpression node) { // TODO(terry): TB throw UnimplementedError(); } @override dynamic visitPaddingExpression(PaddingExpression node) { // TODO(terry): TBD throw UnimplementedError(); } @override dynamic visitWidthExpression(WidthExpression node) { // TODO(terry): TBD throw UnimplementedError(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/tree.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../visitor.dart'; ///////////////////////////////////////////////////////////////////////// // CSS specific types: ///////////////////////////////////////////////////////////////////////// class Identifier extends TreeNode { String name; Identifier(this.name, SourceSpan span) : super(span); @override Identifier clone() => Identifier(name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitIdentifier(this); @override String toString() { // Try to use the identifier's original lexeme to preserve any escape codes // as authored. The name, which may include escaped values, may no longer be // a valid identifier. return span?.text ?? name; } } class Wildcard extends TreeNode { Wildcard(SourceSpan span) : super(span); @override Wildcard clone() => Wildcard(span); @override dynamic visit(VisitorBase visitor) => visitor.visitWildcard(this); String get name => '*'; } class ThisOperator extends TreeNode { ThisOperator(SourceSpan span) : super(span); @override ThisOperator clone() => ThisOperator(span); @override dynamic visit(VisitorBase visitor) => visitor.visitThisOperator(this); String get name => '&'; } class Negation extends TreeNode { Negation(SourceSpan span) : super(span); @override Negation clone() => Negation(span); @override dynamic visit(VisitorBase visitor) => visitor.visitNegation(this); String get name => 'not'; } // calc(...) // TODO(terry): Hack to handle calc however the expressions should be fully // parsed and in the AST. class CalcTerm extends LiteralTerm { final LiteralTerm expr; CalcTerm(var value, String t, this.expr, SourceSpan span) : super(value, t, span); @override CalcTerm clone() => CalcTerm(value, text, expr.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitCalcTerm(this); @override String toString() => '$text($expr)'; } // /* .... */ class CssComment extends TreeNode { final String comment; CssComment(this.comment, SourceSpan span) : super(span); @override CssComment clone() => CssComment(comment, span); @override dynamic visit(VisitorBase visitor) => visitor.visitCssComment(this); } // CDO/CDC (Comment Definition Open <!-- and Comment Definition Close -->). class CommentDefinition extends CssComment { CommentDefinition(String comment, SourceSpan span) : super(comment, span); @override CommentDefinition clone() => CommentDefinition(comment, span); @override dynamic visit(VisitorBase visitor) => visitor.visitCommentDefinition(this); } class SelectorGroup extends TreeNode { final List<Selector> selectors; SelectorGroup(this.selectors, SourceSpan span) : super(span); @override SelectorGroup clone() => SelectorGroup(selectors, span); @override dynamic visit(VisitorBase visitor) => visitor.visitSelectorGroup(this); } class Selector extends TreeNode { final List<SimpleSelectorSequence> simpleSelectorSequences; Selector(this.simpleSelectorSequences, SourceSpan span) : super(span); void add(SimpleSelectorSequence seq) => simpleSelectorSequences.add(seq); int get length => simpleSelectorSequences.length; @override Selector clone() { var simpleSequences = simpleSelectorSequences.map((ss) => ss.clone()).toList(); return Selector(simpleSequences, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitSelector(this); } class SimpleSelectorSequence extends TreeNode { /// +, >, ~, NONE int combinator; final SimpleSelector simpleSelector; SimpleSelectorSequence(this.simpleSelector, SourceSpan span, [int combinator = TokenKind.COMBINATOR_NONE]) : combinator = combinator, super(span); bool get isCombinatorNone => combinator == TokenKind.COMBINATOR_NONE; bool get isCombinatorPlus => combinator == TokenKind.COMBINATOR_PLUS; bool get isCombinatorGreater => combinator == TokenKind.COMBINATOR_GREATER; bool get isCombinatorTilde => combinator == TokenKind.COMBINATOR_TILDE; bool get isCombinatorDescendant => combinator == TokenKind.COMBINATOR_DESCENDANT; String get _combinatorToString { switch (combinator) { case TokenKind.COMBINATOR_DESCENDANT: return ' '; case TokenKind.COMBINATOR_GREATER: return ' > '; case TokenKind.COMBINATOR_PLUS: return ' + '; case TokenKind.COMBINATOR_TILDE: return ' ~ '; default: return ''; } } @override SimpleSelectorSequence clone() => SimpleSelectorSequence(simpleSelector, span, combinator); @override dynamic visit(VisitorBase visitor) => visitor.visitSimpleSelectorSequence(this); @override String toString() => simpleSelector.name; } // All other selectors (element, #id, .class, attribute, pseudo, negation, // namespace, *) are derived from this selector. abstract class SimpleSelector extends TreeNode { final dynamic _name; // Wildcard, ThisOperator, Identifier, Negation, others? SimpleSelector(this._name, SourceSpan span) : super(span); String get name => _name.name; bool get isWildcard => _name is Wildcard; bool get isThis => _name is ThisOperator; @override dynamic visit(VisitorBase visitor) => visitor.visitSimpleSelector(this); } // element name class ElementSelector extends SimpleSelector { ElementSelector(name, SourceSpan span) : super(name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitElementSelector(this); @override ElementSelector clone() => ElementSelector(_name, span); @override String toString() => name; } // namespace|element class NamespaceSelector extends SimpleSelector { final dynamic _namespace; // null, Wildcard or Identifier NamespaceSelector(this._namespace, var name, SourceSpan span) : super(name, span); String get namespace => _namespace is Wildcard ? '*' : _namespace == null ? '' : _namespace.name; bool get isNamespaceWildcard => _namespace is Wildcard; SimpleSelector get nameAsSimpleSelector => _name; @override NamespaceSelector clone() => NamespaceSelector(_namespace, '', span); @override dynamic visit(VisitorBase visitor) => visitor.visitNamespaceSelector(this); @override String toString() => '$namespace|${nameAsSimpleSelector.name}'; } // [attr op value] class AttributeSelector extends SimpleSelector { final int _op; final dynamic value; AttributeSelector(Identifier name, this._op, this.value, SourceSpan span) : super(name, span); int get operatorKind => _op; String matchOperator() { switch (_op) { case TokenKind.EQUALS: return '='; case TokenKind.INCLUDES: return '~='; case TokenKind.DASH_MATCH: return '|='; case TokenKind.PREFIX_MATCH: return '^='; case TokenKind.SUFFIX_MATCH: return '\$='; case TokenKind.SUBSTRING_MATCH: return '*='; case TokenKind.NO_MATCH: return ''; } return null; } // Return the TokenKind for operator used by visitAttributeSelector. String matchOperatorAsTokenString() { switch (_op) { case TokenKind.EQUALS: return 'EQUALS'; case TokenKind.INCLUDES: return 'INCLUDES'; case TokenKind.DASH_MATCH: return 'DASH_MATCH'; case TokenKind.PREFIX_MATCH: return 'PREFIX_MATCH'; case TokenKind.SUFFIX_MATCH: return 'SUFFIX_MATCH'; case TokenKind.SUBSTRING_MATCH: return 'SUBSTRING_MATCH'; } return null; } String valueToString() { if (value != null) { if (value is Identifier) { return value.toString(); } else { return '"$value"'; } } else { return ''; } } @override AttributeSelector clone() => AttributeSelector(_name, _op, value, span); @override dynamic visit(VisitorBase visitor) => visitor.visitAttributeSelector(this); @override String toString() => '[$name${matchOperator()}${valueToString()}]'; } // #id class IdSelector extends SimpleSelector { IdSelector(Identifier name, SourceSpan span) : super(name, span); @override IdSelector clone() => IdSelector(_name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitIdSelector(this); @override String toString() => '#$_name'; } // .class class ClassSelector extends SimpleSelector { ClassSelector(Identifier name, SourceSpan span) : super(name, span); @override ClassSelector clone() => ClassSelector(_name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitClassSelector(this); @override String toString() => '.$_name'; } // :pseudoClass class PseudoClassSelector extends SimpleSelector { PseudoClassSelector(Identifier name, SourceSpan span) : super(name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitPseudoClassSelector(this); @override PseudoClassSelector clone() => PseudoClassSelector(_name, span); @override String toString() => ':$name'; } // ::pseudoElement class PseudoElementSelector extends SimpleSelector { // If true, this is a CSS2.1 pseudo-element with only a single ':'. final bool isLegacy; PseudoElementSelector(Identifier name, SourceSpan span, {this.isLegacy = false}) : super(name, span); @override dynamic visit(VisitorBase visitor) => visitor.visitPseudoElementSelector(this); @override PseudoElementSelector clone() => PseudoElementSelector(_name, span); @override String toString() => "${isLegacy ? ':' : '::'}$name"; } // :pseudoClassFunction(argument) class PseudoClassFunctionSelector extends PseudoClassSelector { final TreeNode _argument; // Selector, SelectorExpression PseudoClassFunctionSelector(Identifier name, this._argument, SourceSpan span) : super(name, span); @override PseudoClassFunctionSelector clone() => PseudoClassFunctionSelector(_name, _argument, span); TreeNode get argument => _argument; Selector get selector => _argument as Selector; SelectorExpression get expression => _argument as SelectorExpression; @override dynamic visit(VisitorBase visitor) => visitor.visitPseudoClassFunctionSelector(this); } // ::pseudoElementFunction(expression) class PseudoElementFunctionSelector extends PseudoElementSelector { final SelectorExpression expression; PseudoElementFunctionSelector( Identifier name, this.expression, SourceSpan span) : super(name, span); @override PseudoElementFunctionSelector clone() => PseudoElementFunctionSelector(_name, expression, span); @override dynamic visit(VisitorBase visitor) => visitor.visitPseudoElementFunctionSelector(this); } class SelectorExpression extends TreeNode { final List<Expression> expressions; SelectorExpression(this.expressions, SourceSpan span) : super(span); @override SelectorExpression clone() { return SelectorExpression(expressions.map((e) => e.clone()).toList(), span); } @override dynamic visit(VisitorBase visitor) => visitor.visitSelectorExpression(this); } // :NOT(negation_arg) class NegationSelector extends SimpleSelector { final SimpleSelector negationArg; NegationSelector(this.negationArg, SourceSpan span) : super(Negation(span), span); @override NegationSelector clone() => NegationSelector(negationArg, span); @override dynamic visit(VisitorBase visitor) => visitor.visitNegationSelector(this); } class NoOp extends TreeNode { NoOp() : super(null); @override NoOp clone() => NoOp(); @override dynamic visit(VisitorBase visitor) => visitor.visitNoOp(this); } class StyleSheet extends TreeNode { /// Contains charset, ruleset, directives (media, page, etc.), and selectors. final List<TreeNode> topLevels; StyleSheet(this.topLevels, SourceSpan span) : super(span) { for (final node in topLevels) { assert(node is TopLevelProduction || node is Directive); } } /// Selectors only in this tree. StyleSheet.selector(this.topLevels, SourceSpan span) : super(span); @override StyleSheet clone() { var clonedTopLevels = topLevels.map((e) => e.clone()).toList(); return StyleSheet(clonedTopLevels, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitStyleSheet(this); } class TopLevelProduction extends TreeNode { TopLevelProduction(SourceSpan span) : super(span); @override TopLevelProduction clone() => TopLevelProduction(span); @override dynamic visit(VisitorBase visitor) => visitor.visitTopLevelProduction(this); } class RuleSet extends TopLevelProduction { final SelectorGroup _selectorGroup; final DeclarationGroup _declarationGroup; RuleSet(this._selectorGroup, this._declarationGroup, SourceSpan span) : super(span); SelectorGroup get selectorGroup => _selectorGroup; DeclarationGroup get declarationGroup => _declarationGroup; @override RuleSet clone() { var cloneSelectorGroup = _selectorGroup.clone(); var cloneDeclarationGroup = _declarationGroup.clone(); return RuleSet(cloneSelectorGroup, cloneDeclarationGroup, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitRuleSet(this); } class Directive extends TreeNode { Directive(SourceSpan span) : super(span); bool get isBuiltIn => true; // Known CSS directive? bool get isExtension => false; // SCSS extension? @override Directive clone() => Directive(span); @override dynamic visit(VisitorBase visitor) => visitor.visitDirective(this); } class DocumentDirective extends Directive { final List<LiteralTerm> functions; final List<TreeNode> groupRuleBody; DocumentDirective(this.functions, this.groupRuleBody, SourceSpan span) : super(span); @override DocumentDirective clone() { var clonedFunctions = <LiteralTerm>[]; for (var function in functions) { clonedFunctions.add(function.clone()); } var clonedGroupRuleBody = <TreeNode>[]; for (var rule in groupRuleBody) { clonedGroupRuleBody.add(rule.clone()); } return DocumentDirective(clonedFunctions, clonedGroupRuleBody, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitDocumentDirective(this); } class SupportsDirective extends Directive { final SupportsCondition condition; final List<TreeNode> groupRuleBody; SupportsDirective(this.condition, this.groupRuleBody, SourceSpan span) : super(span); @override SupportsDirective clone() { var clonedCondition = condition.clone(); var clonedGroupRuleBody = <TreeNode>[]; for (var rule in groupRuleBody) { clonedGroupRuleBody.add(rule.clone()); } return SupportsDirective(clonedCondition, clonedGroupRuleBody, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitSupportsDirective(this); } abstract class SupportsCondition extends TreeNode { SupportsCondition(SourceSpan span) : super(span); } class SupportsConditionInParens extends SupportsCondition { /// A [Declaration] or nested [SupportsCondition]. final TreeNode condition; SupportsConditionInParens(Declaration declaration, SourceSpan span) : condition = declaration, super(span); SupportsConditionInParens.nested(SupportsCondition condition, SourceSpan span) : condition = condition, super(span); @override SupportsConditionInParens clone() => SupportsConditionInParens(condition.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitSupportsConditionInParens(this); } class SupportsNegation extends SupportsCondition { final SupportsConditionInParens condition; SupportsNegation(this.condition, SourceSpan span) : super(span); @override SupportsNegation clone() => SupportsNegation(condition.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitSupportsNegation(this); } class SupportsConjunction extends SupportsCondition { final List<SupportsConditionInParens> conditions; SupportsConjunction(this.conditions, SourceSpan span) : super(span); @override SupportsConjunction clone() { var clonedConditions = <SupportsConditionInParens>[]; for (var condition in conditions) { clonedConditions.add(condition.clone()); } return SupportsConjunction(clonedConditions, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitSupportsConjunction(this); } class SupportsDisjunction extends SupportsCondition { final List<SupportsConditionInParens> conditions; SupportsDisjunction(this.conditions, SourceSpan span) : super(span); @override SupportsDisjunction clone() { var clonedConditions = <SupportsConditionInParens>[]; for (var condition in conditions) { clonedConditions.add(condition.clone()); } return SupportsDisjunction(clonedConditions, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitSupportsDisjunction(this); } class ViewportDirective extends Directive { final String name; final DeclarationGroup declarations; ViewportDirective(this.name, this.declarations, SourceSpan span) : super(span); @override ViewportDirective clone() => ViewportDirective(name, declarations.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitViewportDirective(this); } class ImportDirective extends Directive { /// import name specified. final String import; /// Any media queries for this import. final List<MediaQuery> mediaQueries; ImportDirective(this.import, this.mediaQueries, SourceSpan span) : super(span); @override ImportDirective clone() { var cloneMediaQueries = <MediaQuery>[]; for (var mediaQuery in mediaQueries) { cloneMediaQueries.add(mediaQuery.clone()); } return ImportDirective(import, cloneMediaQueries, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitImportDirective(this); } /// MediaExpression grammar: /// /// '(' S* media_feature S* [ ':' S* expr ]? ')' S* class MediaExpression extends TreeNode { final bool andOperator; final Identifier _mediaFeature; final Expressions exprs; MediaExpression( this.andOperator, this._mediaFeature, this.exprs, SourceSpan span) : super(span); String get mediaFeature => _mediaFeature.name; @override MediaExpression clone() { var clonedExprs = exprs.clone(); return MediaExpression(andOperator, _mediaFeature, clonedExprs, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMediaExpression(this); } /// MediaQuery grammar: /// /// : [ONLY | NOT]? S* media_type S* [ AND S* media_expression ]* /// | media_expression [ AND S* media_expression ]* /// media_type /// : IDENT /// media_expression /// : '(' S* media_feature S* [ ':' S* expr ]? ')' S* /// media_feature /// : IDENT class MediaQuery extends TreeNode { /// not, only or no operator. final int _mediaUnary; final Identifier _mediaType; final List<MediaExpression> expressions; MediaQuery( this._mediaUnary, this._mediaType, this.expressions, SourceSpan span) : super(span); bool get hasMediaType => _mediaType != null; String get mediaType => _mediaType.name; bool get hasUnary => _mediaUnary != -1; String get unary => TokenKind.idToValue(TokenKind.MEDIA_OPERATORS, _mediaUnary).toUpperCase(); @override MediaQuery clone() { var cloneExpressions = <MediaExpression>[]; for (var expr in expressions) { cloneExpressions.add(expr.clone()); } return MediaQuery(_mediaUnary, _mediaType, cloneExpressions, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMediaQuery(this); } class MediaDirective extends Directive { final List<MediaQuery> mediaQueries; final List<TreeNode> rules; MediaDirective(this.mediaQueries, this.rules, SourceSpan span) : super(span); @override MediaDirective clone() { var cloneQueries = <MediaQuery>[]; for (var mediaQuery in mediaQueries) { cloneQueries.add(mediaQuery.clone()); } var cloneRules = <TreeNode>[]; for (var rule in rules) { cloneRules.add(rule.clone()); } return MediaDirective(cloneQueries, cloneRules, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMediaDirective(this); } class HostDirective extends Directive { final List<TreeNode> rules; HostDirective(this.rules, SourceSpan span) : super(span); @override HostDirective clone() { var cloneRules = <TreeNode>[]; for (var rule in rules) { cloneRules.add(rule.clone()); } return HostDirective(cloneRules, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitHostDirective(this); } class PageDirective extends Directive { final String _ident; final String _pseudoPage; final List<DeclarationGroup> _declsMargin; PageDirective( this._ident, this._pseudoPage, this._declsMargin, SourceSpan span) : super(span); @override PageDirective clone() { var cloneDeclsMargin = <DeclarationGroup>[]; for (var declMargin in _declsMargin) { cloneDeclsMargin.add(declMargin.clone()); } return PageDirective(_ident, _pseudoPage, cloneDeclsMargin, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitPageDirective(this); bool get hasIdent => _ident != null && _ident.isNotEmpty; bool get hasPseudoPage => _pseudoPage != null && _pseudoPage.isNotEmpty; } class CharsetDirective extends Directive { final String charEncoding; CharsetDirective(this.charEncoding, SourceSpan span) : super(span); @override CharsetDirective clone() => CharsetDirective(charEncoding, span); @override dynamic visit(VisitorBase visitor) => visitor.visitCharsetDirective(this); } class KeyFrameDirective extends Directive { // Either @keyframe or keyframe prefixed with @-webkit-, @-moz-, @-ms-, @-o-. final int _keyframeName; final Identifier name; final List<KeyFrameBlock> _blocks; KeyFrameDirective(this._keyframeName, this.name, SourceSpan span) : _blocks = [], super(span); void add(KeyFrameBlock block) { _blocks.add(block); } String get keyFrameName { switch (_keyframeName) { case TokenKind.DIRECTIVE_KEYFRAMES: case TokenKind.DIRECTIVE_MS_KEYFRAMES: return '@keyframes'; case TokenKind.DIRECTIVE_WEB_KIT_KEYFRAMES: return '@-webkit-keyframes'; case TokenKind.DIRECTIVE_MOZ_KEYFRAMES: return '@-moz-keyframes'; case TokenKind.DIRECTIVE_O_KEYFRAMES: return '@-o-keyframes'; } return null; } @override KeyFrameDirective clone() { var directive = KeyFrameDirective(_keyframeName, name.clone(), span); for (var block in _blocks) { directive.add(block.clone()); } return directive; } @override dynamic visit(VisitorBase visitor) => visitor.visitKeyFrameDirective(this); } class KeyFrameBlock extends Expression { final Expressions _blockSelectors; final DeclarationGroup _declarations; KeyFrameBlock(this._blockSelectors, this._declarations, SourceSpan span) : super(span); @override KeyFrameBlock clone() => KeyFrameBlock(_blockSelectors.clone(), _declarations.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitKeyFrameBlock(this); } class FontFaceDirective extends Directive { final DeclarationGroup _declarations; FontFaceDirective(this._declarations, SourceSpan span) : super(span); @override FontFaceDirective clone() => FontFaceDirective(_declarations.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitFontFaceDirective(this); } class StyletDirective extends Directive { final String dartClassName; final List<TreeNode> rules; StyletDirective(this.dartClassName, this.rules, SourceSpan span) : super(span); @override bool get isBuiltIn => false; @override bool get isExtension => true; @override StyletDirective clone() { var cloneRules = <TreeNode>[]; for (var rule in rules) { cloneRules.add(rule.clone()); } return StyletDirective(dartClassName, cloneRules, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitStyletDirective(this); } class NamespaceDirective extends Directive { /// Namespace prefix. final String _prefix; /// URI associated with this namespace. final String _uri; NamespaceDirective(this._prefix, this._uri, SourceSpan span) : super(span); @override NamespaceDirective clone() => NamespaceDirective(_prefix, _uri, span); @override dynamic visit(VisitorBase visitor) => visitor.visitNamespaceDirective(this); String get prefix => _prefix.isNotEmpty ? '$_prefix ' : ''; } /// To support Less syntax @name: expression class VarDefinitionDirective extends Directive { final VarDefinition def; VarDefinitionDirective(this.def, SourceSpan span) : super(span); @override VarDefinitionDirective clone() => VarDefinitionDirective(def.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitVarDefinitionDirective(this); } class MixinDefinition extends Directive { final String name; final List<TreeNode> definedArgs; final bool varArgs; MixinDefinition(this.name, this.definedArgs, this.varArgs, SourceSpan span) : super(span); @override MixinDefinition clone() { var cloneDefinedArgs = <TreeNode>[]; for (var definedArg in definedArgs) { cloneDefinedArgs.add(definedArg.clone()); } return MixinDefinition(name, cloneDefinedArgs, varArgs, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMixinDefinition(this); } /// Support a Sass @mixin. See http://sass-lang.com for description. class MixinRulesetDirective extends MixinDefinition { final List<TreeNode> rulesets; MixinRulesetDirective(String name, List<TreeNode> args, bool varArgs, this.rulesets, SourceSpan span) : super(name, args, varArgs, span); @override MixinRulesetDirective clone() { var clonedArgs = <VarDefinition>[]; for (var arg in definedArgs) { clonedArgs.add(arg.clone()); } var clonedRulesets = <TreeNode>[]; for (var ruleset in rulesets) { clonedRulesets.add(ruleset.clone()); } return MixinRulesetDirective( name, clonedArgs, varArgs, clonedRulesets, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMixinRulesetDirective(this); } class MixinDeclarationDirective extends MixinDefinition { final DeclarationGroup declarations; MixinDeclarationDirective(String name, List<TreeNode> args, bool varArgs, this.declarations, SourceSpan span) : super(name, args, varArgs, span); @override MixinDeclarationDirective clone() { var clonedArgs = <TreeNode>[]; for (var arg in definedArgs) { clonedArgs.add(arg.clone()); } return MixinDeclarationDirective( name, clonedArgs, varArgs, declarations.clone(), span); } @override dynamic visit(VisitorBase visitor) => visitor.visitMixinDeclarationDirective(this); } /// To support consuming a Sass mixin @include. class IncludeDirective extends Directive { final String name; final List<List<Expression>> args; IncludeDirective(this.name, this.args, SourceSpan span) : super(span); @override IncludeDirective clone() { var cloneArgs = <List<Expression>>[]; for (var arg in args) { cloneArgs.add(arg.map((term) => term.clone()).toList()); } return IncludeDirective(name, cloneArgs, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitIncludeDirective(this); } /// To support Sass @content. class ContentDirective extends Directive { ContentDirective(SourceSpan span) : super(span); @override dynamic visit(VisitorBase visitor) => visitor.visitContentDirective(this); } class Declaration extends TreeNode { final Identifier _property; final Expression _expression; /// Style exposed to Dart. DartStyleExpression dartStyle; final bool important; /// IE CSS hacks that can only be read by a particular IE version. /// 7 implies IE 7 or older property (e.g., `*background: blue;`) /// /// * Note: IE 8 or older property (e.g., `background: green\9;`) is handled /// by IE8Term in declaration expression handling. /// * Note: IE 6 only property with a leading underscore is a valid IDENT /// since an ident can start with underscore (e.g., `_background: red;`) final bool isIE7; Declaration(this._property, this._expression, this.dartStyle, SourceSpan span, {this.important = false, bool ie7 = false}) : isIE7 = ie7, super(span); String get property => isIE7 ? '*${_property.name}' : _property.name; Expression get expression => _expression; bool get hasDartStyle => dartStyle != null; @override Declaration clone() => Declaration(_property.clone(), _expression.clone(), dartStyle, span, important: important); @override dynamic visit(VisitorBase visitor) => visitor.visitDeclaration(this); } // TODO(terry): Consider 2 kinds of VarDefinitions static at top-level and // dynamic when in a declaration. Currently, Less syntax // '@foo: expression' and 'var-foo: expression' in a declaration // are statically resolved. Better solution, if @foo or var-foo // are top-level are then statically resolved and var-foo in a // declaration group (surrounded by a selector) would be dynamic. class VarDefinition extends Declaration { bool badUsage = false; VarDefinition(Identifier definedName, Expression expr, SourceSpan span) : super(definedName, expr, null, span); String get definedName => _property.name; @override VarDefinition clone() => VarDefinition( _property.clone(), expression != null ? expression.clone() : null, span); @override dynamic visit(VisitorBase visitor) => visitor.visitVarDefinition(this); } /// Node for usage of @include mixin[(args,...)] found in a declaration group /// instead of at a ruleset (toplevel) e.g., /// /// div { /// @include mixin1; /// } class IncludeMixinAtDeclaration extends Declaration { final IncludeDirective include; IncludeMixinAtDeclaration(this.include, SourceSpan span) : super(null, null, null, span); @override IncludeMixinAtDeclaration clone() => IncludeMixinAtDeclaration(include.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitIncludeMixinAtDeclaration(this); } class ExtendDeclaration extends Declaration { final List<TreeNode> selectors; ExtendDeclaration(this.selectors, SourceSpan span) : super(null, null, null, span); @override ExtendDeclaration clone() { var newSelector = selectors.map((s) => s.clone()).toList(); return ExtendDeclaration(newSelector, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitExtendDeclaration(this); } class DeclarationGroup extends TreeNode { /// Can be either Declaration or RuleSet (if nested selector). final List<TreeNode> declarations; DeclarationGroup(this.declarations, SourceSpan span) : super(span); @override DeclarationGroup clone() { var clonedDecls = declarations.map((d) => d.clone()).toList(); return DeclarationGroup(clonedDecls, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitDeclarationGroup(this); } class MarginGroup extends DeclarationGroup { final int margin_sym; // TokenType for for @margin sym. MarginGroup(this.margin_sym, List<TreeNode> decls, SourceSpan span) : super(decls, span); @override MarginGroup clone() => MarginGroup(margin_sym, super.clone().declarations, span); @override dynamic visit(VisitorBase visitor) => visitor.visitMarginGroup(this); } class VarUsage extends Expression { final String name; final List<Expression> defaultValues; VarUsage(this.name, this.defaultValues, SourceSpan span) : super(span); @override VarUsage clone() { var clonedValues = <Expression>[]; for (var expr in defaultValues) { clonedValues.add(expr.clone()); } return VarUsage(name, clonedValues, span); } @override dynamic visit(VisitorBase visitor) => visitor.visitVarUsage(this); } class OperatorSlash extends Expression { OperatorSlash(SourceSpan span) : super(span); @override OperatorSlash clone() => OperatorSlash(span); @override dynamic visit(VisitorBase visitor) => visitor.visitOperatorSlash(this); } class OperatorComma extends Expression { OperatorComma(SourceSpan span) : super(span); @override OperatorComma clone() => OperatorComma(span); @override dynamic visit(VisitorBase visitor) => visitor.visitOperatorComma(this); } class OperatorPlus extends Expression { OperatorPlus(SourceSpan span) : super(span); @override OperatorPlus clone() => OperatorPlus(span); @override dynamic visit(VisitorBase visitor) => visitor.visitOperatorPlus(this); } class OperatorMinus extends Expression { OperatorMinus(SourceSpan span) : super(span); @override OperatorMinus clone() => OperatorMinus(span); @override dynamic visit(VisitorBase visitor) => visitor.visitOperatorMinus(this); } class UnicodeRangeTerm extends Expression { final String first; final String second; UnicodeRangeTerm(this.first, this.second, SourceSpan span) : super(span); bool get hasSecond => second != null; @override UnicodeRangeTerm clone() => UnicodeRangeTerm(first, second, span); @override dynamic visit(VisitorBase visitor) => visitor.visitUnicodeRangeTerm(this); } class LiteralTerm extends Expression { // TODO(terry): value and text fields can be made final once all CSS resources // are copied/symlink'd in the build tool and UriVisitor in // web_ui is removed. dynamic value; String text; LiteralTerm(this.value, this.text, SourceSpan span) : super(span); @override LiteralTerm clone() => LiteralTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitLiteralTerm(this); } class NumberTerm extends LiteralTerm { NumberTerm(value, String t, SourceSpan span) : super(value, t, span); @override NumberTerm clone() => NumberTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitNumberTerm(this); } class UnitTerm extends LiteralTerm { final int unit; UnitTerm(value, String t, SourceSpan span, this.unit) : super(value, t, span); @override UnitTerm clone() => UnitTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitUnitTerm(this); String unitToString() => TokenKind.unitToString(unit); @override String toString() => '$text${unitToString()}'; } class LengthTerm extends UnitTerm { LengthTerm(value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(this.unit == TokenKind.UNIT_LENGTH_PX || this.unit == TokenKind.UNIT_LENGTH_CM || this.unit == TokenKind.UNIT_LENGTH_MM || this.unit == TokenKind.UNIT_LENGTH_IN || this.unit == TokenKind.UNIT_LENGTH_PT || this.unit == TokenKind.UNIT_LENGTH_PC); } @override LengthTerm clone() => LengthTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitLengthTerm(this); } class PercentageTerm extends LiteralTerm { PercentageTerm(value, String t, SourceSpan span) : super(value, t, span); @override PercentageTerm clone() => PercentageTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitPercentageTerm(this); } class EmTerm extends LiteralTerm { EmTerm(value, String t, SourceSpan span) : super(value, t, span); @override EmTerm clone() => EmTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitEmTerm(this); } class ExTerm extends LiteralTerm { ExTerm(value, String t, SourceSpan span) : super(value, t, span); @override ExTerm clone() => ExTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitExTerm(this); } class AngleTerm extends UnitTerm { AngleTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(this.unit == TokenKind.UNIT_ANGLE_DEG || this.unit == TokenKind.UNIT_ANGLE_RAD || this.unit == TokenKind.UNIT_ANGLE_GRAD || this.unit == TokenKind.UNIT_ANGLE_TURN); } @override AngleTerm clone() => AngleTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitAngleTerm(this); } class TimeTerm extends UnitTerm { TimeTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(this.unit == TokenKind.UNIT_ANGLE_DEG || this.unit == TokenKind.UNIT_TIME_MS || this.unit == TokenKind.UNIT_TIME_S); } @override TimeTerm clone() => TimeTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitTimeTerm(this); } class FreqTerm extends UnitTerm { FreqTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(unit == TokenKind.UNIT_FREQ_HZ || unit == TokenKind.UNIT_FREQ_KHZ); } @override FreqTerm clone() => FreqTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitFreqTerm(this); } class FractionTerm extends LiteralTerm { FractionTerm(var value, String t, SourceSpan span) : super(value, t, span); @override FractionTerm clone() => FractionTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitFractionTerm(this); } class UriTerm extends LiteralTerm { UriTerm(String value, SourceSpan span) : super(value, value, span); @override UriTerm clone() => UriTerm(value, span); @override dynamic visit(VisitorBase visitor) => visitor.visitUriTerm(this); } class ResolutionTerm extends UnitTerm { ResolutionTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(unit == TokenKind.UNIT_RESOLUTION_DPI || unit == TokenKind.UNIT_RESOLUTION_DPCM || unit == TokenKind.UNIT_RESOLUTION_DPPX); } @override ResolutionTerm clone() => ResolutionTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitResolutionTerm(this); } class ChTerm extends UnitTerm { ChTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(unit == TokenKind.UNIT_CH); } @override ChTerm clone() => ChTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitChTerm(this); } class RemTerm extends UnitTerm { RemTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(unit == TokenKind.UNIT_REM); } @override RemTerm clone() => RemTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitRemTerm(this); } class ViewportTerm extends UnitTerm { ViewportTerm(var value, String t, SourceSpan span, [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { assert(unit == TokenKind.UNIT_VIEWPORT_VW || unit == TokenKind.UNIT_VIEWPORT_VH || unit == TokenKind.UNIT_VIEWPORT_VMIN || unit == TokenKind.UNIT_VIEWPORT_VMAX); } @override ViewportTerm clone() => ViewportTerm(value, text, span, unit); @override dynamic visit(VisitorBase visitor) => visitor.visitViewportTerm(this); } /// Type to signal a bad hex value for HexColorTerm.value. class BAD_HEX_VALUE {} class HexColorTerm extends LiteralTerm { HexColorTerm(var value, String t, SourceSpan span) : super(value, t, span); @override HexColorTerm clone() => HexColorTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitHexColorTerm(this); } class FunctionTerm extends LiteralTerm { final Expressions _params; FunctionTerm(var value, String t, this._params, SourceSpan span) : super(value, t, span); @override FunctionTerm clone() => FunctionTerm(value, text, _params.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitFunctionTerm(this); } /// A "\9" was encountered at the end of the expression and before a semi-colon. /// This is an IE trick to ignore a property or value except by IE 8 and older /// browsers. class IE8Term extends LiteralTerm { IE8Term(SourceSpan span) : super('\\9', '\\9', span); @override IE8Term clone() => IE8Term(span); @override dynamic visit(VisitorBase visitor) => visitor.visitIE8Term(this); } class GroupTerm extends Expression { final List<LiteralTerm> _terms; GroupTerm(SourceSpan span) : _terms = [], super(span); void add(LiteralTerm term) { _terms.add(term); } @override GroupTerm clone() => GroupTerm(span); @override dynamic visit(VisitorBase visitor) => visitor.visitGroupTerm(this); } class ItemTerm extends NumberTerm { ItemTerm(dynamic value, String t, SourceSpan span) : super(value, t, span); @override ItemTerm clone() => ItemTerm(value, text, span); @override dynamic visit(VisitorBase visitor) => visitor.visitItemTerm(this); } class Expressions extends Expression { final List<Expression> expressions = []; Expressions(SourceSpan span) : super(span); void add(Expression expression) { expressions.add(expression); } @override Expressions clone() { var clonedExprs = Expressions(span); for (var expr in expressions) { clonedExprs.add(expr.clone()); } return clonedExprs; } @override dynamic visit(VisitorBase visitor) => visitor.visitExpressions(this); } class BinaryExpression extends Expression { final Token op; final Expression x; final Expression y; BinaryExpression(this.op, this.x, this.y, SourceSpan span) : super(span); @override BinaryExpression clone() => BinaryExpression(op, x.clone(), y.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitBinaryExpression(this); } class UnaryExpression extends Expression { final Token op; final Expression self; UnaryExpression(this.op, this.self, SourceSpan span) : super(span); @override UnaryExpression clone() => UnaryExpression(op, self.clone(), span); @override dynamic visit(VisitorBase visitor) => visitor.visitUnaryExpression(this); } abstract class DartStyleExpression extends TreeNode { static const int unknownType = 0; static const int fontStyle = 1; static const int marginStyle = 2; static const int borderStyle = 3; static const int paddingStyle = 4; static const int heightStyle = 5; static const int widthStyle = 6; final int _styleType; int priority; DartStyleExpression(this._styleType, SourceSpan span) : super(span); // Merges give 2 DartStyleExpression (or derived from DartStyleExpression, // e.g., FontExpression, etc.) will merge if the two expressions are of the // same property name (implies same exact type e.g, FontExpression). DartStyleExpression merged(DartStyleExpression newDartExpr); bool get isUnknown => _styleType == 0 || _styleType == null; bool get isFont => _styleType == fontStyle; bool get isMargin => _styleType == marginStyle; bool get isBorder => _styleType == borderStyle; bool get isPadding => _styleType == paddingStyle; bool get isHeight => _styleType == heightStyle; bool get isWidth => _styleType == widthStyle; bool get isBoxExpression => isMargin || isBorder || isPadding; bool isSame(DartStyleExpression other) => _styleType == other._styleType; @override dynamic visit(VisitorBase visitor) => visitor.visitDartStyleExpression(this); } class FontExpression extends DartStyleExpression { final Font font; // font-style font-variant font-weight font-size/line-height font-family // TODO(terry): Only px/pt for now need to handle all possible units to // support calc expressions on units. FontExpression(SourceSpan span, {Object /* LengthTerm | num */ size, List<String> family, int weight, String style, String variant, LineHeight lineHeight}) : font = Font( size: size is LengthTerm ? size.value : size as num, family: family, weight: weight, style: style, variant: variant, lineHeight: lineHeight), super(DartStyleExpression.fontStyle, span); @override FontExpression merged(DartStyleExpression newFontExpr) { if (newFontExpr is FontExpression && isFont && newFontExpr.isFont) { return FontExpression.merge(this, newFontExpr); } return null; } /// Merge the two FontExpression and return the result. factory FontExpression.merge(FontExpression x, FontExpression y) { return FontExpression._merge(x, y, y.span); } FontExpression._merge(FontExpression x, FontExpression y, SourceSpan span) : font = Font.merge(x.font, y.font), super(DartStyleExpression.fontStyle, span); @override FontExpression clone() => FontExpression(span, size: font.size, family: font.family, weight: font.weight, style: font.style, variant: font.variant, lineHeight: font.lineHeight); @override dynamic visit(VisitorBase visitor) => visitor.visitFontExpression(this); } abstract class BoxExpression extends DartStyleExpression { final BoxEdge box; BoxExpression(int styleType, SourceSpan span, this.box) : super(styleType, span); @override dynamic visit(VisitorBase visitor) => visitor.visitBoxExpression(this); String get formattedBoxEdge { if (box.top == box.left && box.top == box.bottom && box.top == box.right) { return '.uniform(${box.top})'; } else { var left = box.left ?? 0; var top = box.top ?? 0; var right = box.right ?? 0; var bottom = box.bottom ?? 0; return '.clockwiseFromTop($top,$right,$bottom,$left)'; } } } class MarginExpression extends BoxExpression { // TODO(terry): Does auto for margin need to be exposed to Dart UI framework? /// Margin expression ripped apart. MarginExpression(SourceSpan span, {num top, num right, num bottom, num left}) : super(DartStyleExpression.marginStyle, span, BoxEdge(left, top, right, bottom)); MarginExpression.boxEdge(SourceSpan span, BoxEdge box) : super(DartStyleExpression.marginStyle, span, box); @override MarginExpression merged(DartStyleExpression newMarginExpr) { if (newMarginExpr is MarginExpression && isMargin && newMarginExpr.isMargin) { return MarginExpression.merge(this, newMarginExpr); } return null; } /// Merge the two MarginExpressions and return the result. factory MarginExpression.merge(MarginExpression x, MarginExpression y) { return MarginExpression._merge(x, y, y.span); } MarginExpression._merge( MarginExpression x, MarginExpression y, SourceSpan span) : super(x._styleType, span, BoxEdge.merge(x.box, y.box)); @override MarginExpression clone() => MarginExpression(span, top: box.top, right: box.right, bottom: box.bottom, left: box.left); @override dynamic visit(VisitorBase visitor) => visitor.visitMarginExpression(this); } class BorderExpression extends BoxExpression { /// Border expression ripped apart. BorderExpression(SourceSpan span, {num top, num right, num bottom, num left}) : super(DartStyleExpression.borderStyle, span, BoxEdge(left, top, right, bottom)); BorderExpression.boxEdge(SourceSpan span, BoxEdge box) : super(DartStyleExpression.borderStyle, span, box); @override BorderExpression merged(DartStyleExpression newBorderExpr) { if (newBorderExpr is BorderExpression && isBorder && newBorderExpr.isBorder) { return BorderExpression.merge(this, newBorderExpr); } return null; } /// Merge the two BorderExpression and return the result. factory BorderExpression.merge(BorderExpression x, BorderExpression y) { return BorderExpression._merge(x, y, y.span); } BorderExpression._merge( BorderExpression x, BorderExpression y, SourceSpan span) : super( DartStyleExpression.borderStyle, span, BoxEdge.merge(x.box, y.box)); @override BorderExpression clone() => BorderExpression(span, top: box.top, right: box.right, bottom: box.bottom, left: box.left); @override dynamic visit(VisitorBase visitor) => visitor.visitBorderExpression(this); } class HeightExpression extends DartStyleExpression { final dynamic height; HeightExpression(SourceSpan span, this.height) : super(DartStyleExpression.heightStyle, span); @override HeightExpression merged(DartStyleExpression newHeightExpr) { if (newHeightExpr is DartStyleExpression && isHeight && newHeightExpr.isHeight) { return newHeightExpr; } return null; } @override HeightExpression clone() => HeightExpression(span, height); @override dynamic visit(VisitorBase visitor) => visitor.visitHeightExpression(this); } class WidthExpression extends DartStyleExpression { final dynamic width; WidthExpression(SourceSpan span, this.width) : super(DartStyleExpression.widthStyle, span); @override WidthExpression merged(DartStyleExpression newWidthExpr) { if (newWidthExpr is WidthExpression && isWidth && newWidthExpr.isWidth) { return newWidthExpr; } return null; } @override WidthExpression clone() => WidthExpression(span, width); @override dynamic visit(VisitorBase visitor) => visitor.visitWidthExpression(this); } class PaddingExpression extends BoxExpression { /// Padding expression ripped apart. PaddingExpression(SourceSpan span, {num top, num right, num bottom, num left}) : super(DartStyleExpression.paddingStyle, span, BoxEdge(left, top, right, bottom)); PaddingExpression.boxEdge(SourceSpan span, BoxEdge box) : super(DartStyleExpression.paddingStyle, span, box); @override PaddingExpression merged(DartStyleExpression newPaddingExpr) { if (newPaddingExpr is PaddingExpression && isPadding && newPaddingExpr.isPadding) { return PaddingExpression.merge(this, newPaddingExpr); } return null; } /// Merge the two PaddingExpression and return the result. factory PaddingExpression.merge(PaddingExpression x, PaddingExpression y) { return PaddingExpression._merge(x, y, y.span); } PaddingExpression._merge( PaddingExpression x, PaddingExpression y, SourceSpan span) : super(DartStyleExpression.paddingStyle, span, BoxEdge.merge(x.box, y.box)); @override PaddingExpression clone() => PaddingExpression(span, top: box.top, right: box.right, bottom: box.bottom, left: box.left); @override dynamic visit(VisitorBase visitor) => visitor.visitPaddingExpression(this); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/tokenizer.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../parser.dart'; class Tokenizer extends TokenizerBase { /// U+ prefix for unicode characters. final UNICODE_U = 'U'.codeUnitAt(0); final UNICODE_LOWER_U = 'u'.codeUnitAt(0); final UNICODE_PLUS = '+'.codeUnitAt(0); final QUESTION_MARK = '?'.codeUnitAt(0); /// CDATA keyword. final List<int> CDATA_NAME = 'CDATA'.codeUnits; Tokenizer(SourceFile file, String text, bool skipWhitespace, [int index = 0]) : super(file, text, skipWhitespace, index); @override Token next({bool unicodeRange = false}) { // keep track of our starting position _startIndex = _index; int ch; ch = _nextChar(); switch (ch) { case TokenChar.NEWLINE: case TokenChar.RETURN: case TokenChar.SPACE: case TokenChar.TAB: return finishWhitespace(); case TokenChar.END_OF_FILE: return _finishToken(TokenKind.END_OF_FILE); case TokenChar.AT: var peekCh = _peekChar(); if (TokenizerHelpers.isIdentifierStart(peekCh)) { var oldIndex = _index; var oldStartIndex = _startIndex; _startIndex = _index; ch = _nextChar(); finishIdentifier(); // Is it a directive? var tokId = TokenKind.matchDirectives( _text, _startIndex, _index - _startIndex); if (tokId == -1) { // No, is it a margin directive? tokId = TokenKind.matchMarginDirectives( _text, _startIndex, _index - _startIndex); } if (tokId != -1) { return _finishToken(tokId); } else { // Didn't find a CSS directive or margin directive so the @name is // probably the Less definition '@name: value_variable_definition'. _startIndex = oldStartIndex; _index = oldIndex; } } return _finishToken(TokenKind.AT); case TokenChar.DOT: var start = _startIndex; // Start where the dot started. if (maybeEatDigit()) { // looks like a number dot followed by digit(s). var number = finishNumber(); if (number.kind == TokenKind.INTEGER) { // It's a number but it's preceeded by a dot, so make it a double. _startIndex = start; return _finishToken(TokenKind.DOUBLE); } else { // Don't allow dot followed by a double (e.g, '..1'). return _errorToken(); } } // It's really a dot. return _finishToken(TokenKind.DOT); case TokenChar.LPAREN: return _finishToken(TokenKind.LPAREN); case TokenChar.RPAREN: return _finishToken(TokenKind.RPAREN); case TokenChar.LBRACE: return _finishToken(TokenKind.LBRACE); case TokenChar.RBRACE: return _finishToken(TokenKind.RBRACE); case TokenChar.LBRACK: return _finishToken(TokenKind.LBRACK); case TokenChar.RBRACK: if (_maybeEatChar(TokenChar.RBRACK) && _maybeEatChar(TokenChar.GREATER)) { // ]]> return next(); } return _finishToken(TokenKind.RBRACK); case TokenChar.HASH: return _finishToken(TokenKind.HASH); case TokenChar.PLUS: if (_nextCharsAreNumber(ch)) return finishNumber(); return _finishToken(TokenKind.PLUS); case TokenChar.MINUS: if (inSelectorExpression || unicodeRange) { // If parsing in pseudo function expression then minus is an operator // not part of identifier e.g., interval value range (e.g. U+400-4ff) // or minus operator in selector expression. return _finishToken(TokenKind.MINUS); } else if (_nextCharsAreNumber(ch)) { return finishNumber(); } else if (TokenizerHelpers.isIdentifierStart(ch)) { return finishIdentifier(); } return _finishToken(TokenKind.MINUS); case TokenChar.GREATER: return _finishToken(TokenKind.GREATER); case TokenChar.TILDE: if (_maybeEatChar(TokenChar.EQUALS)) { return _finishToken(TokenKind.INCLUDES); // ~= } return _finishToken(TokenKind.TILDE); case TokenChar.ASTERISK: if (_maybeEatChar(TokenChar.EQUALS)) { return _finishToken(TokenKind.SUBSTRING_MATCH); // *= } return _finishToken(TokenKind.ASTERISK); case TokenChar.AMPERSAND: return _finishToken(TokenKind.AMPERSAND); case TokenChar.NAMESPACE: if (_maybeEatChar(TokenChar.EQUALS)) { return _finishToken(TokenKind.DASH_MATCH); // |= } return _finishToken(TokenKind.NAMESPACE); case TokenChar.COLON: return _finishToken(TokenKind.COLON); case TokenChar.COMMA: return _finishToken(TokenKind.COMMA); case TokenChar.SEMICOLON: return _finishToken(TokenKind.SEMICOLON); case TokenChar.PERCENT: return _finishToken(TokenKind.PERCENT); case TokenChar.SINGLE_QUOTE: return _finishToken(TokenKind.SINGLE_QUOTE); case TokenChar.DOUBLE_QUOTE: return _finishToken(TokenKind.DOUBLE_QUOTE); case TokenChar.SLASH: if (_maybeEatChar(TokenChar.ASTERISK)) return finishMultiLineComment(); return _finishToken(TokenKind.SLASH); case TokenChar.LESS: // <!-- if (_maybeEatChar(TokenChar.BANG)) { if (_maybeEatChar(TokenChar.MINUS) && _maybeEatChar(TokenChar.MINUS)) { return finishHtmlComment(); } else if (_maybeEatChar(TokenChar.LBRACK) && _maybeEatChar(CDATA_NAME[0]) && _maybeEatChar(CDATA_NAME[1]) && _maybeEatChar(CDATA_NAME[2]) && _maybeEatChar(CDATA_NAME[3]) && _maybeEatChar(CDATA_NAME[4]) && _maybeEatChar(TokenChar.LBRACK)) { // <![CDATA[ return next(); } } return _finishToken(TokenKind.LESS); case TokenChar.EQUALS: return _finishToken(TokenKind.EQUALS); case TokenChar.CARET: if (_maybeEatChar(TokenChar.EQUALS)) { return _finishToken(TokenKind.PREFIX_MATCH); // ^= } return _finishToken(TokenKind.CARET); case TokenChar.DOLLAR: if (_maybeEatChar(TokenChar.EQUALS)) { return _finishToken(TokenKind.SUFFIX_MATCH); // $= } return _finishToken(TokenKind.DOLLAR); case TokenChar.BANG: var tok = finishIdentifier(); return (tok == null) ? _finishToken(TokenKind.BANG) : tok; default: // TODO(jmesserly): this is used for IE8 detection; I'm not sure it's // appropriate outside of a few specific places; certainly shouldn't // be parsed in selectors. if (!inSelector && ch == TokenChar.BACKSLASH) { return _finishToken(TokenKind.BACKSLASH); } if (unicodeRange) { // Three types of unicode ranges: // - single code point (e.g. U+416) // - interval value range (e.g. U+400-4ff) // - range where trailing ‘?’ characters imply ‘any digit value’ // (e.g. U+4??) if (maybeEatHexDigit()) { var t = finishHexNumber(); // Any question marks then it's a HEX_RANGE not HEX_NUMBER. if (maybeEatQuestionMark()) finishUnicodeRange(); return t; } else if (maybeEatQuestionMark()) { // HEX_RANGE U+N??? return finishUnicodeRange(); } else { return _errorToken(); } } else if (_inString && (ch == UNICODE_U || ch == UNICODE_LOWER_U) && (_peekChar() == UNICODE_PLUS)) { // `_inString` is misleading. We actually DON'T want to enter this // block while tokenizing a string, but the parser sets this value to // false while it IS consuming tokens within a string. // // Unicode range: U+uNumber[-U+uNumber] // uNumber = 0..10FFFF _nextChar(); // Skip + _startIndex = _index; // Starts at the number return _finishToken(TokenKind.UNICODE_RANGE); } else if (varDef(ch)) { return _finishToken(TokenKind.VAR_DEFINITION); } else if (varUsage(ch)) { return _finishToken(TokenKind.VAR_USAGE); } else if (TokenizerHelpers.isIdentifierStart(ch)) { return finishIdentifier(); } else if (TokenizerHelpers.isDigit(ch)) { return finishNumber(); } return _errorToken(); } } bool varDef(int ch) { return ch == 'v'.codeUnitAt(0) && _maybeEatChar('a'.codeUnitAt(0)) && _maybeEatChar('r'.codeUnitAt(0)) && _maybeEatChar('-'.codeUnitAt(0)); } bool varUsage(int ch) { return ch == 'v'.codeUnitAt(0) && _maybeEatChar('a'.codeUnitAt(0)) && _maybeEatChar('r'.codeUnitAt(0)) && (_peekChar() == '-'.codeUnitAt(0)); } @override Token _errorToken([String message]) { return _finishToken(TokenKind.ERROR); } @override int getIdentifierKind() { // Is the identifier a unit type? var tokId = -1; // Don't match units in selectors or selector expressions. if (!inSelectorExpression && !inSelector) { tokId = TokenKind.matchUnits(_text, _startIndex, _index - _startIndex); } if (tokId == -1) { tokId = (_text.substring(_startIndex, _index) == '!important') ? TokenKind.IMPORTANT : -1; } return tokId >= 0 ? tokId : TokenKind.IDENTIFIER; } Token finishIdentifier() { // If we encounter an escape sequence, remember it so we can post-process // to unescape. var chars = <int>[]; // backup so we can start with the first character var validateFrom = _index; _index = _startIndex; while (_index < _text.length) { var ch = _text.codeUnitAt(_index); // If the previous character was "\" we need to escape. T // http://www.w3.org/TR/CSS21/syndata.html#characters // if followed by hexadecimal digits, create the appropriate character. // otherwise, include the character in the identifier and don't treat it // specially. if (ch == 92 /*\*/ && _inString) { var startHex = ++_index; eatHexDigits(startHex + 6); if (_index != startHex) { // Parse the hex digits and add that character. chars.add(int.parse('0x' + _text.substring(startHex, _index))); if (_index == _text.length) break; // if we stopped the hex because of a whitespace char, skip it ch = _text.codeUnitAt(_index); if (_index - startHex != 6 && (ch == TokenChar.SPACE || ch == TokenChar.TAB || ch == TokenChar.RETURN || ch == TokenChar.NEWLINE)) { _index++; } } else { // not a digit, just add the next character literally if (_index == _text.length) break; chars.add(_text.codeUnitAt(_index++)); } } else if (_index < validateFrom || (inSelectorExpression ? TokenizerHelpers.isIdentifierPartExpr(ch) : TokenizerHelpers.isIdentifierPart(ch))) { chars.add(ch); _index++; } else { // Not an identifier or escaped character. break; } } var span = _file.span(_startIndex, _index); var text = String.fromCharCodes(chars); return IdentifierToken(text, getIdentifierKind(), span); } @override Token finishNumber() { eatDigits(); if (_peekChar() == 46 /*.*/) { // Handle the case of 1.toString(). _nextChar(); if (TokenizerHelpers.isDigit(_peekChar())) { eatDigits(); return _finishToken(TokenKind.DOUBLE); } else { _index -= 1; } } return _finishToken(TokenKind.INTEGER); } bool maybeEatDigit() { if (_index < _text.length && TokenizerHelpers.isDigit(_text.codeUnitAt(_index))) { _index += 1; return true; } return false; } Token finishHexNumber() { eatHexDigits(_text.length); return _finishToken(TokenKind.HEX_INTEGER); } void eatHexDigits(int end) { end = math.min(end, _text.length); while (_index < end) { if (TokenizerHelpers.isHexDigit(_text.codeUnitAt(_index))) { _index += 1; } else { return; } } } bool maybeEatHexDigit() { if (_index < _text.length && TokenizerHelpers.isHexDigit(_text.codeUnitAt(_index))) { _index += 1; return true; } return false; } bool maybeEatQuestionMark() { if (_index < _text.length && _text.codeUnitAt(_index) == QUESTION_MARK) { _index += 1; return true; } return false; } void eatQuestionMarks() { while (_index < _text.length) { if (_text.codeUnitAt(_index) == QUESTION_MARK) { _index += 1; } else { return; } } } Token finishUnicodeRange() { eatQuestionMarks(); return _finishToken(TokenKind.HEX_RANGE); } Token finishHtmlComment() { while (true) { var ch = _nextChar(); if (ch == 0) { return _finishToken(TokenKind.INCOMPLETE_COMMENT); } else if (ch == TokenChar.MINUS) { /* Check if close part of Comment Definition --> (CDC). */ if (_maybeEatChar(TokenChar.MINUS)) { if (_maybeEatChar(TokenChar.GREATER)) { if (_inString) { return next(); } else { return _finishToken(TokenKind.HTML_COMMENT); } } } } } } @override Token finishMultiLineComment() { while (true) { var ch = _nextChar(); if (ch == 0) { return _finishToken(TokenKind.INCOMPLETE_COMMENT); } else if (ch == 42 /*'*'*/) { if (_maybeEatChar(47 /*'/'*/)) { if (_inString) { return next(); } else { return _finishToken(TokenKind.COMMENT); } } } } } } /// Static helper methods. class TokenizerHelpers { static bool isIdentifierStart(int c) { return isIdentifierStartExpr(c) || c == 45 /*-*/; } static bool isDigit(int c) { return (c >= 48 /*0*/ && c <= 57 /*9*/); } static bool isHexDigit(int c) { return (isDigit(c) || (c >= 97 /*a*/ && c <= 102 /*f*/) || (c >= 65 /*A*/ && c <= 70 /*F*/)); } static bool isIdentifierPart(int c) { return isIdentifierPartExpr(c) || c == 45 /*-*/; } /// Pseudo function expressions identifiers can't have a minus sign. static bool isIdentifierStartExpr(int c) { return ((c >= 97 /*a*/ && c <= 122 /*z*/) || (c >= 65 /*A*/ && c <= 90 /*Z*/) || // Note: Unicode 10646 chars U+00A0 or higher are allowed, see: // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier // http://www.w3.org/TR/CSS21/syndata.html#characters // Also, escaped character should be allowed. c == 95 /*_*/ || c >= 0xA0 || c == 92 /*\*/); } /// Pseudo function expressions identifiers can't have a minus sign. static bool isIdentifierPartExpr(int c) { return (isIdentifierStartExpr(c) || isDigit(c)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/preprocessor_options.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. class PreprocessorOptions { /// Generate polyfill code (e.g., var, etc.) final bool polyfill; /// Report warnings as errors. final bool warningsAsErrors; /// Throw an exception on warnings (not used by command line tool). final bool throwOnWarnings; /// Throw an exception on errors (not used by command line tool). final bool throwOnErrors; /// True to show informational messages. The `--verbose` flag. final bool verbose; /// True to show warning messages for bad CSS. The '--checked' flag. final bool checked; // TODO(terry): Add mixin support and nested rules. /// Subset of Less commands enabled; disable with '--no-less'. /// Less syntax supported: /// - @name at root level statically defines variables resolved at compilation /// time. Essentially a directive e.g., @var-name. final bool lessSupport; /// Whether to use colors to print messages on the terminal. final bool useColors; /// File to process by the compiler. final String inputFile; const PreprocessorOptions( {this.verbose = false, this.checked = false, this.lessSupport = true, this.warningsAsErrors = false, this.throwOnErrors = false, this.throwOnWarnings = false, this.useColors = true, this.polyfill = false, this.inputFile}); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/property.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Representations of CSS styles. part of '../parser.dart'; // TODO(terry): Prune down this file we do need some of the code in this file // for darker, lighter, how to represent a Font, etc but alot of // the complexity can be removed. // See https://github.com/dart-lang/csslib/issues/7 /// Base for all style properties (e.g., Color, Font, Border, Margin, etc.) abstract class _StyleProperty { /// Returns the expression part of a CSS declaration. Declaration is: /// /// property:expression; /// /// E.g., if property is color then expression could be rgba(255,255,0) the /// CSS declaration would be 'color:rgba(255,255,0);'. /// /// then _cssExpression would return 'rgba(255,255,0)'. See /// <http://www.w3.org/TR/CSS21/grammar.html> String get cssExpression; } /// Base interface for Color, HSL and RGB. abstract class ColorBase { /// Canonical form for color #rrggbb with alpha blending (0.0 == full /// transparency and 1.0 == fully opaque). If _argb length is 6 it's an /// rrggbb otherwise it's aarrggbb. String toHexArgbString(); /// Return argb as a value (int). int get argbValue; } /// General purpse Color class. Represent a color as an ARGB value that can be /// converted to and from num, hex string, hsl, hsla, rgb, rgba and SVG pre- /// defined color constant. class Color implements _StyleProperty, ColorBase { // If _argb length is 6 it's an rrggbb otherwise it's aarrggbb. final String _argb; // TODO(terry): Look at reducing Rgba and Hsla classes as factories for // converting from Color to an Rgba or Hsla for reading only. // Usefulness of creating an Rgba or Hsla is limited. /// Create a color with an integer representing the rgb value of red, green, /// and blue. The value 0xffffff is the color white #ffffff (CSS style). /// The [rgb] value of 0xffd700 would map to #ffd700 or the constant /// Color.gold, where ff is red intensity, d7 is green intensity, and 00 is /// blue intensity. Color(int rgb, [num alpha]) : _argb = Color._rgbToArgbString(rgb, alpha); /// RGB takes three values. The [red], [green], and [blue] parameters are /// the intensity of those components where '0' is the least and '256' is the /// greatest. /// /// If [alpha] is provided, it is the level of translucency which ranges from /// '0' (completely transparent) to '1.0' (completely opaque). It will /// internally be mapped to an int between '0' and '255' like the other color /// components. Color.createRgba(int red, int green, int blue, [num alpha]) : _argb = Color.convertToHexString( Color._clamp(red, 0, 255), Color._clamp(green, 0, 255), Color._clamp(blue, 0, 255), alpha != null ? Color._clamp(alpha, 0, 1) : alpha); /// Creates a new color from a CSS color string. For more information, see /// <https://developer.mozilla.org/en/CSS/color>. Color.css(String color) : _argb = Color._convertCssToArgb(color); // TODO(jmesserly): I found the use of percents a bit suprising. /// HSL takes three values. The [hueDegree] degree on the color wheel; '0' is /// the least and '100' is the greatest. The value '0' or '360' is red, '120' /// is green, '240' is blue. Numbers in between reflect different shades. /// The [saturationPercent] percentage; where'0' is the least and '100' is the /// greatest (100 represents full color). The [lightnessPercent] percentage; /// where'0' is the least and '100' is the greatest. The value 0 is dark or /// black, 100 is light or white and 50 is a medium lightness. /// /// If [alpha] is provided, it is the level of translucency which ranges from /// '0' (completely transparent foreground) to '1.0' (completely opaque /// foreground). Color.createHsla(num hueDegree, num saturationPercent, num lightnessPercent, [num alpha]) : _argb = Hsla( Color._clamp(hueDegree, 0, 360) / 360, Color._clamp(saturationPercent, 0, 100) / 100, Color._clamp(lightnessPercent, 0, 100) / 100, alpha != null ? Color._clamp(alpha, 0, 1) : alpha) .toHexArgbString(); /// The hslaRaw takes three values. The [hue] degree on the color wheel; '0' /// is the least and '1' is the greatest. The value '0' or '1' is red, the /// ratio of 120/360 is green, and the ratio of 240/360 is blue. Numbers in /// between reflect different shades. The [saturation] is a percentage; '0' /// is the least and '1' is the greatest. The value of '1' is equivalent to /// 100% (full colour). The [lightness] is a percentage; '0' is the least and /// '1' is the greatest. The value of '0' is dark (black), the value of '1' /// is light (white), and the value of '.50' is a medium lightness. /// /// The fourth optional parameter is: /// [alpha] level of translucency range of values is 0..1, zero is a /// completely transparent foreground and 1 is a completely /// opaque foreground. Color.hslaRaw(num hue, num saturation, num lightness, [num alpha]) : _argb = Hsla( Color._clamp(hue, 0, 1), Color._clamp(saturation, 0, 1), Color._clamp(lightness, 0, 1), alpha != null ? Color._clamp(alpha, 0, 1) : alpha) .toHexArgbString(); /// Generate a real constant for pre-defined colors (no leading #). const Color.hex(this._argb); // TODO(jmesserly): this is needed by the example so leave it exposed for now. @override String toString() => cssExpression; // TODO(terry): Regardless of how color is set (rgb, num, css or hsl) we'll // always return a rgb or rgba loses fidelity when debugging in // CSS if user uses hsl and would like to edit as hsl, etc. If // this is an issue we should keep the original value and not re- // create the CSS from the normalized value. @override String get cssExpression { if (_argb.length == 6) { return '#$_argb'; // RGB only, no alpha blending. } else { num alpha = Color.hexToInt(_argb.substring(0, 2)); var a = (alpha / 255).toStringAsPrecision(2); var r = Color.hexToInt(_argb.substring(2, 4)); var g = Color.hexToInt(_argb.substring(4, 6)); var b = Color.hexToInt(_argb.substring(6, 8)); return 'rgba($r,$g,$b,$a)'; } } Rgba get rgba { var nextIndex = 0; num a; if (_argb.length == 8) { // Get alpha blending value 0..255 var alpha = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2)); // Convert to value from 0..1 a = double.parse((alpha / 255).toStringAsPrecision(2)); nextIndex += 2; } var r = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2)); nextIndex += 2; var g = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2)); nextIndex += 2; var b = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2)); return Rgba(r, g, b, a); } Hsla get hsla => Hsla.fromRgba(rgba); @override int get argbValue => Color.hexToInt(_argb); @override bool operator ==(other) => Color.equal(this, other); @override String toHexArgbString() => _argb; Color darker(num amount) { var newRgba = Color._createNewTintShadeFromRgba(rgba, -amount); return Color.hex('${newRgba.toHexArgbString()}'); } Color lighter(num amount) { var newRgba = Color._createNewTintShadeFromRgba(rgba, amount); return Color.hex('${newRgba.toHexArgbString()}'); } static bool equal(ColorBase curr, other) { if (other is Color) { var o = other; return o.toHexArgbString() == curr.toHexArgbString(); } else if (other is Rgba) { var rgb = other; return rgb.toHexArgbString() == curr.toHexArgbString(); } else if (other is Hsla) { var hsla = other; return hsla.toHexArgbString() == curr.toHexArgbString(); } else { return false; } } @override int get hashCode => _argb.hashCode; // Conversion routines: static String _rgbToArgbString(int rgba, num alpha) { int a; // If alpha is defined then adjust from 0..1 to 0..255 value, if not set // then a is left as undefined and passed to convertToHexString. if (alpha != null) { a = (Color._clamp(alpha, 0, 1) * 255).round(); } var r = (rgba & 0xff0000) >> 0x10; var g = (rgba & 0xff00) >> 8; var b = rgba & 0xff; return Color.convertToHexString(r, g, b, a); } static const int _rgbCss = 1; static const int _rgbaCss = 2; static const int _hslCss = 3; static const int _hslaCss = 4; /// Parse CSS expressions of the from #rgb, rgb(r,g,b), rgba(r,g,b,a), /// hsl(h,s,l), hsla(h,s,l,a) and SVG colors (e.g., darkSlateblue, etc.) and /// convert to argb. static String _convertCssToArgb(String value) { // TODO(terry): Better parser/regex for converting CSS properties. var color = value.trim().replaceAll('\\s', ''); if (color[0] == '#') { var v = color.substring(1); Color.hexToInt(v); // Valid hexadecimal, throws if not. return v; } else if (color.isNotEmpty && color[color.length - 1] == ')') { int type; if (color.indexOf('rgb(') == 0 || color.indexOf('RGB(') == 0) { color = color.substring(4); type = _rgbCss; } else if (color.indexOf('rgba(') == 0 || color.indexOf('RGBA(') == 0) { type = _rgbaCss; color = color.substring(5); } else if (color.indexOf('hsl(') == 0 || color.indexOf('HSL(') == 0) { type = _hslCss; color = color.substring(4); } else if (color.indexOf('hsla(') == 0 || color.indexOf('HSLA(') == 0) { type = _hslaCss; color = color.substring(5); } else { throw UnsupportedError('CSS property not implemented'); } color = color.substring(0, color.length - 1); // Strip close paren. var args = <num>[]; var params = color.split(','); for (var param in params) { args.add(double.parse(param)); } switch (type) { case _rgbCss: return Color.convertToHexString(args[0], args[1], args[2]); case _rgbaCss: return Color.convertToHexString(args[0], args[1], args[2], args[3]); case _hslCss: return Hsla(args[0], args[1], args[2]).toHexArgbString(); case _hslaCss: return Hsla(args[0], args[1], args[2], args[3]).toHexArgbString(); default: // Type not defined UnsupportedOperationException should have thrown. assert(false); break; } } return null; } static int hexToInt(String hex) => int.parse(hex, radix: 16); static String convertToHexString(int r, int g, int b, [num a]) { var rHex = Color._numAs2DigitHex(Color._clamp(r, 0, 255)); var gHex = Color._numAs2DigitHex(Color._clamp(g, 0, 255)); var bHex = Color._numAs2DigitHex(Color._clamp(b, 0, 255)); var aHex = (a != null) ? Color._numAs2DigitHex((Color._clamp(a, 0, 1) * 255).round()) : ''; // TODO(terry) 15.toRadixString(16) return 'F' on Dartium not f as in JS. // bug: <http://code.google.com/p/dart/issues/detail?id=2670> return '$aHex$rHex$gHex$bHex'.toLowerCase(); } static String _numAs2DigitHex(num v) { // TODO(terry): v.toInt().toRadixString instead of v.toRadixString // Bug <http://code.google.com/p/dart/issues/detail?id=2671>. var hex = v.toInt().toRadixString(16); if (hex.length == 1) { hex = '0${hex}'; } return hex; } static num _clamp(num value, num min, num max) => math.max(math.min(max, value), min); /// Change the tint (make color lighter) or shade (make color darker) of all /// parts of [rgba] (r, g and b). The [amount] is percentage darker between /// -1 to 0 for darker and 0 to 1 for lighter; '0' is no change. The [amount] /// will darken or lighten the rgb values; it will not change the alpha value. /// If [amount] is outside of the value -1 to +1 then [amount] is changed to /// either the min or max direction -1 or 1. /// /// Darker will approach the color #000000 (black) and lighter will approach /// the color #ffffff (white). static Rgba _createNewTintShadeFromRgba(Rgba rgba, num amount) { int r, g, b; var tintShade = Color._clamp(amount, -1, 1); if (amount < 0 && rgba.r == 255 && rgba.g == 255 && rgba.b == 255) { // TODO(terry): See TODO in _changeTintShadeColor; eliminate this test // by converting to HSL and adjust lightness although this // is fastest lighter/darker algorithm. // Darkening white special handling. r = Color._clamp((255 + (255 * tintShade)).round().toInt(), 0, 255); g = Color._clamp((255 + (255 * tintShade)).round().toInt(), 0, 255); b = Color._clamp((255 + (255 * tintShade)).round().toInt(), 0, 255); } else { // All other colors then darkening white go here. r = Color._changeTintShadeColor(rgba.r, tintShade).round().toInt(); g = Color._changeTintShadeColor(rgba.g, tintShade).round().toInt(); b = Color._changeTintShadeColor(rgba.b, tintShade).round().toInt(); } return Rgba(r, g, b, rgba.a); } // TODO(terry): This does an okay lighter/darker; better would be convert to // HSL then change the lightness. /// The parameter [v] is the color to change (r, g, or b) in the range '0' to /// '255'. The parameter [delta] is a number between '-1' and '1'. A value /// between '-1' and '0' is darker and a value between '0' and '1' is lighter /// ('0' imples no change). static num _changeTintShadeColor(num v, num delta) => Color._clamp(((1 - delta) * v + (delta * 255)).round(), 0, 255); // Predefined CSS colors see <http://www.w3.org/TR/css3-color/> static final Color transparent = const Color.hex('00ffffff'); // Alpha 0.0 static final Color aliceBlue = const Color.hex('0f08ff'); static final Color antiqueWhite = const Color.hex('0faebd7'); static final Color aqua = const Color.hex('00ffff'); static final Color aquaMarine = const Color.hex('7fffd4'); static final Color azure = const Color.hex('f0ffff'); static final Color beige = const Color.hex('f5f5dc'); static final Color bisque = const Color.hex('ffe4c4'); static final Color black = const Color.hex('000000'); static final Color blanchedAlmond = const Color.hex('ffebcd'); static final Color blue = const Color.hex('0000ff'); static final Color blueViolet = const Color.hex('8a2be2'); static final Color brown = const Color.hex('a52a2a'); static final Color burlyWood = const Color.hex('deb887'); static final Color cadetBlue = const Color.hex('5f9ea0'); static final Color chartreuse = const Color.hex('7fff00'); static final Color chocolate = const Color.hex('d2691e'); static final Color coral = const Color.hex('ff7f50'); static final Color cornFlowerBlue = const Color.hex('6495ed'); static final Color cornSilk = const Color.hex('fff8dc'); static final Color crimson = const Color.hex('dc143c'); static final Color cyan = const Color.hex('00ffff'); static final Color darkBlue = const Color.hex('00008b'); static final Color darkCyan = const Color.hex('008b8b'); static final Color darkGoldenRod = const Color.hex('b8860b'); static final Color darkGray = const Color.hex('a9a9a9'); static final Color darkGreen = const Color.hex('006400'); static final Color darkGrey = const Color.hex('a9a9a9'); static final Color darkKhaki = const Color.hex('bdb76b'); static final Color darkMagenta = const Color.hex('8b008b'); static final Color darkOliveGreen = const Color.hex('556b2f'); static final Color darkOrange = const Color.hex('ff8c00'); static final Color darkOrchid = const Color.hex('9932cc'); static final Color darkRed = const Color.hex('8b0000'); static final Color darkSalmon = const Color.hex('e9967a'); static final Color darkSeaGreen = const Color.hex('8fbc8f'); static final Color darkSlateBlue = const Color.hex('483d8b'); static final Color darkSlateGray = const Color.hex('2f4f4f'); static final Color darkSlateGrey = const Color.hex('2f4f4f'); static final Color darkTurquoise = const Color.hex('00ced1'); static final Color darkViolet = const Color.hex('9400d3'); static final Color deepPink = const Color.hex('ff1493'); static final Color deepSkyBlue = const Color.hex('00bfff'); static final Color dimGray = const Color.hex('696969'); static final Color dimGrey = const Color.hex('696969'); static final Color dodgerBlue = const Color.hex('1e90ff'); static final Color fireBrick = const Color.hex('b22222'); static final Color floralWhite = const Color.hex('fffaf0'); static final Color forestGreen = const Color.hex('228b22'); static final Color fuchsia = const Color.hex('ff00ff'); static final Color gainsboro = const Color.hex('dcdcdc'); static final Color ghostWhite = const Color.hex('f8f8ff'); static final Color gold = const Color.hex('ffd700'); static final Color goldenRod = const Color.hex('daa520'); static final Color gray = const Color.hex('808080'); static final Color green = const Color.hex('008000'); static final Color greenYellow = const Color.hex('adff2f'); static final Color grey = const Color.hex('808080'); static final Color honeydew = const Color.hex('f0fff0'); static final Color hotPink = const Color.hex('ff69b4'); static final Color indianRed = const Color.hex('cd5c5c'); static final Color indigo = const Color.hex('4b0082'); static final Color ivory = const Color.hex('fffff0'); static final Color khaki = const Color.hex('f0e68c'); static final Color lavender = const Color.hex('e6e6fa'); static final Color lavenderBlush = const Color.hex('fff0f5'); static final Color lawnGreen = const Color.hex('7cfc00'); static final Color lemonChiffon = const Color.hex('fffacd'); static final Color lightBlue = const Color.hex('add8e6'); static final Color lightCoral = const Color.hex('f08080'); static final Color lightCyan = const Color.hex('e0ffff'); static final Color lightGoldenRodYellow = const Color.hex('fafad2'); static final Color lightGray = const Color.hex('d3d3d3'); static final Color lightGreen = const Color.hex('90ee90'); static final Color lightGrey = const Color.hex('d3d3d3'); static final Color lightPink = const Color.hex('ffb6c1'); static final Color lightSalmon = const Color.hex('ffa07a'); static final Color lightSeaGreen = const Color.hex('20b2aa'); static final Color lightSkyBlue = const Color.hex('87cefa'); static final Color lightSlateGray = const Color.hex('778899'); static final Color lightSlateGrey = const Color.hex('778899'); static final Color lightSteelBlue = const Color.hex('b0c4de'); static final Color lightYellow = const Color.hex('ffffe0'); static final Color lime = const Color.hex('00ff00'); static final Color limeGreen = const Color.hex('32cd32'); static final Color linen = const Color.hex('faf0e6'); static final Color magenta = const Color.hex('ff00ff'); static final Color maroon = const Color.hex('800000'); static final Color mediumAquaMarine = const Color.hex('66cdaa'); static final Color mediumBlue = const Color.hex('0000cd'); static final Color mediumOrchid = const Color.hex('ba55d3'); static final Color mediumPurple = const Color.hex('9370db'); static final Color mediumSeaGreen = const Color.hex('3cb371'); static final Color mediumSlateBlue = const Color.hex('7b68ee'); static final Color mediumSpringGreen = const Color.hex('00fa9a'); static final Color mediumTurquoise = const Color.hex('48d1cc'); static final Color mediumVioletRed = const Color.hex('c71585'); static final Color midnightBlue = const Color.hex('191970'); static final Color mintCream = const Color.hex('f5fffa'); static final Color mistyRose = const Color.hex('ffe4e1'); static final Color moccasin = const Color.hex('ffe4b5'); static final Color navajoWhite = const Color.hex('ffdead'); static final Color navy = const Color.hex('000080'); static final Color oldLace = const Color.hex('fdf5e6'); static final Color olive = const Color.hex('808000'); static final Color oliveDrab = const Color.hex('6b8e23'); static final Color orange = const Color.hex('ffa500'); static final Color orangeRed = const Color.hex('ff4500'); static final Color orchid = const Color.hex('da70d6'); static final Color paleGoldenRod = const Color.hex('eee8aa'); static final Color paleGreen = const Color.hex('98fb98'); static final Color paleTurquoise = const Color.hex('afeeee'); static final Color paleVioletRed = const Color.hex('db7093'); static final Color papayaWhip = const Color.hex('ffefd5'); static final Color peachPuff = const Color.hex('ffdab9'); static final Color peru = const Color.hex('cd85ef'); static final Color pink = const Color.hex('ffc0cb'); static final Color plum = const Color.hex('dda0dd'); static final Color powderBlue = const Color.hex('b0e0e6'); static final Color purple = const Color.hex('800080'); static final Color red = const Color.hex('ff0000'); static final Color rosyBrown = const Color.hex('bc8f8f'); static final Color royalBlue = const Color.hex('4169e1'); static final Color saddleBrown = const Color.hex('8b4513'); static final Color salmon = const Color.hex('fa8072'); static final Color sandyBrown = const Color.hex('f4a460'); static final Color seaGreen = const Color.hex('2e8b57'); static final Color seashell = const Color.hex('fff5ee'); static final Color sienna = const Color.hex('a0522d'); static final Color silver = const Color.hex('c0c0c0'); static final Color skyBlue = const Color.hex('87ceeb'); static final Color slateBlue = const Color.hex('6a5acd'); static final Color slateGray = const Color.hex('708090'); static final Color slateGrey = const Color.hex('708090'); static final Color snow = const Color.hex('fffafa'); static final Color springGreen = const Color.hex('00ff7f'); static final Color steelBlue = const Color.hex('4682b4'); static final Color tan = const Color.hex('d2b48c'); static final Color teal = const Color.hex('008080'); static final Color thistle = const Color.hex('d8bfd8'); static final Color tomato = const Color.hex('ff6347'); static final Color turquoise = const Color.hex('40e0d0'); static final Color violet = const Color.hex('ee82ee'); static final Color wheat = const Color.hex('f5deb3'); static final Color white = const Color.hex('ffffff'); static final Color whiteSmoke = const Color.hex('f5f5f5'); static final Color yellow = const Color.hex('ffff00'); static final Color yellowGreen = const Color.hex('9acd32'); } /// Rgba class for users that want to interact with a color as a RGBA value. class Rgba implements _StyleProperty, ColorBase { // TODO(terry): Consider consolidating rgba to a single 32-bit int, make sure // it works under JS and Dart VM. final int r; final int g; final int b; final num a; Rgba(int red, int green, int blue, [num alpha]) : r = Color._clamp(red, 0, 255), g = Color._clamp(green, 0, 255), b = Color._clamp(blue, 0, 255), a = (alpha != null) ? Color._clamp(alpha, 0, 1) : alpha; factory Rgba.fromString(String hexValue) => Color.css('#${Color._convertCssToArgb(hexValue)}').rgba; factory Rgba.fromColor(Color color) => color.rgba; factory Rgba.fromArgbValue(num value) { return Rgba( ((value.toInt() & 0xff000000) >> 0x18), // a ((value.toInt() & 0xff0000) >> 0x10), // r ((value.toInt() & 0xff00) >> 8), // g ((value.toInt() & 0xff))); // b } factory Rgba.fromHsla(Hsla hsla) { // Convert to Rgba. // See site <http://easyrgb.com/index.php?X=MATH> for good documentation // and color conversion routines. var h = hsla.hue; var s = hsla.saturation; var l = hsla.lightness; var a = hsla.alpha; int r; int g; int b; if (s == 0) { r = (l * 255).round().toInt(); g = r; b = r; } else { num var2; if (l < 0.5) { var2 = l * (1 + s); } else { var2 = (l + s) - (s * l); } var var1 = 2 * l - var2; r = (255 * Rgba._hueToRGB(var1, var2, h + (1 / 3))).round().toInt(); g = (255 * Rgba._hueToRGB(var1, var2, h)).round().toInt(); b = (255 * Rgba._hueToRGB(var1, var2, h - (1 / 3))).round().toInt(); } return Rgba(r, g, b, a); } static num _hueToRGB(num v1, num v2, num vH) { if (vH < 0) { vH += 1; } if (vH > 1) { vH -= 1; } if ((6 * vH) < 1) { return (v1 + (v2 - v1) * 6 * vH); } if ((2 * vH) < 1) { return v2; } if ((3 * vH) < 2) { return (v1 + (v2 - v1) * ((2 / 3 - vH) * 6)); } return v1; } @override bool operator ==(other) => Color.equal(this, other); @override String get cssExpression { if (a == null) { return '#${Color.convertToHexString(r, g, b)}'; } else { return 'rgba($r,$g,$b,$a)'; } } @override String toHexArgbString() => Color.convertToHexString(r, g, b, a); @override int get argbValue { var value = 0; if (a != null) { value = (a.toInt() << 0x18); } value += (r << 0x10); value += (g << 0x08); value += b; return value; } Color get color => Color.createRgba(r, g, b, a); Hsla get hsla => Hsla.fromRgba(this); Rgba darker(num amount) => Color._createNewTintShadeFromRgba(this, -amount); Rgba lighter(num amount) => Color._createNewTintShadeFromRgba(this, amount); @override int get hashCode => toHexArgbString().hashCode; } /// Hsl class support to interact with a color as a hsl with hue, saturation, /// and lightness with optional alpha blending. The hue is a ratio of 360 /// degrees 360° = 1 or 0, (1° == (1/360)), saturation and lightness is a 0..1 /// fraction (1 == 100%) and alpha is a 0..1 fraction. class Hsla implements _StyleProperty, ColorBase { final num _h; // Value from 0..1 final num _s; // Value from 0..1 final num _l; // Value from 0..1 final num _a; // Value from 0..1 /// [hue] is a 0..1 fraction of 360 degrees (360 == 0). /// [saturation] is a 0..1 fraction (100% == 1). /// [lightness] is a 0..1 fraction (100% == 1). /// [alpha] is a 0..1 fraction, alpha blending between 0..1, 1 == 100% opaque. Hsla(num hue, num saturation, num lightness, [num alpha]) : _h = (hue == 1) ? 0 : Color._clamp(hue, 0, 1), _s = Color._clamp(saturation, 0, 1), _l = Color._clamp(lightness, 0, 1), _a = (alpha != null) ? Color._clamp(alpha, 0, 1) : alpha; factory Hsla.fromString(String hexValue) { var rgba = Color.css('#${Color._convertCssToArgb(hexValue)}').rgba; return _createFromRgba(rgba.r, rgba.g, rgba.b, rgba.a); } factory Hsla.fromColor(Color color) { var rgba = color.rgba; return _createFromRgba(rgba.r, rgba.g, rgba.b, rgba.a); } factory Hsla.fromArgbValue(num value) { num a = (value.toInt() & 0xff000000) >> 0x18; var r = (value.toInt() & 0xff0000) >> 0x10; var g = (value.toInt() & 0xff00) >> 8; var b = value.toInt() & 0xff; // Convert alpha to 0..1 from (0..255). if (a != null) { a = double.parse((a / 255).toStringAsPrecision(2)); } return _createFromRgba(r, g, b, a); } factory Hsla.fromRgba(Rgba rgba) => _createFromRgba(rgba.r, rgba.g, rgba.b, rgba.a); static Hsla _createFromRgba(num r, num g, num b, num a) { // Convert RGB to hsl. // See site <http://easyrgb.com/index.php?X=MATH> for good documentation // and color conversion routines. r /= 255; g /= 255; b /= 255; // Hue, saturation and lightness. num h; num s; num l; var minRgb = math.min(r, math.min(g, b)); var maxRgb = math.max(r, math.max(g, b)); l = (maxRgb + minRgb) / 2; if (l <= 0) { return Hsla(0, 0, l); // Black; } var vm = maxRgb - minRgb; s = vm; if (s > 0) { s /= (l < 0.5) ? (maxRgb + minRgb) : (2 - maxRgb - minRgb); } else { return Hsla(0, 0, l); // White } num r2, g2, b2; r2 = (maxRgb - r) / vm; g2 = (maxRgb - g) / vm; b2 = (maxRgb - b) / vm; if (r == maxRgb) { h = (g == minRgb) ? 5.0 + b2 : 1 - g2; } else if (g == maxRgb) { h = (b == minRgb) ? 1 + r2 : 3 - b2; } else { h = (r == minRgb) ? 3 + g2 : 5 - r2; } h /= 6; return Hsla(h, s, l, a); } /// Returns 0..1 fraction (ratio of 360°, e.g. 1° == 1/360). num get hue => _h; /// Returns 0..1 fraction (1 == 100%) num get saturation => _s; /// Returns 0..1 fraction (1 == 100%). num get lightness => _l; /// Returns number as degrees 0..360. num get hueDegrees => (_h * 360).round(); /// Returns number as percentage 0..100 num get saturationPercentage => (_s * 100).round(); /// Returns number as percentage 0..100. num get lightnessPercentage => (_l * 100).round(); /// Returns number as 0..1 num get alpha => _a; @override bool operator ==(other) => Color.equal(this, other); @override String get cssExpression => (_a == null) ? 'hsl($hueDegrees,$saturationPercentage,$lightnessPercentage)' : 'hsla($hueDegrees,$saturationPercentage,$lightnessPercentage,$_a)'; @override String toHexArgbString() => Rgba.fromHsla(this).toHexArgbString(); @override int get argbValue => Color.hexToInt(toHexArgbString()); Color get color => Color.createHsla(_h, _s, _l, _a); Rgba get rgba => Rgba.fromHsla(this); Hsla darker(num amount) => Hsla.fromRgba(Rgba.fromHsla(this).darker(amount)); Hsla lighter(num amount) => Hsla.fromRgba(Rgba.fromHsla(this).lighter(amount)); @override int get hashCode => toHexArgbString().hashCode; } /// X,Y position. class PointXY implements _StyleProperty { final num x, y; const PointXY(this.x, this.y); @override String get cssExpression { // TODO(terry): TBD return null; } } // TODO(terry): Implement style and color. /// Supports border for measuring with layout. class Border implements _StyleProperty { final int top, left, bottom, right; // TODO(terry): Just like CSS, 1-arg -> set all properties, 2-args -> top and // bottom are first arg, left and right are second, 3-args, and // 4-args -> tlbr or trbl. const Border([this.top, this.left, this.bottom, this.right]); // TODO(terry): Consider using Size or width and height. Border.uniform(num amount) : top = amount, left = amount, bottom = amount, right = amount; int get width => left + right; int get height => top + bottom; @override String get cssExpression { return (top == left && bottom == right && top == right) ? '${left}px' : "${top != null ? '$top' : '0'}px " "${right != null ? '$right' : '0'}px " "${bottom != null ? '$bottom' : '0'}px " "${left != null ? '$left' : '0'}px"; } } /// Font style constants. class FontStyle { /// Font style [normal] default. static const String normal = 'normal'; /// Font style [italic] use explicity crafted italic font otherwise inclined /// on the fly like oblique. static const String italic = 'italic'; /// Font style [oblique] is rarely used. The normal style of a font is /// inclined on the fly to the right by 8-12 degrees. static const String oblique = 'oblique'; } /// Font variant constants. class FontVariant { /// Font style [normal] default. static const String normal = 'normal'; /// Font variant [smallCaps]. static const String smallCaps = 'small-caps'; } /// Font weight constants values 100, 200, 300, 400, 500, 600, 700, 800, 900. class FontWeight { /// Font weight normal [default] static const int normal = 400; /// Font weight bold static const int bold = 700; static const int wt100 = 100; static const int wt200 = 200; static const int wt300 = 300; static const int wt400 = 400; static const int wt500 = 500; static const int wt600 = 600; static const int wt700 = 700; static const int wt800 = 800; static const int wt900 = 900; } /// Generic font family names. class FontGeneric { /// Generic family sans-serif font (w/o serifs). static const String sansSerif = 'sans-serif'; /// Generic family serif font. static const String serif = 'serif'; /// Generic family fixed-width font. static const monospace = 'monospace'; /// Generic family emulate handwriting font. static const String cursive = 'cursive'; /// Generic family decorative font. static const String fantasy = 'fantasy'; } /// List of most common font families across different platforms. Use the /// collection names in the Font class (e.g., Font.SANS_SERIF, Font.FONT_SERIF, /// Font.MONOSPACE, Font.CURSIVE or Font.FANTASY). These work best on all /// platforms using the fonts that best match availability on each platform. /// See <http://www.angelfire.com/al4/rcollins/style/fonts.html> for a good /// description of fonts available between platforms and browsers. class FontFamily { /// Sans-Serif font for Windows similar to Helvetica on Mac bold/italic. static const String arial = 'arial'; /// Sans-Serif font for Windows less common already bolded. static const String arialBlack = 'arial black'; /// Sans-Serif font for Mac since 1984, similar to Arial/Helvetica. static const String geneva = 'geneva'; /// Sans-Serif font for Windows most readable sans-serif font for displays. static const String verdana = 'verdana'; /// Sans-Serif font for Mac since 1984 is identical to Arial. static const String helvetica = 'helvetica'; /// Serif font for Windows traditional font with “old-style” numerals. static const String georgia = 'georgia'; /// Serif font for Mac. PCs may have the non-scalable Times use Times New /// Roman instead. Times is more compact than Times New Roman. static const String times = 'times'; /// Serif font for Windows most common serif font and default serif font for /// most browsers. static const String timesNewRoman = 'times new roman'; /// Monospace font for Mac/Windows most common. Scalable on Mac not scalable /// on Windows. static const String courier = 'courier'; /// Monospace font for Mac/Windows scalable on both platforms. static const String courierNew = 'courier new'; /// Cursive font for Windows and default cursive font for IE. static const String comicSansMs = 'comic sans ms'; /// Cursive font for Mac on Macs 2000 and newer. static const String textile = 'textile'; /// Cursive font for older Macs. static const String appleChancery = 'apple chancery'; /// Cursive font for some PCs. static const String zaphChancery = 'zaph chancery'; /// Fantasy font on most Mac/Windows/Linux platforms. static const String impact = 'impact'; /// Fantasy font for Windows. static const String webdings = 'webdings'; } class LineHeight { final num height; final bool inPixels; const LineHeight(this.height, {this.inPixels = true}); } // TODO(terry): Support @font-face fule. /// Font style support for size, family, weight, style, variant, and lineheight. class Font implements _StyleProperty { /// Collection of most common sans-serif fonts in order. static const List<String> sansSerif = [ FontFamily.arial, FontFamily.verdana, FontFamily.geneva, FontFamily.helvetica, FontGeneric.sansSerif ]; /// Collection of most common serif fonts in order. static const List<String> serif = [ FontFamily.georgia, FontFamily.timesNewRoman, FontFamily.times, FontGeneric.serif ]; /// Collection of most common monospace fonts in order. static const List<String> monospace = [ FontFamily.courierNew, FontFamily.courier, FontGeneric.monospace ]; /// Collection of most common cursive fonts in order. static const List<String> cursive = [ FontFamily.textile, FontFamily.appleChancery, FontFamily.zaphChancery, FontGeneric.fantasy ]; /// Collection of most common fantasy fonts in order. static const List<String> fantasy = [ FontFamily.comicSansMs, FontFamily.impact, FontFamily.webdings, FontGeneric.fantasy ]; // TODO(terry): Should support the values xx-small, small, large, xx-large, // etc. (mapped to a pixel sized font)? /// Font size in pixels. final num size; // TODO(terry): _family should be an immutable list, wrapper class to do this // should exist in Dart. /// Family specifies a list of fonts, the browser will sequentially select the /// the first known/supported font. There are two types of font families the /// family-name (e.g., arial, times, courier, etc) or the generic-family /// (e.g., serif, sans-seric, etc.) final List<String> family; /// Font weight from 100, 200, 300, 400, 500, 600, 700, 800, 900 final int weight; /// Style of a font normal, italic, oblique. final String style; /// Font variant NORMAL (default) or SMALL_CAPS. Different set of font glyph /// lower case letters designed to have to fit within the font-height and /// weight of the corresponding lowercase letters. final String variant; final LineHeight lineHeight; // TODO(terry): Size and computedLineHeight are in pixels. Need to figure out // how to handle in other units (specified in other units) like // points, inches, etc. Do we have helpers like Units.Points(12) // where 12 is in points and that's converted to pixels? // TODO(terry): lineHeight is computed as 1.2 although CSS_RESET is 1.0 we // need to be consistent some browsers use 1 others 1.2. // TODO(terry): There is a school of thought "Golden Ratio Typography". // Where width to display the text is also important in computing the line // height. Classic typography suggest the ratio be 1.5. See // <http://www.pearsonified.com/2011/12/golden-ratio-typography.php> and // <http://meyerweb.com/eric/thoughts/2008/05/06/line-height-abnormal/>. /// Create a font using [size] of font in pixels, [family] name of font(s) /// using [FontFamily], [style] of the font using [FontStyle], [variant] using /// [FontVariant], and [lineHeight] extra space (leading) around the font in /// pixels, if not specified it's 1.2 the font size. const Font( {this.size, this.family, this.weight, this.style, this.variant, this.lineHeight}); /// Merge the two fonts and return the result. See [Style.merge] for /// more information. factory Font.merge(Font a, Font b) { if (a == null) return b; if (b == null) return a; return Font._merge(a, b); } Font._merge(Font a, Font b) : size = _mergeVal(a.size, b.size), family = _mergeVal(a.family, b.family), weight = _mergeVal(a.weight, b.weight), style = _mergeVal(a.style, b.style), variant = _mergeVal(a.variant, b.variant), lineHeight = _mergeVal(a.lineHeight, b.lineHeight); /// Shorthand CSS format for font is: /// /// font-style font-variant font-weight font-size/line-height font-family /// /// The font-size and font-family values are required. If any of the other /// values are missing the default value is used. @override String get cssExpression { // TODO(jimhug): include variant, style, other options if (weight != null) { // TODO(jacobr): is this really correct for lineHeight? if (lineHeight != null) { return '$weight ${size}px/$lineHeightInPixels $_fontsAsString'; } return '$weight ${size}px $_fontsAsString'; } return '${size}px $_fontsAsString'; } Font scale(num ratio) => Font( size: size * ratio, family: family, weight: weight, style: style, variant: variant); /// The lineHeight, provides an indirect means to specify the leading. The /// leading is the difference between the font-size height and the (used) /// value of line height in pixels. If lineHeight is not specified it's /// automatically computed as 1.2 of the font size. Firefox is 1.2, Safari is /// ~1.2, and CSS suggest a ration from 1 to 1.2 of the font-size when /// computing line-height. The Font class constructor has the computation for /// _lineHeight. num get lineHeightInPixels { if (lineHeight != null) { if (lineHeight.inPixels) { return lineHeight.height; } else { return (size != null) ? lineHeight.height * size : null; } } else { return (size != null) ? size * 1.2 : null; } } @override int get hashCode { // TODO(jimhug): Lot's of potential collisions here. List of fonts, etc. return size.toInt() % family[0].hashCode; } @override bool operator ==(other) { if (other is! Font) return false; Font o = other; return o.size == size && o.family == family && o.weight == weight && o.lineHeight == lineHeight && o.style == style && o.variant == variant; } // TODO(terry): This is fragile should probably just iterate through the list // of fonts construction the font-family string. /// Return fonts as a comma seperated list sans the square brackets. String get _fontsAsString { var fonts = family.toString(); return fonts.length > 2 ? fonts.substring(1, fonts.length - 1) : ''; } } /// This class stores the sizes of the box edges in the CSS [box model][]. Each /// edge area is placed around the sides of the content box. The innermost area /// is the [Style.padding] area which has a background and surrounds the /// content. The content and padding area is surrounded by the [Style.border], /// which itself is surrounded by the transparent [Style.margin]. This box /// represents the eges of padding, border, or margin depending on which /// accessor was used to retrieve it. /// /// [box model]: https://developer.mozilla.org/en/CSS/box_model class BoxEdge { /// The size of the left edge, or null if the style has no edge. final num left; /// The size of the top edge, or null if the style has no edge. final num top; /// The size of the right edge, or null if the style has no edge. final num right; /// The size of the bottom edge, or null if the style has no edge. final num bottom; /// Creates a box edge with the specified [left], [top], [right], and /// [bottom] width. const BoxEdge([this.left, this.top, this.right, this.bottom]); /// Creates a box edge with the specified [top], [right], [bottom], and /// [left] width. This matches the typical CSS order: /// <https://developer.mozilla.org/en/CSS/margin> /// <https://developer.mozilla.org/en/CSS/border-width> /// <https://developer.mozilla.org/en/CSS/padding>. const BoxEdge.clockwiseFromTop(this.top, this.right, this.bottom, this.left); /// This is a helper to creates a box edge with the same [left], [top] /// [right], and [bottom] widths. const BoxEdge.uniform(num size) : top = size, left = size, bottom = size, right = size; /// Takes a possibly null box edge, with possibly null metrics, and fills /// them in with 0 instead. factory BoxEdge.nonNull(BoxEdge other) { if (other == null) return const BoxEdge(0, 0, 0, 0); var left = other.left; var top = other.top; var right = other.right; var bottom = other.bottom; var make = false; if (left == null) { make = true; left = 0; } if (top == null) { make = true; top = 0; } if (right == null) { make = true; right = 0; } if (bottom == null) { make = true; bottom = 0; } return make ? BoxEdge(left, top, right, bottom) : other; } /// Merge the two box edge sizes and return the result. See [Style.merge] for /// more information. factory BoxEdge.merge(BoxEdge x, BoxEdge y) { if (x == null) return y; if (y == null) return x; return BoxEdge._merge(x, y); } BoxEdge._merge(BoxEdge x, BoxEdge y) : left = _mergeVal(x.left, y.left), top = _mergeVal(x.top, y.top), right = _mergeVal(x.right, y.right), bottom = _mergeVal(x.bottom, y.bottom); /// The total size of the horizontal edges. Equal to [left] + [right], where /// null is interpreted as 0px. num get width => (left ?? 0) + (right ?? 0); /// The total size of the vertical edges. Equal to [top] + [bottom], where /// null is interpreted as 0px. num get height => (top ?? 0) + (bottom ?? 0); } T _mergeVal<T>(T x, T y) => y ?? x;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/tree_printer.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. part of '../visitor.dart'; // TODO(terry): Enable class for debug only; when conditional imports enabled. /// Helper function to dump the CSS AST. String treeToDebugString(StyleSheet styleSheet, [bool useSpan = false]) { var to = TreeOutput(); _TreePrinter(to, useSpan)..visitTree(styleSheet); return to.toString(); } /// Tree dump for debug output of the CSS AST. class _TreePrinter extends Visitor { final TreeOutput output; final bool useSpan; _TreePrinter(this.output, this.useSpan) { output.printer = this; } @override void visitTree(StyleSheet tree) => visitStylesheet(tree); void heading(String heading, node) { if (useSpan) { output.heading(heading, node.span); } else { output.heading(heading); } } void visitStylesheet(StyleSheet node) { heading('Stylesheet', node); output.depth++; super.visitStyleSheet(node); output.depth--; } @override void visitTopLevelProduction(TopLevelProduction node) { heading('TopLevelProduction', node); } @override void visitDirective(Directive node) { heading('Directive', node); } @override void visitCalcTerm(CalcTerm node) { heading('CalcTerm', node); output.depth++; super.visitCalcTerm(node); output.depth--; } @override void visitCssComment(CssComment node) { heading('Comment', node); output.depth++; output.writeValue('comment value', node.comment); output.depth--; } @override void visitCommentDefinition(CommentDefinition node) { heading('CommentDefinition (CDO/CDC)', node); output.depth++; output.writeValue('comment value', node.comment); output.depth--; } @override void visitMediaExpression(MediaExpression node) { heading('MediaExpression', node); output.writeValue('feature', node.mediaFeature); if (node.andOperator) output.writeValue('AND operator', ''); visitExpressions(node.exprs); } void visitMediaQueries(MediaQuery query) { output.heading('MediaQueries'); output.writeValue('unary', query.unary); output.writeValue('media type', query.mediaType); output.writeNodeList('media expressions', query.expressions); } @override void visitMediaDirective(MediaDirective node) { heading('MediaDirective', node); output.depth++; output.writeNodeList('media queries', node.mediaQueries); output.writeNodeList('rule sets', node.rules); super.visitMediaDirective(node); output.depth--; } @override void visitDocumentDirective(DocumentDirective node) { heading('DocumentDirective', node); output.depth++; output.writeNodeList('functions', node.functions); output.writeNodeList('group rule body', node.groupRuleBody); output.depth--; } @override void visitSupportsDirective(SupportsDirective node) { heading('SupportsDirective', node); output.depth++; output.writeNode('condition', node.condition); output.writeNodeList('group rule body', node.groupRuleBody); output.depth--; } @override void visitSupportsConditionInParens(SupportsConditionInParens node) { heading('SupportsConditionInParens', node); output.depth++; output.writeNode('condition', node.condition); output.depth--; } @override void visitSupportsNegation(SupportsNegation node) { heading('SupportsNegation', node); output.depth++; output.writeNode('condition', node.condition); output.depth--; } @override void visitSupportsConjunction(SupportsConjunction node) { heading('SupportsConjunction', node); output.depth++; output.writeNodeList('conditions', node.conditions); output.depth--; } @override void visitSupportsDisjunction(SupportsDisjunction node) { heading('SupportsDisjunction', node); output.depth++; output.writeNodeList('conditions', node.conditions); output.depth--; } @override void visitViewportDirective(ViewportDirective node) { heading('ViewportDirective', node); output.depth++; super.visitViewportDirective(node); output.depth--; } @override void visitPageDirective(PageDirective node) { heading('PageDirective', node); output.depth++; output.writeValue('pseudo page', node._pseudoPage); super.visitPageDirective(node); output.depth; } @override void visitCharsetDirective(CharsetDirective node) { heading('Charset Directive', node); output.writeValue('charset encoding', node.charEncoding); } @override void visitImportDirective(ImportDirective node) { heading('ImportDirective', node); output.depth++; output.writeValue('import', node.import); super.visitImportDirective(node); output.writeNodeList('media', node.mediaQueries); output.depth--; } @override void visitContentDirective(ContentDirective node) { print('ContentDirective not implemented'); } @override void visitKeyFrameDirective(KeyFrameDirective node) { heading('KeyFrameDirective', node); output.depth++; output.writeValue('keyframe', node.keyFrameName); output.writeValue('name', node.name); output.writeNodeList('blocks', node._blocks); output.depth--; } @override void visitKeyFrameBlock(KeyFrameBlock node) { heading('KeyFrameBlock', node); output.depth++; super.visitKeyFrameBlock(node); output.depth--; } @override void visitFontFaceDirective(FontFaceDirective node) { // TODO(terry): To Be Implemented } @override void visitStyletDirective(StyletDirective node) { heading('StyletDirective', node); output.writeValue('dartClassName', node.dartClassName); output.depth++; output.writeNodeList('rulesets', node.rules); output.depth--; } @override void visitNamespaceDirective(NamespaceDirective node) { heading('NamespaceDirective', node); output.depth++; output.writeValue('prefix', node._prefix); output.writeValue('uri', node._uri); output.depth--; } @override void visitVarDefinitionDirective(VarDefinitionDirective node) { heading('Less variable definition', node); output.depth++; visitVarDefinition(node.def); output.depth--; } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { heading('Mixin top-level ${node.name}', node); output.writeNodeList('parameters', node.definedArgs); output.depth++; _visitNodeList(node.rulesets); output.depth--; } @override void visitMixinDeclarationDirective(MixinDeclarationDirective node) { heading('Mixin declaration ${node.name}', node); output.writeNodeList('parameters', node.definedArgs); output.depth++; visitDeclarationGroup(node.declarations); output.depth--; } /// Added optional newLine for handling @include at top-level vs/ inside of /// a declaration group. @override void visitIncludeDirective(IncludeDirective node) { heading('IncludeDirective ${node.name}', node); var flattened = node.args.expand((e) => e).toList(); output.writeNodeList('parameters', flattened); } @override void visitIncludeMixinAtDeclaration(IncludeMixinAtDeclaration node) { heading('IncludeMixinAtDeclaration ${node.include.name}', node); output.depth++; visitIncludeDirective(node.include); output.depth--; } @override void visitExtendDeclaration(ExtendDeclaration node) { heading('ExtendDeclaration', node); output.depth++; _visitNodeList(node.selectors); output.depth--; } @override void visitRuleSet(RuleSet node) { heading('Ruleset', node); output.depth++; super.visitRuleSet(node); output.depth--; } @override void visitDeclarationGroup(DeclarationGroup node) { heading('DeclarationGroup', node); output.depth++; output.writeNodeList('declarations', node.declarations); output.depth--; } @override void visitMarginGroup(MarginGroup node) { heading('MarginGroup', node); output.depth++; output.writeValue('@directive', node.margin_sym); output.writeNodeList('declarations', node.declarations); output.depth--; } @override void visitDeclaration(Declaration node) { heading('Declaration', node); output.depth++; if (node.isIE7) output.write('IE7 property'); output.write('property'); super.visitDeclaration(node); output.writeNode('expression', node._expression); if (node.important) { output.writeValue('!important', 'true'); } output.depth--; } @override void visitVarDefinition(VarDefinition node) { heading('Var', node); output.depth++; output.write('defintion'); super.visitVarDefinition(node); output.writeNode('expression', node._expression); output.depth--; } @override void visitSelectorGroup(SelectorGroup node) { heading('Selector Group', node); output.depth++; output.writeNodeList('selectors', node.selectors); output.depth--; } @override void visitSelector(Selector node) { heading('Selector', node); output.depth++; output.writeNodeList( 'simpleSelectorsSequences', node.simpleSelectorSequences); output.depth--; } @override void visitSimpleSelectorSequence(SimpleSelectorSequence node) { heading('SimpleSelectorSequence', node); output.depth++; if (node.isCombinatorNone) { output.writeValue('combinator', 'NONE'); } else if (node.isCombinatorDescendant) { output.writeValue('combinator', 'descendant'); } else if (node.isCombinatorPlus) { output.writeValue('combinator', '+'); } else if (node.isCombinatorGreater) { output.writeValue('combinator', '>'); } else if (node.isCombinatorTilde) { output.writeValue('combinator', '~'); } else { output.writeValue('combinator', 'ERROR UNKNOWN'); } super.visitSimpleSelectorSequence(node); output.depth--; } @override void visitNamespaceSelector(NamespaceSelector node) { heading('Namespace Selector', node); output.depth++; super.visitNamespaceSelector(node); visitSimpleSelector(node.nameAsSimpleSelector); output.depth--; } @override void visitElementSelector(ElementSelector node) { heading('Element Selector', node); output.depth++; super.visitElementSelector(node); output.depth--; } @override void visitAttributeSelector(AttributeSelector node) { heading('AttributeSelector', node); output.depth++; super.visitAttributeSelector(node); var tokenStr = node.matchOperatorAsTokenString(); output.writeValue('operator', '${node.matchOperator()} (${tokenStr})'); output.writeValue('value', node.valueToString()); output.depth--; } @override void visitIdSelector(IdSelector node) { heading('Id Selector', node); output.depth++; super.visitIdSelector(node); output.depth--; } @override void visitClassSelector(ClassSelector node) { heading('Class Selector', node); output.depth++; super.visitClassSelector(node); output.depth--; } @override void visitPseudoClassSelector(PseudoClassSelector node) { heading('Pseudo Class Selector', node); output.depth++; super.visitPseudoClassSelector(node); output.depth--; } @override void visitPseudoElementSelector(PseudoElementSelector node) { heading('Pseudo Element Selector', node); output.depth++; super.visitPseudoElementSelector(node); output.depth--; } @override void visitPseudoClassFunctionSelector(PseudoClassFunctionSelector node) { heading('Pseudo Class Function Selector', node); output.depth++; node.argument.visit(this); super.visitPseudoClassFunctionSelector(node); output.depth--; } @override void visitPseudoElementFunctionSelector(PseudoElementFunctionSelector node) { heading('Pseudo Element Function Selector', node); output.depth++; visitSelectorExpression(node.expression); super.visitPseudoElementFunctionSelector(node); output.depth--; } @override void visitSelectorExpression(SelectorExpression node) { heading('Selector Expression', node); output.depth++; output.writeNodeList('expressions', node.expressions); output.depth--; } @override void visitNegationSelector(NegationSelector node) { super.visitNegationSelector(node); output.depth++; heading('Negation Selector', node); output.writeNode('Negation arg', node.negationArg); output.depth--; } @override void visitUnicodeRangeTerm(UnicodeRangeTerm node) { heading('UnicodeRangeTerm', node); output.depth++; output.writeValue('1st value', node.first); output.writeValue('2nd value', node.second); output.depth--; } @override void visitLiteralTerm(LiteralTerm node) { heading('LiteralTerm', node); output.depth++; output.writeValue('value', node.text); output.depth--; } @override void visitHexColorTerm(HexColorTerm node) { heading('HexColorTerm', node); output.depth++; output.writeValue('hex value', node.text); output.writeValue('decimal value', node.value); output.depth--; } @override void visitNumberTerm(NumberTerm node) { heading('NumberTerm', node); output.depth++; output.writeValue('value', node.text); output.depth--; } @override void visitUnitTerm(UnitTerm node) { output.depth++; output.writeValue('value', node.text); output.writeValue('unit', node.unitToString()); output.depth--; } @override void visitLengthTerm(LengthTerm node) { heading('LengthTerm', node); super.visitLengthTerm(node); } @override void visitPercentageTerm(PercentageTerm node) { heading('PercentageTerm', node); output.depth++; super.visitPercentageTerm(node); output.depth--; } @override void visitEmTerm(EmTerm node) { heading('EmTerm', node); output.depth++; super.visitEmTerm(node); output.depth--; } @override void visitExTerm(ExTerm node) { heading('ExTerm', node); output.depth++; super.visitExTerm(node); output.depth--; } @override void visitAngleTerm(AngleTerm node) { heading('AngleTerm', node); super.visitAngleTerm(node); } @override void visitTimeTerm(TimeTerm node) { heading('TimeTerm', node); super.visitTimeTerm(node); } @override void visitFreqTerm(FreqTerm node) { heading('FreqTerm', node); super.visitFreqTerm(node); } @override void visitFractionTerm(FractionTerm node) { heading('FractionTerm', node); output.depth++; super.visitFractionTerm(node); output.depth--; } @override void visitUriTerm(UriTerm node) { heading('UriTerm', node); output.depth++; super.visitUriTerm(node); output.depth--; } @override void visitFunctionTerm(FunctionTerm node) { heading('FunctionTerm', node); output.depth++; super.visitFunctionTerm(node); output.depth--; } @override void visitGroupTerm(GroupTerm node) { heading('GroupTerm', node); output.depth++; output.writeNodeList('grouped terms', node._terms); output.depth--; } @override void visitItemTerm(ItemTerm node) { heading('ItemTerm', node); super.visitItemTerm(node); } @override void visitIE8Term(IE8Term node) { heading('IE8Term', node); visitLiteralTerm(node); } @override void visitOperatorSlash(OperatorSlash node) { heading('OperatorSlash', node); } @override void visitOperatorComma(OperatorComma node) { heading('OperatorComma', node); } @override void visitOperatorPlus(OperatorPlus node) { heading('OperatorPlus', node); } @override void visitOperatorMinus(OperatorMinus node) { heading('OperatorMinus', node); } @override void visitVarUsage(VarUsage node) { heading('Var', node); output.depth++; output.write('usage ${node.name}'); output.writeNodeList('default values', node.defaultValues); output.depth--; } @override void visitExpressions(Expressions node) { heading('Expressions', node); output.depth++; output.writeNodeList('expressions', node.expressions); output.depth--; } @override void visitBinaryExpression(BinaryExpression node) { heading('BinaryExpression', node); // TODO(terry): TBD } @override void visitUnaryExpression(UnaryExpression node) { heading('UnaryExpression', node); // TODO(terry): TBD } @override void visitIdentifier(Identifier node) { heading('Identifier(${output.toValue(node.name)})', node); } @override void visitWildcard(Wildcard node) { heading('Wildcard(*)', node); } @override void visitDartStyleExpression(DartStyleExpression node) { heading('DartStyleExpression', node); } @override void visitFontExpression(FontExpression node) { heading('Dart Style FontExpression', node); } @override void visitBoxExpression(BoxExpression node) { heading('Dart Style BoxExpression', node); } @override void visitMarginExpression(MarginExpression node) { heading('Dart Style MarginExpression', node); } @override void visitBorderExpression(BorderExpression node) { heading('Dart Style BorderExpression', node); } @override void visitHeightExpression(HeightExpression node) { heading('Dart Style HeightExpression', node); } @override void visitPaddingExpression(PaddingExpression node) { heading('Dart Style PaddingExpression', node); } @override void visitWidthExpression(WidthExpression node) { heading('Dart Style WidthExpression', node); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/token_kind.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../parser.dart'; // TODO(terry): Need to be consistent with tokens either they're ASCII tokens // e.g., ASTERISK or they're CSS e.g., PSEUDO, COMBINATOR_*. class TokenKind { // Common shared tokens used in TokenizerBase. static const int UNUSED = 0; // Unused place holder... static const int END_OF_FILE = 1; // EOF static const int LPAREN = 2; // ( static const int RPAREN = 3; // ) static const int LBRACK = 4; // [ static const int RBRACK = 5; // ] static const int LBRACE = 6; // { static const int RBRACE = 7; // } static const int DOT = 8; // . static const int SEMICOLON = 9; // ; // Unique tokens for CSS. static const int AT = 10; // @ static const int HASH = 11; // # static const int PLUS = 12; // + static const int GREATER = 13; // > static const int TILDE = 14; // ~ static const int ASTERISK = 15; // * static const int NAMESPACE = 16; // | static const int COLON = 17; // : static const int PRIVATE_NAME = 18; // _ prefix private class or id static const int COMMA = 19; // , static const int SPACE = 20; static const int TAB = 21; // /t static const int NEWLINE = 22; // /n static const int RETURN = 23; // /r static const int PERCENT = 24; // % static const int SINGLE_QUOTE = 25; // ' static const int DOUBLE_QUOTE = 26; // " static const int SLASH = 27; // / static const int EQUALS = 28; // = static const int CARET = 30; // ^ static const int DOLLAR = 31; // $ static const int LESS = 32; // < static const int BANG = 33; // ! static const int MINUS = 34; // - static const int BACKSLASH = 35; // \ static const int AMPERSAND = 36; // & // WARNING: Tokens from this point and above must have the corresponding ASCII // character in the TokenChar list at the bottom of this file. The // order of the above tokens should be the same order as TokenChar. /// [TokenKind] representing integer tokens. static const int INTEGER = 60; /// [TokenKind] representing hex integer tokens. static const int HEX_INTEGER = 61; /// [TokenKind] representing double tokens. static const int DOUBLE = 62; /// [TokenKind] representing whitespace tokens. static const int WHITESPACE = 63; /// [TokenKind] representing comment tokens. static const int COMMENT = 64; /// [TokenKind] representing error tokens. static const int ERROR = 65; /// [TokenKind] representing incomplete string tokens. static const int INCOMPLETE_STRING = 66; /// [TokenKind] representing incomplete comment tokens. static const int INCOMPLETE_COMMENT = 67; static const int VAR_DEFINITION = 400; // var-NNN-NNN static const int VAR_USAGE = 401; // var(NNN-NNN [,default]) // Synthesized Tokens (no character associated with TOKEN). static const int STRING = 500; static const int STRING_PART = 501; static const int NUMBER = 502; static const int HEX_NUMBER = 503; static const int HTML_COMMENT = 504; // <!-- static const int IMPORTANT = 505; // !important static const int CDATA_START = 506; // <![CDATA[ static const int CDATA_END = 507; // ]]> // U+uNumber[-U+uNumber] // uNumber = 0..10FFFF | ?[?]* static const int UNICODE_RANGE = 508; static const int HEX_RANGE = 509; // ? in the hex range static const int IDENTIFIER = 511; // Uniquely synthesized tokens for CSS. static const int SELECTOR_EXPRESSION = 512; static const int COMBINATOR_NONE = 513; static const int COMBINATOR_DESCENDANT = 514; // Space combinator static const int COMBINATOR_PLUS = 515; // + combinator static const int COMBINATOR_GREATER = 516; // > combinator static const int COMBINATOR_TILDE = 517; // ~ combinator static const int UNARY_OP_NONE = 518; // No unary operator present. // Attribute match types: static const int INCLUDES = 530; // '~=' static const int DASH_MATCH = 531; // '|=' static const int PREFIX_MATCH = 532; // '^=' static const int SUFFIX_MATCH = 533; // '$=' static const int SUBSTRING_MATCH = 534; // '*=' static const int NO_MATCH = 535; // No operator. // Unit types: static const int UNIT_EM = 600; static const int UNIT_EX = 601; static const int UNIT_LENGTH_PX = 602; static const int UNIT_LENGTH_CM = 603; static const int UNIT_LENGTH_MM = 604; static const int UNIT_LENGTH_IN = 605; static const int UNIT_LENGTH_PT = 606; static const int UNIT_LENGTH_PC = 607; static const int UNIT_ANGLE_DEG = 608; static const int UNIT_ANGLE_RAD = 609; static const int UNIT_ANGLE_GRAD = 610; static const int UNIT_ANGLE_TURN = 611; static const int UNIT_TIME_MS = 612; static const int UNIT_TIME_S = 613; static const int UNIT_FREQ_HZ = 614; static const int UNIT_FREQ_KHZ = 615; static const int UNIT_PERCENT = 616; static const int UNIT_FRACTION = 617; static const int UNIT_RESOLUTION_DPI = 618; static const int UNIT_RESOLUTION_DPCM = 619; static const int UNIT_RESOLUTION_DPPX = 620; static const int UNIT_CH = 621; // Measure of "0" U+0030 glyph. static const int UNIT_REM = 622; // computed value ‘font-size’ on root elem. static const int UNIT_VIEWPORT_VW = 623; static const int UNIT_VIEWPORT_VH = 624; static const int UNIT_VIEWPORT_VMIN = 625; static const int UNIT_VIEWPORT_VMAX = 626; // Directives (@nnnn) static const int DIRECTIVE_NONE = 640; static const int DIRECTIVE_IMPORT = 641; static const int DIRECTIVE_MEDIA = 642; static const int DIRECTIVE_PAGE = 643; static const int DIRECTIVE_CHARSET = 644; static const int DIRECTIVE_STYLET = 645; static const int DIRECTIVE_KEYFRAMES = 646; static const int DIRECTIVE_WEB_KIT_KEYFRAMES = 647; static const int DIRECTIVE_MOZ_KEYFRAMES = 648; static const int DIRECTIVE_MS_KEYFRAMES = 649; static const int DIRECTIVE_O_KEYFRAMES = 650; static const int DIRECTIVE_FONTFACE = 651; static const int DIRECTIVE_NAMESPACE = 652; static const int DIRECTIVE_HOST = 653; static const int DIRECTIVE_MIXIN = 654; static const int DIRECTIVE_INCLUDE = 655; static const int DIRECTIVE_CONTENT = 656; static const int DIRECTIVE_EXTEND = 657; static const int DIRECTIVE_MOZ_DOCUMENT = 658; static const int DIRECTIVE_SUPPORTS = 659; static const int DIRECTIVE_VIEWPORT = 660; static const int DIRECTIVE_MS_VIEWPORT = 661; // Media query operators static const int MEDIA_OP_ONLY = 665; // Unary. static const int MEDIA_OP_NOT = 666; // Unary. static const int MEDIA_OP_AND = 667; // Binary. // Directives inside of a @page (margin sym). static const int MARGIN_DIRECTIVE_TOPLEFTCORNER = 670; static const int MARGIN_DIRECTIVE_TOPLEFT = 671; static const int MARGIN_DIRECTIVE_TOPCENTER = 672; static const int MARGIN_DIRECTIVE_TOPRIGHT = 673; static const int MARGIN_DIRECTIVE_TOPRIGHTCORNER = 674; static const int MARGIN_DIRECTIVE_BOTTOMLEFTCORNER = 675; static const int MARGIN_DIRECTIVE_BOTTOMLEFT = 676; static const int MARGIN_DIRECTIVE_BOTTOMCENTER = 677; static const int MARGIN_DIRECTIVE_BOTTOMRIGHT = 678; static const int MARGIN_DIRECTIVE_BOTTOMRIGHTCORNER = 679; static const int MARGIN_DIRECTIVE_LEFTTOP = 680; static const int MARGIN_DIRECTIVE_LEFTMIDDLE = 681; static const int MARGIN_DIRECTIVE_LEFTBOTTOM = 682; static const int MARGIN_DIRECTIVE_RIGHTTOP = 683; static const int MARGIN_DIRECTIVE_RIGHTMIDDLE = 684; static const int MARGIN_DIRECTIVE_RIGHTBOTTOM = 685; // Simple selector type. static const int CLASS_NAME = 700; // .class static const int ELEMENT_NAME = 701; // tagName static const int HASH_NAME = 702; // #elementId static const int ATTRIBUTE_NAME = 703; // [attrib] static const int PSEUDO_ELEMENT_NAME = 704; // ::pseudoElement static const int PSEUDO_CLASS_NAME = 705; // :pseudoClass static const int NEGATION = 706; // NOT static const List<Map<String, dynamic>> _DIRECTIVES = [ {'type': TokenKind.DIRECTIVE_IMPORT, 'value': 'import'}, {'type': TokenKind.DIRECTIVE_MEDIA, 'value': 'media'}, {'type': TokenKind.DIRECTIVE_PAGE, 'value': 'page'}, {'type': TokenKind.DIRECTIVE_CHARSET, 'value': 'charset'}, {'type': TokenKind.DIRECTIVE_STYLET, 'value': 'stylet'}, {'type': TokenKind.DIRECTIVE_KEYFRAMES, 'value': 'keyframes'}, { 'type': TokenKind.DIRECTIVE_WEB_KIT_KEYFRAMES, 'value': '-webkit-keyframes' }, {'type': TokenKind.DIRECTIVE_MOZ_KEYFRAMES, 'value': '-moz-keyframes'}, {'type': TokenKind.DIRECTIVE_MS_KEYFRAMES, 'value': '-ms-keyframes'}, {'type': TokenKind.DIRECTIVE_O_KEYFRAMES, 'value': '-o-keyframes'}, {'type': TokenKind.DIRECTIVE_FONTFACE, 'value': 'font-face'}, {'type': TokenKind.DIRECTIVE_NAMESPACE, 'value': 'namespace'}, {'type': TokenKind.DIRECTIVE_HOST, 'value': 'host'}, {'type': TokenKind.DIRECTIVE_MIXIN, 'value': 'mixin'}, {'type': TokenKind.DIRECTIVE_INCLUDE, 'value': 'include'}, {'type': TokenKind.DIRECTIVE_CONTENT, 'value': 'content'}, {'type': TokenKind.DIRECTIVE_EXTEND, 'value': 'extend'}, {'type': TokenKind.DIRECTIVE_MOZ_DOCUMENT, 'value': '-moz-document'}, {'type': TokenKind.DIRECTIVE_SUPPORTS, 'value': 'supports'}, {'type': TokenKind.DIRECTIVE_VIEWPORT, 'value': 'viewport'}, {'type': TokenKind.DIRECTIVE_MS_VIEWPORT, 'value': '-ms-viewport'}, ]; static const List<Map<String, dynamic>> MEDIA_OPERATORS = [ {'type': TokenKind.MEDIA_OP_ONLY, 'value': 'only'}, {'type': TokenKind.MEDIA_OP_NOT, 'value': 'not'}, {'type': TokenKind.MEDIA_OP_AND, 'value': 'and'}, ]; static const List<Map<String, dynamic>> MARGIN_DIRECTIVES = [ { 'type': TokenKind.MARGIN_DIRECTIVE_TOPLEFTCORNER, 'value': 'top-left-corner' }, {'type': TokenKind.MARGIN_DIRECTIVE_TOPLEFT, 'value': 'top-left'}, {'type': TokenKind.MARGIN_DIRECTIVE_TOPCENTER, 'value': 'top-center'}, {'type': TokenKind.MARGIN_DIRECTIVE_TOPRIGHT, 'value': 'top-right'}, { 'type': TokenKind.MARGIN_DIRECTIVE_TOPRIGHTCORNER, 'value': 'top-right-corner' }, { 'type': TokenKind.MARGIN_DIRECTIVE_BOTTOMLEFTCORNER, 'value': 'bottom-left-corner' }, {'type': TokenKind.MARGIN_DIRECTIVE_BOTTOMLEFT, 'value': 'bottom-left'}, {'type': TokenKind.MARGIN_DIRECTIVE_BOTTOMCENTER, 'value': 'bottom-center'}, {'type': TokenKind.MARGIN_DIRECTIVE_BOTTOMRIGHT, 'value': 'bottom-right'}, { 'type': TokenKind.MARGIN_DIRECTIVE_BOTTOMRIGHTCORNER, 'value': 'bottom-right-corner' }, {'type': TokenKind.MARGIN_DIRECTIVE_LEFTTOP, 'value': 'left-top'}, {'type': TokenKind.MARGIN_DIRECTIVE_LEFTMIDDLE, 'value': 'left-middle'}, {'type': TokenKind.MARGIN_DIRECTIVE_LEFTBOTTOM, 'value': 'right-bottom'}, {'type': TokenKind.MARGIN_DIRECTIVE_RIGHTTOP, 'value': 'right-top'}, {'type': TokenKind.MARGIN_DIRECTIVE_RIGHTMIDDLE, 'value': 'right-middle'}, {'type': TokenKind.MARGIN_DIRECTIVE_RIGHTBOTTOM, 'value': 'right-bottom'}, ]; static const List<Map> _UNITS = [ {'unit': TokenKind.UNIT_EM, 'value': 'em'}, {'unit': TokenKind.UNIT_EX, 'value': 'ex'}, {'unit': TokenKind.UNIT_LENGTH_PX, 'value': 'px'}, {'unit': TokenKind.UNIT_LENGTH_CM, 'value': 'cm'}, {'unit': TokenKind.UNIT_LENGTH_MM, 'value': 'mm'}, {'unit': TokenKind.UNIT_LENGTH_IN, 'value': 'in'}, {'unit': TokenKind.UNIT_LENGTH_PT, 'value': 'pt'}, {'unit': TokenKind.UNIT_LENGTH_PC, 'value': 'pc'}, {'unit': TokenKind.UNIT_ANGLE_DEG, 'value': 'deg'}, {'unit': TokenKind.UNIT_ANGLE_RAD, 'value': 'rad'}, {'unit': TokenKind.UNIT_ANGLE_GRAD, 'value': 'grad'}, {'unit': TokenKind.UNIT_ANGLE_TURN, 'value': 'turn'}, {'unit': TokenKind.UNIT_TIME_MS, 'value': 'ms'}, {'unit': TokenKind.UNIT_TIME_S, 'value': 's'}, {'unit': TokenKind.UNIT_FREQ_HZ, 'value': 'hz'}, {'unit': TokenKind.UNIT_FREQ_KHZ, 'value': 'khz'}, {'unit': TokenKind.UNIT_FRACTION, 'value': 'fr'}, {'unit': TokenKind.UNIT_RESOLUTION_DPI, 'value': 'dpi'}, {'unit': TokenKind.UNIT_RESOLUTION_DPCM, 'value': 'dpcm'}, {'unit': TokenKind.UNIT_RESOLUTION_DPPX, 'value': 'dppx'}, {'unit': TokenKind.UNIT_CH, 'value': 'ch'}, {'unit': TokenKind.UNIT_REM, 'value': 'rem'}, {'unit': TokenKind.UNIT_VIEWPORT_VW, 'value': 'vw'}, {'unit': TokenKind.UNIT_VIEWPORT_VH, 'value': 'vh'}, {'unit': TokenKind.UNIT_VIEWPORT_VMIN, 'value': 'vmin'}, {'unit': TokenKind.UNIT_VIEWPORT_VMAX, 'value': 'vmax'}, ]; // Some more constants: static const int ASCII_UPPER_A = 65; // ASCII value for uppercase A static const int ASCII_UPPER_Z = 90; // ASCII value for uppercase Z // Extended color keywords: static const List<Map> _EXTENDED_COLOR_NAMES = [ {'name': 'aliceblue', 'value': 0xF08FF}, {'name': 'antiquewhite', 'value': 0xFAEBD7}, {'name': 'aqua', 'value': 0x00FFFF}, {'name': 'aquamarine', 'value': 0x7FFFD4}, {'name': 'azure', 'value': 0xF0FFFF}, {'name': 'beige', 'value': 0xF5F5DC}, {'name': 'bisque', 'value': 0xFFE4C4}, {'name': 'black', 'value': 0x000000}, {'name': 'blanchedalmond', 'value': 0xFFEBCD}, {'name': 'blue', 'value': 0x0000FF}, {'name': 'blueviolet', 'value': 0x8A2BE2}, {'name': 'brown', 'value': 0xA52A2A}, {'name': 'burlywood', 'value': 0xDEB887}, {'name': 'cadetblue', 'value': 0x5F9EA0}, {'name': 'chartreuse', 'value': 0x7FFF00}, {'name': 'chocolate', 'value': 0xD2691E}, {'name': 'coral', 'value': 0xFF7F50}, {'name': 'cornflowerblue', 'value': 0x6495ED}, {'name': 'cornsilk', 'value': 0xFFF8DC}, {'name': 'crimson', 'value': 0xDC143C}, {'name': 'cyan', 'value': 0x00FFFF}, {'name': 'darkblue', 'value': 0x00008B}, {'name': 'darkcyan', 'value': 0x008B8B}, {'name': 'darkgoldenrod', 'value': 0xB8860B}, {'name': 'darkgray', 'value': 0xA9A9A9}, {'name': 'darkgreen', 'value': 0x006400}, {'name': 'darkgrey', 'value': 0xA9A9A9}, {'name': 'darkkhaki', 'value': 0xBDB76B}, {'name': 'darkmagenta', 'value': 0x8B008B}, {'name': 'darkolivegreen', 'value': 0x556B2F}, {'name': 'darkorange', 'value': 0xFF8C00}, {'name': 'darkorchid', 'value': 0x9932CC}, {'name': 'darkred', 'value': 0x8B0000}, {'name': 'darksalmon', 'value': 0xE9967A}, {'name': 'darkseagreen', 'value': 0x8FBC8F}, {'name': 'darkslateblue', 'value': 0x483D8B}, {'name': 'darkslategray', 'value': 0x2F4F4F}, {'name': 'darkslategrey', 'value': 0x2F4F4F}, {'name': 'darkturquoise', 'value': 0x00CED1}, {'name': 'darkviolet', 'value': 0x9400D3}, {'name': 'deeppink', 'value': 0xFF1493}, {'name': 'deepskyblue', 'value': 0x00BFFF}, {'name': 'dimgray', 'value': 0x696969}, {'name': 'dimgrey', 'value': 0x696969}, {'name': 'dodgerblue', 'value': 0x1E90FF}, {'name': 'firebrick', 'value': 0xB22222}, {'name': 'floralwhite', 'value': 0xFFFAF0}, {'name': 'forestgreen', 'value': 0x228B22}, {'name': 'fuchsia', 'value': 0xFF00FF}, {'name': 'gainsboro', 'value': 0xDCDCDC}, {'name': 'ghostwhite', 'value': 0xF8F8FF}, {'name': 'gold', 'value': 0xFFD700}, {'name': 'goldenrod', 'value': 0xDAA520}, {'name': 'gray', 'value': 0x808080}, {'name': 'green', 'value': 0x008000}, {'name': 'greenyellow', 'value': 0xADFF2F}, {'name': 'grey', 'value': 0x808080}, {'name': 'honeydew', 'value': 0xF0FFF0}, {'name': 'hotpink', 'value': 0xFF69B4}, {'name': 'indianred', 'value': 0xCD5C5C}, {'name': 'indigo', 'value': 0x4B0082}, {'name': 'ivory', 'value': 0xFFFFF0}, {'name': 'khaki', 'value': 0xF0E68C}, {'name': 'lavender', 'value': 0xE6E6FA}, {'name': 'lavenderblush', 'value': 0xFFF0F5}, {'name': 'lawngreen', 'value': 0x7CFC00}, {'name': 'lemonchiffon', 'value': 0xFFFACD}, {'name': 'lightblue', 'value': 0xADD8E6}, {'name': 'lightcoral', 'value': 0xF08080}, {'name': 'lightcyan', 'value': 0xE0FFFF}, {'name': 'lightgoldenrodyellow', 'value': 0xFAFAD2}, {'name': 'lightgray', 'value': 0xD3D3D3}, {'name': 'lightgreen', 'value': 0x90EE90}, {'name': 'lightgrey', 'value': 0xD3D3D3}, {'name': 'lightpink', 'value': 0xFFB6C1}, {'name': 'lightsalmon', 'value': 0xFFA07A}, {'name': 'lightseagreen', 'value': 0x20B2AA}, {'name': 'lightskyblue', 'value': 0x87CEFA}, {'name': 'lightslategray', 'value': 0x778899}, {'name': 'lightslategrey', 'value': 0x778899}, {'name': 'lightsteelblue', 'value': 0xB0C4DE}, {'name': 'lightyellow', 'value': 0xFFFFE0}, {'name': 'lime', 'value': 0x00FF00}, {'name': 'limegreen', 'value': 0x32CD32}, {'name': 'linen', 'value': 0xFAF0E6}, {'name': 'magenta', 'value': 0xFF00FF}, {'name': 'maroon', 'value': 0x800000}, {'name': 'mediumaquamarine', 'value': 0x66CDAA}, {'name': 'mediumblue', 'value': 0x0000CD}, {'name': 'mediumorchid', 'value': 0xBA55D3}, {'name': 'mediumpurple', 'value': 0x9370DB}, {'name': 'mediumseagreen', 'value': 0x3CB371}, {'name': 'mediumslateblue', 'value': 0x7B68EE}, {'name': 'mediumspringgreen', 'value': 0x00FA9A}, {'name': 'mediumturquoise', 'value': 0x48D1CC}, {'name': 'mediumvioletred', 'value': 0xC71585}, {'name': 'midnightblue', 'value': 0x191970}, {'name': 'mintcream', 'value': 0xF5FFFA}, {'name': 'mistyrose', 'value': 0xFFE4E1}, {'name': 'moccasin', 'value': 0xFFE4B5}, {'name': 'navajowhite', 'value': 0xFFDEAD}, {'name': 'navy', 'value': 0x000080}, {'name': 'oldlace', 'value': 0xFDF5E6}, {'name': 'olive', 'value': 0x808000}, {'name': 'olivedrab', 'value': 0x6B8E23}, {'name': 'orange', 'value': 0xFFA500}, {'name': 'orangered', 'value': 0xFF4500}, {'name': 'orchid', 'value': 0xDA70D6}, {'name': 'palegoldenrod', 'value': 0xEEE8AA}, {'name': 'palegreen', 'value': 0x98FB98}, {'name': 'paleturquoise', 'value': 0xAFEEEE}, {'name': 'palevioletred', 'value': 0xDB7093}, {'name': 'papayawhip', 'value': 0xFFEFD5}, {'name': 'peachpuff', 'value': 0xFFDAB9}, {'name': 'peru', 'value': 0xCD853F}, {'name': 'pink', 'value': 0xFFC0CB}, {'name': 'plum', 'value': 0xDDA0DD}, {'name': 'powderblue', 'value': 0xB0E0E6}, {'name': 'purple', 'value': 0x800080}, {'name': 'red', 'value': 0xFF0000}, {'name': 'rosybrown', 'value': 0xBC8F8F}, {'name': 'royalblue', 'value': 0x4169E1}, {'name': 'saddlebrown', 'value': 0x8B4513}, {'name': 'salmon', 'value': 0xFA8072}, {'name': 'sandybrown', 'value': 0xF4A460}, {'name': 'seagreen', 'value': 0x2E8B57}, {'name': 'seashell', 'value': 0xFFF5EE}, {'name': 'sienna', 'value': 0xA0522D}, {'name': 'silver', 'value': 0xC0C0C0}, {'name': 'skyblue', 'value': 0x87CEEB}, {'name': 'slateblue', 'value': 0x6A5ACD}, {'name': 'slategray', 'value': 0x708090}, {'name': 'slategrey', 'value': 0x708090}, {'name': 'snow', 'value': 0xFFFAFA}, {'name': 'springgreen', 'value': 0x00FF7F}, {'name': 'steelblue', 'value': 0x4682B4}, {'name': 'tan', 'value': 0xD2B48C}, {'name': 'teal', 'value': 0x008080}, {'name': 'thistle', 'value': 0xD8BFD8}, {'name': 'tomato', 'value': 0xFF6347}, {'name': 'turquoise', 'value': 0x40E0D0}, {'name': 'violet', 'value': 0xEE82EE}, {'name': 'wheat', 'value': 0xF5DEB3}, {'name': 'white', 'value': 0xFFFFFF}, {'name': 'whitesmoke', 'value': 0xF5F5F5}, {'name': 'yellow', 'value': 0xFFFF00}, {'name': 'yellowgreen', 'value': 0x9ACD32}, ]; // TODO(terry): Should used Dart mirroring for parameter values and types // especially for enumeration (e.g., counter's second parameter // is list-style-type which is an enumerated list for ordering // of a list 'circle', 'decimal', 'lower-roman', 'square', etc. // see http://www.w3schools.com/cssref/pr_list-style-type.asp // for list of possible values. /// Check if name is a pre-defined CSS name. Used by error handler to report /// if name is unknown or used improperly. static bool isPredefinedName(String name) { var nameLen = name.length; // TODO(terry): Add more pre-defined names (hidden, bolder, inherit, etc.). if (matchUnits(name, 0, nameLen) == -1 || matchDirectives(name, 0, nameLen) == -1 || matchMarginDirectives(name, 0, nameLen) == -1 || matchColorName(name) == null) { return false; } return true; } /// Return the token that matches the unit ident found. static int matchList( var identList, String tokenField, String text, int offset, int length) { for (final entry in identList) { String ident = entry['value']; if (length == ident.length) { var idx = offset; var match = true; for (var i = 0; i < ident.length; i++) { var identChar = ident.codeUnitAt(i); var char = text.codeUnitAt(idx++); // Compare lowercase to lowercase then check if char is uppercase. match = match && (char == identChar || ((char >= ASCII_UPPER_A && char <= ASCII_UPPER_Z) && (char + 32) == identChar)); if (!match) { break; } } if (match) { // Completely matched; return the token for this unit. return entry[tokenField]; } } } return -1; // Not a unit token. } /// Return the token that matches the unit ident found. static int matchUnits(String text, int offset, int length) { return matchList(_UNITS, 'unit', text, offset, length); } /// Return the token that matches the directive name found. static int matchDirectives(String text, int offset, int length) { return matchList(_DIRECTIVES, 'type', text, offset, length); } /// Return the token that matches the margin directive name found. static int matchMarginDirectives(String text, int offset, int length) { return matchList(MARGIN_DIRECTIVES, 'type', text, offset, length); } /// Return the token that matches the media operator found. static int matchMediaOperator(String text, int offset, int length) { return matchList(MEDIA_OPERATORS, 'type', text, offset, length); } static String idToValue(var identList, int tokenId) { for (var entry in identList) { if (tokenId == entry['type']) { return entry['value']; } } return null; } /// Return the unit token as its pretty name. static String unitToString(int unitTokenToFind) { if (unitTokenToFind == TokenKind.PERCENT) { return '%'; } else { for (final entry in _UNITS) { int unit = entry['unit']; if (unit == unitTokenToFind) { return entry['value']; } } } return '<BAD UNIT>'; // Not a unit token. } /// Match color name, case insensitive match and return the associated color /// entry from _EXTENDED_COLOR_NAMES list, return [:null:] if not found. static Map matchColorName(String text) { var name = text.toLowerCase(); return _EXTENDED_COLOR_NAMES.firstWhere((e) => e['name'] == name, orElse: () => null); } /// Return RGB value as [int] from a color entry in _EXTENDED_COLOR_NAMES. static int colorValue(Map entry) { assert(entry != null); return entry['value']; } static String hexToColorName(hexValue) { for (final entry in _EXTENDED_COLOR_NAMES) { if (entry['value'] == hexValue) { return entry['name']; } } return null; } static String decimalToHex(int number, [int minDigits = 1]) { final _HEX_DIGITS = '0123456789abcdef'; var result = <String>[]; var dividend = number >> 4; var remain = number % 16; result.add(_HEX_DIGITS[remain]); while (dividend != 0) { remain = dividend % 16; dividend >>= 4; result.add(_HEX_DIGITS[remain]); } var invertResult = StringBuffer(); var paddings = minDigits - result.length; while (paddings-- > 0) { invertResult.write('0'); } for (var i = result.length - 1; i >= 0; i--) { invertResult.write(result[i]); } return invertResult.toString(); } static String kindToString(int kind) { switch (kind) { case TokenKind.UNUSED: return 'ERROR'; case TokenKind.END_OF_FILE: return 'end of file'; case TokenKind.LPAREN: return '('; case TokenKind.RPAREN: return ')'; case TokenKind.LBRACK: return '['; case TokenKind.RBRACK: return ']'; case TokenKind.LBRACE: return '{'; case TokenKind.RBRACE: return '}'; case TokenKind.DOT: return '.'; case TokenKind.SEMICOLON: return ';'; case TokenKind.AT: return '@'; case TokenKind.HASH: return '#'; case TokenKind.PLUS: return '+'; case TokenKind.GREATER: return '>'; case TokenKind.TILDE: return '~'; case TokenKind.ASTERISK: return '*'; case TokenKind.NAMESPACE: return '|'; case TokenKind.COLON: return ':'; case TokenKind.PRIVATE_NAME: return '_'; case TokenKind.COMMA: return ','; case TokenKind.SPACE: return ' '; case TokenKind.TAB: return '\t'; case TokenKind.NEWLINE: return '\n'; case TokenKind.RETURN: return '\r'; case TokenKind.PERCENT: return '%'; case TokenKind.SINGLE_QUOTE: return "'"; case TokenKind.DOUBLE_QUOTE: return '\"'; case TokenKind.SLASH: return '/'; case TokenKind.EQUALS: return '='; case TokenKind.CARET: return '^'; case TokenKind.DOLLAR: return '\$'; case TokenKind.LESS: return '<'; case TokenKind.BANG: return '!'; case TokenKind.MINUS: return '-'; case TokenKind.BACKSLASH: return '\\'; default: throw 'Unknown TOKEN'; } } static bool isKindIdentifier(int kind) { switch (kind) { // Synthesized tokens. case TokenKind.DIRECTIVE_IMPORT: case TokenKind.DIRECTIVE_MEDIA: case TokenKind.DIRECTIVE_PAGE: case TokenKind.DIRECTIVE_CHARSET: case TokenKind.DIRECTIVE_STYLET: case TokenKind.DIRECTIVE_KEYFRAMES: case TokenKind.DIRECTIVE_WEB_KIT_KEYFRAMES: case TokenKind.DIRECTIVE_MOZ_KEYFRAMES: case TokenKind.DIRECTIVE_MS_KEYFRAMES: case TokenKind.DIRECTIVE_O_KEYFRAMES: case TokenKind.DIRECTIVE_FONTFACE: case TokenKind.DIRECTIVE_NAMESPACE: case TokenKind.DIRECTIVE_HOST: case TokenKind.DIRECTIVE_MIXIN: case TokenKind.DIRECTIVE_INCLUDE: case TokenKind.DIRECTIVE_CONTENT: case TokenKind.UNIT_EM: case TokenKind.UNIT_EX: case TokenKind.UNIT_LENGTH_PX: case TokenKind.UNIT_LENGTH_CM: case TokenKind.UNIT_LENGTH_MM: case TokenKind.UNIT_LENGTH_IN: case TokenKind.UNIT_LENGTH_PT: case TokenKind.UNIT_LENGTH_PC: case TokenKind.UNIT_ANGLE_DEG: case TokenKind.UNIT_ANGLE_RAD: case TokenKind.UNIT_ANGLE_GRAD: case TokenKind.UNIT_TIME_MS: case TokenKind.UNIT_TIME_S: case TokenKind.UNIT_FREQ_HZ: case TokenKind.UNIT_FREQ_KHZ: case TokenKind.UNIT_FRACTION: return true; default: return false; } } static bool isIdentifier(int kind) { return kind == IDENTIFIER; } } // Note: these names should match TokenKind names class TokenChar { static const int UNUSED = -1; static const int END_OF_FILE = 0; static const int LPAREN = 0x28; // "(".codeUnitAt(0) static const int RPAREN = 0x29; // ")".codeUnitAt(0) static const int LBRACK = 0x5b; // "[".codeUnitAt(0) static const int RBRACK = 0x5d; // "]".codeUnitAt(0) static const int LBRACE = 0x7b; // "{".codeUnitAt(0) static const int RBRACE = 0x7d; // "}".codeUnitAt(0) static const int DOT = 0x2e; // ".".codeUnitAt(0) static const int SEMICOLON = 0x3b; // ";".codeUnitAt(0) static const int AT = 0x40; // "@".codeUnitAt(0) static const int HASH = 0x23; // "#".codeUnitAt(0) static const int PLUS = 0x2b; // "+".codeUnitAt(0) static const int GREATER = 0x3e; // ">".codeUnitAt(0) static const int TILDE = 0x7e; // "~".codeUnitAt(0) static const int ASTERISK = 0x2a; // "*".codeUnitAt(0) static const int NAMESPACE = 0x7c; // "|".codeUnitAt(0) static const int COLON = 0x3a; // ":".codeUnitAt(0) static const int PRIVATE_NAME = 0x5f; // "_".codeUnitAt(0) static const int COMMA = 0x2c; // ",".codeUnitAt(0) static const int SPACE = 0x20; // " ".codeUnitAt(0) static const int TAB = 0x9; // "\t".codeUnitAt(0) static const int NEWLINE = 0xa; // "\n".codeUnitAt(0) static const int RETURN = 0xd; // "\r".codeUnitAt(0) static const int BACKSPACE = 0x8; // "/b".codeUnitAt(0) static const int FF = 0xc; // "/f".codeUnitAt(0) static const int VT = 0xb; // "/v".codeUnitAt(0) static const int PERCENT = 0x25; // "%".codeUnitAt(0) static const int SINGLE_QUOTE = 0x27; // "'".codeUnitAt(0) static const int DOUBLE_QUOTE = 0x22; // '"'.codeUnitAt(0) static const int SLASH = 0x2f; // "/".codeUnitAt(0) static const int EQUALS = 0x3d; // "=".codeUnitAt(0) static const int OR = 0x7c; // "|".codeUnitAt(0) static const int CARET = 0x5e; // "^".codeUnitAt(0) static const int DOLLAR = 0x24; // "\$".codeUnitAt(0) static const int LESS = 0x3c; // "<".codeUnitAt(0) static const int BANG = 0x21; // "!".codeUnitAt(0) static const int MINUS = 0x2d; // "-".codeUnitAt(0) static const int BACKSLASH = 0x5c; // "\".codeUnitAt(0) static const int AMPERSAND = 0x26; // "&".codeUnitAt(0) }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/messages.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:source_span/source_span.dart'; import 'preprocessor_options.dart'; enum MessageLevel { info, warning, severe } // TODO(terry): Remove the global messages, use some object that tracks // compilation state. /// The global [Messages] for tracking info/warnings/messages. Messages messages; // Color constants used for generating messages. const _greenColor = '\u001b[32m'; const _redColor = '\u001b[31m'; const _magentaColor = '\u001b[35m'; const _noColor = '\u001b[0m'; /// Map between error levels and their display color. const Map<MessageLevel, String> _errorColors = { MessageLevel.severe: _redColor, MessageLevel.warning: _magentaColor, MessageLevel.info: _greenColor, }; /// Map between error levels and their friendly name. const Map<MessageLevel, String> _errorLabel = { MessageLevel.severe: 'error', MessageLevel.warning: 'warning', MessageLevel.info: 'info', }; /// A single message from the compiler. class Message { final MessageLevel level; final String message; final SourceSpan span; final bool useColors; Message(this.level, this.message, {this.span, this.useColors = false}); @override String toString() { var output = StringBuffer(); var colors = useColors && _errorColors.containsKey(level); var levelColor = colors ? _errorColors[level] : null; if (colors) output.write(levelColor); output..write(_errorLabel[level])..write(' '); if (colors) output.write(_noColor); if (span == null) { output.write(message); } else { output.write('on '); output.write(span.message(message, color: levelColor)); } return output.toString(); } } /// This class tracks and prints information, warnings, and errors emitted by /// the compiler. class Messages { /// Called on every error. Set to blank function to supress printing. final void Function(Message obj) printHandler; final PreprocessorOptions options; final List<Message> messages = <Message>[]; Messages({PreprocessorOptions options, this.printHandler = print}) : options = options ?? PreprocessorOptions(); /// Report a compile-time CSS error. void error(String message, SourceSpan span) { var msg = Message(MessageLevel.severe, message, span: span, useColors: options.useColors); messages.add(msg); printHandler(msg); } /// Report a compile-time CSS warning. void warning(String message, SourceSpan span) { if (options.warningsAsErrors) { error(message, span); } else { var msg = Message(MessageLevel.warning, message, span: span, useColors: options.useColors); messages.add(msg); } } /// Report and informational message about what the compiler is doing. void info(String message, SourceSpan span) { var msg = Message(MessageLevel.info, message, span: span, useColors: options.useColors); messages.add(msg); if (options.verbose) printHandler(msg); } /// Merge [newMessages] to this message lsit. void mergeMessages(Messages newMessages) { messages.addAll(newMessages.messages); newMessages.messages .where((message) => message.level == MessageLevel.severe || options.verbose) .forEach(printHandler); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/token.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../parser.dart'; /// A single token in the Dart language. class Token { /// A member of [TokenKind] specifying what kind of token this is. final int kind; /// The location where this token was parsed from. final FileSpan span; /// The start offset of this token. int get start => span.start.offset; /// The end offset of this token. int get end => span.end.offset; /// Returns the source text corresponding to this [Token]. String get text => span.text; Token(this.kind, this.span); /// Returns a pretty representation of this token for error messages. @override String toString() { var kindText = TokenKind.kindToString(kind); var actualText = text.trim(); if (kindText != actualText) { if (actualText.length > 10) { actualText = '${actualText.substring(0, 8)}...'; } return '$kindText($actualText)'; } else { return kindText; } } } /// A token containing a parsed literal value. class LiteralToken extends Token { dynamic value; LiteralToken(int kind, FileSpan span, this.value) : super(kind, span); } /// A token containing error information. class ErrorToken extends Token { String message; ErrorToken(int kind, FileSpan span, this.message) : super(kind, span); } /// CSS ident-token. /// /// See <http://dev.w3.org/csswg/css-syntax/#typedef-ident-token> and /// <http://dev.w3.org/csswg/css-syntax/#ident-token-diagram>. class IdentifierToken extends Token { @override final String text; IdentifierToken(this.text, int kind, FileSpan span) : super(kind, span); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/polyfill.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. part of '../parser.dart'; /// CSS polyfill emits CSS to be understood by older parsers that which do not /// understand (var, calc, etc.). class PolyFill { final Messages _messages; Map<String, VarDefinition> _allVarDefinitions = <String, VarDefinition>{}; Set<StyleSheet> allStyleSheets = <StyleSheet>{}; /// [_pseudoElements] list of known pseudo attributes found in HTML, any /// CSS pseudo-elements 'name::custom-element' is mapped to the manged name /// associated with the pseudo-element key. PolyFill(this._messages); /// Run the analyzer on every file that is a style sheet or any component that /// has a style tag. void process(StyleSheet styleSheet, {List<StyleSheet> includes}) { if (includes != null) { processVarDefinitions(includes); } processVars(styleSheet); // Remove all var definitions for this style sheet. _RemoveVarDefinitions().visitTree(styleSheet); } /// Process all includes looking for var definitions. void processVarDefinitions(List<StyleSheet> includes) { for (var include in includes) { _allVarDefinitions = (_VarDefinitionsIncludes(_allVarDefinitions) ..visitTree(include)) .varDefs; } } void processVars(StyleSheet styleSheet) { // Build list of all var definitions. var mainStyleSheetVarDefs = (_VarDefAndUsage(_messages, _allVarDefinitions) ..visitTree(styleSheet)) .varDefs; // Resolve all definitions to a non-VarUsage (terminal expression). mainStyleSheetVarDefs.forEach((key, value) { for (var _ in (value.expression as Expressions).expressions) { mainStyleSheetVarDefs[key] = _findTerminalVarDefinition(_allVarDefinitions, value); } }); } } /// Build list of all var definitions in all includes. class _VarDefinitionsIncludes extends Visitor { final Map<String, VarDefinition> varDefs; _VarDefinitionsIncludes(this.varDefs); @override void visitTree(StyleSheet tree) { visitStyleSheet(tree); } @override void visitVarDefinition(VarDefinition node) { // Replace with latest variable definition. varDefs[node.definedName] = node; super.visitVarDefinition(node); } @override void visitVarDefinitionDirective(VarDefinitionDirective node) { visitVarDefinition(node.def); } } /// Find var- definitions in a style sheet. /// [found] list of known definitions. class _VarDefAndUsage extends Visitor { final Messages _messages; final Map<String, VarDefinition> _knownVarDefs; final varDefs = <String, VarDefinition>{}; VarDefinition currVarDefinition; List<Expression> currentExpressions; _VarDefAndUsage(this._messages, this._knownVarDefs); @override void visitTree(StyleSheet tree) { visitStyleSheet(tree); } @override void visitVarDefinition(VarDefinition node) { // Replace with latest variable definition. currVarDefinition = node; _knownVarDefs[node.definedName] = node; varDefs[node.definedName] = node; super.visitVarDefinition(node); currVarDefinition = null; } @override void visitVarDefinitionDirective(VarDefinitionDirective node) { visitVarDefinition(node.def); } @override void visitExpressions(Expressions node) { currentExpressions = node.expressions; super.visitExpressions(node); currentExpressions = null; } @override void visitVarUsage(VarUsage node) { if (currVarDefinition != null && currVarDefinition.badUsage) return; // Don't process other var() inside of a varUsage. That implies that the // default is a var() too. Also, don't process any var() inside of a // varDefinition (they're just place holders until we've resolved all real // usages. var expressions = currentExpressions; var index = expressions.indexOf(node); assert(index >= 0); var def = _knownVarDefs[node.name]; if (def != null) { if (def.badUsage) { // Remove any expressions pointing to a bad var definition. expressions.removeAt(index); return; } _resolveVarUsage(currentExpressions, index, _findTerminalVarDefinition(_knownVarDefs, def)); } else if (node.defaultValues.any((e) => e is VarUsage)) { // Don't have a VarDefinition need to use default values resolve all // default values. var terminalDefaults = <Expression>[]; for (var defaultValue in node.defaultValues) { terminalDefaults.addAll(resolveUsageTerminal(defaultValue)); } expressions.replaceRange(index, index + 1, terminalDefaults); } else if (node.defaultValues.isNotEmpty) { // No VarDefinition but default value is a terminal expression; use it. expressions.replaceRange(index, index + 1, node.defaultValues); } else { if (currVarDefinition != null) { currVarDefinition.badUsage = true; var mainStyleSheetDef = varDefs[node.name]; if (mainStyleSheetDef != null) { varDefs.remove(currVarDefinition.property); } } // Remove var usage that points at an undefined definition. expressions.removeAt(index); _messages.warning('Variable is not defined.', node.span); } var oldExpressions = currentExpressions; currentExpressions = node.defaultValues; super.visitVarUsage(node); currentExpressions = oldExpressions; } List<Expression> resolveUsageTerminal(VarUsage usage) { var result = <Expression>[]; var varDef = _knownVarDefs[usage.name]; List<Expression> expressions; if (varDef == null) { // VarDefinition not found try the defaultValues. expressions = usage.defaultValues; } else { // Use the VarDefinition found. expressions = (varDef.expression as Expressions).expressions; } for (var expr in expressions) { if (expr is VarUsage) { // Get terminal value. result.addAll(resolveUsageTerminal(expr)); } } // We're at a terminal just return the VarDefinition expression. if (result.isEmpty && varDef != null) { result = (varDef.expression as Expressions).expressions; } return result; } void _resolveVarUsage( List<Expression> expressions, int index, VarDefinition def) { var defExpressions = (def.expression as Expressions).expressions; expressions.replaceRange(index, index + 1, defExpressions); } } /// Remove all var definitions. class _RemoveVarDefinitions extends Visitor { @override void visitTree(StyleSheet tree) { visitStyleSheet(tree); } @override void visitStyleSheet(StyleSheet ss) { ss.topLevels.removeWhere((e) => e is VarDefinitionDirective); super.visitStyleSheet(ss); } @override void visitDeclarationGroup(DeclarationGroup node) { node.declarations.removeWhere((e) => e is VarDefinition); super.visitDeclarationGroup(node); } } /// Find terminal definition (non VarUsage implies real CSS value). VarDefinition _findTerminalVarDefinition( Map<String, VarDefinition> varDefs, VarDefinition varDef) { var expressions = varDef.expression as Expressions; for (var expr in expressions.expressions) { if (expr is VarUsage) { var usageName = expr.name; var foundDef = varDefs[usageName]; // If foundDef is unknown check if defaultValues; if it exist then resolve // to terminal value. if (foundDef == null) { // We're either a VarUsage or terminal definition if in varDefs; // either way replace VarUsage with it's default value because the // VarDefinition isn't found. var defaultValues = expr.defaultValues; var replaceExprs = expressions.expressions; assert(replaceExprs.length == 1); replaceExprs.replaceRange(0, 1, defaultValues); return varDef; } if (foundDef is VarDefinition) { return _findTerminalVarDefinition(varDefs, foundDef); } } else { // Return real CSS property. return varDef; } } // Didn't point to a var definition that existed. return varDef; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/tokenizer_base.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Generated by scripts/tokenizer_gen.py. part of '../parser.dart'; /// Tokenizer state to support look ahead for Less' nested selectors. class TokenizerState { final int index; final int startIndex; final bool inSelectorExpression; final bool inSelector; TokenizerState(TokenizerBase base) : index = base._index, startIndex = base._startIndex, inSelectorExpression = base.inSelectorExpression, inSelector = base.inSelector; } /// The base class for our tokenizer. The hand coded parts are in this file, /// with the generated parts in the subclass Tokenizer. abstract class TokenizerBase { final SourceFile _file; final String _text; // TODO: this seems like a bug – this field *is* used // ignore: prefer_final_fields bool _inString; /// Changes tokenization when in a pseudo function expression. If true then /// minus signs are handled as operators instead of identifiers. bool inSelectorExpression = false; /// Changes tokenization when in selectors. If true, it prevents identifiers /// from being treated as units. This would break things like ":lang(fr)" or /// the HTML (unknown) tag name "px", which is legal to use in a selector. // TODO(jmesserly): is this a problem elsewhere? "fr" for example will be // processed as a "fraction" unit token, preventing it from working in // places where an identifier is expected. This was breaking selectors like: // :lang(fr) // The assumption that "fr" always means fraction (and similar issue with // other units) doesn't seem valid. We probably should defer this // analysis until we reach places in the parser where units are expected. // I'm not sure this is tokenizing as described in the specs: // http://dev.w3.org/csswg/css-syntax/ // http://dev.w3.org/csswg/selectors4/ bool inSelector = false; int _index = 0; int _startIndex = 0; TokenizerBase(this._file, this._text, this._inString, [this._index = 0]); Token next(); int getIdentifierKind(); /// Snapshot of Tokenizer scanning state. TokenizerState get mark => TokenizerState(this); /// Restore Tokenizer scanning state. void restore(TokenizerState markedData) { _index = markedData.index; _startIndex = markedData.startIndex; inSelectorExpression = markedData.inSelectorExpression; inSelector = markedData.inSelector; } int _nextChar() { if (_index < _text.length) { return _text.codeUnitAt(_index++); } else { return 0; } } int _peekChar([int offset = 0]) { if (_index + offset < _text.length) { return _text.codeUnitAt(_index + offset); } else { return 0; } } bool _maybeEatChar(int ch) { if (_index < _text.length) { if (_text.codeUnitAt(_index) == ch) { _index++; return true; } else { return false; } } else { return false; } } bool _nextCharsAreNumber(int first) { if (TokenizerHelpers.isDigit(first)) return true; var second = _peekChar(); if (first == TokenChar.DOT) return TokenizerHelpers.isDigit(second); if (first == TokenChar.PLUS || first == TokenChar.MINUS) { return TokenizerHelpers.isDigit(second) || (second == TokenChar.DOT && TokenizerHelpers.isDigit(_peekChar(1))); } return false; } Token _finishToken(int kind) { return Token(kind, _file.span(_startIndex, _index)); } Token _errorToken([String message]) { return ErrorToken( TokenKind.ERROR, _file.span(_startIndex, _index), message); } Token finishWhitespace() { _index--; while (_index < _text.length) { final ch = _text.codeUnitAt(_index++); if (ch == TokenChar.SPACE || ch == TokenChar.TAB || ch == TokenChar.RETURN) { // do nothing } else if (ch == TokenChar.NEWLINE) { if (!_inString) { return _finishToken(TokenKind.WHITESPACE); // note the newline? } } else { _index--; if (_inString) { return next(); } else { return _finishToken(TokenKind.WHITESPACE); } } } return _finishToken(TokenKind.END_OF_FILE); } Token finishMultiLineComment() { var nesting = 1; do { var ch = _nextChar(); if (ch == 0) { return _errorToken(); } else if (ch == TokenChar.ASTERISK) { if (_maybeEatChar(TokenChar.SLASH)) { nesting--; } } else if (ch == TokenChar.SLASH) { if (_maybeEatChar(TokenChar.ASTERISK)) { nesting++; } } } while (nesting > 0); if (_inString) { return next(); } else { return _finishToken(TokenKind.COMMENT); } } void eatDigits() { while (_index < _text.length) { if (TokenizerHelpers.isDigit(_text.codeUnitAt(_index))) { _index++; } else { return; } } } static int _hexDigit(int c) { if (c >= 48 /*0*/ && c <= 57 /*9*/) { return c - 48; } else if (c >= 97 /*a*/ && c <= 102 /*f*/) { return c - 87; } else if (c >= 65 /*A*/ && c <= 70 /*F*/) { return c - 55; } else { return -1; } } int readHex([int hexLength]) { int maxIndex; if (hexLength == null) { maxIndex = _text.length - 1; } else { // TODO(jimhug): What if this is too long? maxIndex = _index + hexLength; if (maxIndex >= _text.length) return -1; } var result = 0; while (_index < maxIndex) { final digit = _hexDigit(_text.codeUnitAt(_index)); if (digit == -1) { if (hexLength == null) { return result; } else { return -1; } } _hexDigit(_text.codeUnitAt(_index)); // Multiply by 16 rather than shift by 4 since that will result in a // correct value for numbers that exceed the 32 bit precision of JS // 'integers'. // TODO: Figure out a better solution to integer truncation. Issue 638. result = (result * 16) + digit; _index++; } return result; } Token finishNumber() { eatDigits(); if (_peekChar() == TokenChar.DOT) { // Handle the case of 1.toString(). _nextChar(); if (TokenizerHelpers.isDigit(_peekChar())) { eatDigits(); return finishNumberExtra(TokenKind.DOUBLE); } else { _index--; } } return finishNumberExtra(TokenKind.INTEGER); } Token finishNumberExtra(int kind) { if (_maybeEatChar(101 /*e*/) || _maybeEatChar(69 /*E*/)) { kind = TokenKind.DOUBLE; _maybeEatChar(TokenKind.MINUS); _maybeEatChar(TokenKind.PLUS); eatDigits(); } if (_peekChar() != 0 && TokenizerHelpers.isIdentifierStart(_peekChar())) { _nextChar(); return _errorToken('illegal character in number'); } return _finishToken(kind); } Token _makeStringToken(List<int> buf, bool isPart) { final s = String.fromCharCodes(buf); final kind = isPart ? TokenKind.STRING_PART : TokenKind.STRING; return LiteralToken(kind, _file.span(_startIndex, _index), s); } Token makeIEFilter(int start, int end) { var filter = _text.substring(start, end); return LiteralToken(TokenKind.STRING, _file.span(start, end), filter); } Token _makeRawStringToken(bool isMultiline) { String s; if (isMultiline) { // Skip initial newline in multiline strings var start = _startIndex + 4; if (_text[start] == '\n') start++; s = _text.substring(start, _index - 3); } else { s = _text.substring(_startIndex + 2, _index - 1); } return LiteralToken(TokenKind.STRING, _file.span(_startIndex, _index), s); } Token finishMultilineString(int quote) { var buf = <int>[]; while (true) { var ch = _nextChar(); if (ch == 0) { return _errorToken(); } else if (ch == quote) { if (_maybeEatChar(quote)) { if (_maybeEatChar(quote)) { return _makeStringToken(buf, false); } buf.add(quote); } buf.add(quote); } else if (ch == TokenChar.BACKSLASH) { var escapeVal = readEscapeSequence(); if (escapeVal == -1) { return _errorToken('invalid hex escape sequence'); } else { buf.add(escapeVal); } } else { buf.add(ch); } } } Token finishString(int quote) { if (_maybeEatChar(quote)) { if (_maybeEatChar(quote)) { // skip an initial newline _maybeEatChar(TokenChar.NEWLINE); return finishMultilineString(quote); } else { return _makeStringToken(<int>[], false); } } return finishStringBody(quote); } Token finishRawString(int quote) { if (_maybeEatChar(quote)) { if (_maybeEatChar(quote)) { return finishMultilineRawString(quote); } else { return _makeStringToken(<int>[], false); } } while (true) { var ch = _nextChar(); if (ch == quote) { return _makeRawStringToken(false); } else if (ch == 0) { return _errorToken(); } } } Token finishMultilineRawString(int quote) { while (true) { var ch = _nextChar(); if (ch == 0) { return _errorToken(); } else if (ch == quote && _maybeEatChar(quote) && _maybeEatChar(quote)) { return _makeRawStringToken(true); } } } Token finishStringBody(int quote) { var buf = <int>[]; while (true) { var ch = _nextChar(); if (ch == quote) { return _makeStringToken(buf, false); } else if (ch == 0) { return _errorToken(); } else if (ch == TokenChar.BACKSLASH) { var escapeVal = readEscapeSequence(); if (escapeVal == -1) { return _errorToken('invalid hex escape sequence'); } else { buf.add(escapeVal); } } else { buf.add(ch); } } } int readEscapeSequence() { final ch = _nextChar(); int hexValue; switch (ch) { case 110 /*n*/ : return TokenChar.NEWLINE; case 114 /*r*/ : return TokenChar.RETURN; case 102 /*f*/ : return TokenChar.FF; case 98 /*b*/ : return TokenChar.BACKSPACE; case 116 /*t*/ : return TokenChar.TAB; case 118 /*v*/ : return TokenChar.FF; case 120 /*x*/ : hexValue = readHex(2); break; case 117 /*u*/ : if (_maybeEatChar(TokenChar.LBRACE)) { hexValue = readHex(); if (!_maybeEatChar(TokenChar.RBRACE)) { return -1; } } else { hexValue = readHex(4); } break; default: return ch; } if (hexValue == -1) return -1; // According to the Unicode standard the high and low surrogate halves // used by UTF-16 (U+D800 through U+DFFF) and values above U+10FFFF // are not legal Unicode values. if (hexValue < 0xD800 || hexValue > 0xDFFF && hexValue <= 0xFFFF) { return hexValue; } else if (hexValue <= 0x10FFFF) { messages.error('unicode values greater than 2 bytes not implemented yet', _file.span(_startIndex, _startIndex + 1)); return -1; } else { return -1; } } Token finishDot() { if (TokenizerHelpers.isDigit(_peekChar())) { eatDigits(); return finishNumberExtra(TokenKind.DOUBLE); } else { return _finishToken(TokenKind.DOT); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/analyzer.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../parser.dart'; // TODO(terry): Add optimizing phase to remove duplicated selectors in the same // selector group (e.g., .btn, .btn { color: red; }). Also, look // at simplifying selectors expressions too (much harder). // TODO(terry): Detect invalid directive usage. All @imports must occur before // all rules other than @charset directive. Any @import directive // after any non @charset or @import directive are ignored. e.g., // @import "a.css"; // div { color: red; } // @import "b.css"; // becomes: // @import "a.css"; // div { color: red; } // <http://www.w3.org/TR/css3-syntax/#at-rules> /// Analysis phase will validate/fixup any new CSS feature or any Sass style /// feature. class Analyzer { final List<StyleSheet> _styleSheets; final Messages _messages; Analyzer(this._styleSheets, this._messages); // TODO(terry): Currently each feature walks the AST each time. Once we have // our complete feature set consider benchmarking the cost and // possibly combine in one walk. void run() { // Expand top-level @include. _styleSheets.forEach( (styleSheet) => TopLevelIncludes.expand(_messages, _styleSheets)); // Expand @include in declarations. _styleSheets.forEach( (styleSheet) => DeclarationIncludes.expand(_messages, _styleSheets)); // Remove all @mixin and @include _styleSheets.forEach((styleSheet) => MixinsAndIncludes.remove(styleSheet)); // Expand any nested selectors using selector desendant combinator to // signal CSS inheritance notation. _styleSheets.forEach((styleSheet) => ExpandNestedSelectors() ..visitStyleSheet(styleSheet) ..flatten(styleSheet)); // Expand any @extend. _styleSheets.forEach((styleSheet) { var allExtends = AllExtends()..visitStyleSheet(styleSheet); InheritExtends(_messages, allExtends)..visitStyleSheet(styleSheet); }); } } /// Traverse all rulesets looking for nested ones. If a ruleset is in a /// declaration group (implies nested selector) then generate new ruleset(s) at /// level 0 of CSS using selector inheritance syntax (flattens the nesting). /// /// How the AST works for a rule [RuleSet] and nested rules. First of all a /// CSS rule [RuleSet] consist of a selector and a declaration e.g., /// /// selector { /// declaration /// } /// /// AST structure of a [RuleSet] is: /// /// RuleSet /// SelectorGroup /// List<Selector> /// List<SimpleSelectorSequence> /// Combinator // +, >, ~, DESCENDENT, or NONE /// SimpleSelector // class, id, element, namespace, attribute /// DeclarationGroup /// List // Declaration or RuleSet /// /// For the simple rule: /// /// div + span { color: red; } /// /// the AST [RuleSet] is: /// /// RuleSet /// SelectorGroup /// List<Selector> /// [0] /// List<SimpleSelectorSequence> /// [0] Combinator = COMBINATOR_NONE /// ElementSelector (name = div) /// [1] Combinator = COMBINATOR_PLUS /// ElementSelector (name = span) /// DeclarationGroup /// List // Declarations or RuleSets /// [0] /// Declaration (property = color, expression = red) /// /// Usually a SelectorGroup contains 1 Selector. Consider the selectors: /// /// div { color: red; } /// a { color: red; } /// /// are equivalent to /// /// div, a { color : red; } /// /// In the above the RuleSet would have a SelectorGroup with 2 selectors e.g., /// /// RuleSet /// SelectorGroup /// List<Selector> /// [0] /// List<SimpleSelectorSequence> /// [0] Combinator = COMBINATOR_NONE /// ElementSelector (name = div) /// [1] /// List<SimpleSelectorSequence> /// [0] Combinator = COMBINATOR_NONE /// ElementSelector (name = a) /// DeclarationGroup /// List // Declarations or RuleSets /// [0] /// Declaration (property = color, expression = red) /// /// For a nested rule e.g., /// /// div { /// color : blue; /// a { color : red; } /// } /// /// Would map to the follow CSS rules: /// /// div { color: blue; } /// div a { color: red; } /// /// The AST for the former nested rule is: /// /// RuleSet /// SelectorGroup /// List<Selector> /// [0] /// List<SimpleSelectorSequence> /// [0] Combinator = COMBINATOR_NONE /// ElementSelector (name = div) /// DeclarationGroup /// List // Declarations or RuleSets /// [0] /// Declaration (property = color, expression = blue) /// [1] /// RuleSet /// SelectorGroup /// List<Selector> /// [0] /// List<SimpleSelectorSequence> /// [0] Combinator = COMBINATOR_NONE /// ElementSelector (name = a) /// DeclarationGroup /// List // Declarations or RuleSets /// [0] /// Declaration (property = color, expression = red) /// /// Nested rules is a terse mechanism to describe CSS inheritance. The analyzer /// will flatten and expand the nested rules to it's flatten strucure. Using /// the all parent [RuleSets] (selector expressions) and applying each nested /// [RuleSet] to the list of [Selectors] in a [SelectorGroup]. /// /// Then result is a style sheet where all nested rules have been flatten and /// expanded. class ExpandNestedSelectors extends Visitor { /// Parent [RuleSet] if a nested rule otherwise [:null:]. RuleSet _parentRuleSet; /// Top-most rule if nested rules. SelectorGroup _topLevelSelectorGroup; /// SelectorGroup at each nesting level. SelectorGroup _nestedSelectorGroup; /// Declaration (sans the nested selectors). DeclarationGroup _flatDeclarationGroup; /// Each nested selector get's a flatten RuleSet. List<RuleSet> _expandedRuleSets = []; /// Maping of a nested rule set to the fully expanded list of RuleSet(s). final _expansions = <RuleSet, List<RuleSet>>{}; @override void visitRuleSet(RuleSet node) { final oldParent = _parentRuleSet; var oldNestedSelectorGroups = _nestedSelectorGroup; if (_nestedSelectorGroup == null) { // Create top-level selector (may have nested rules). final newSelectors = node.selectorGroup.selectors.toList(); _topLevelSelectorGroup = SelectorGroup(newSelectors, node.span); _nestedSelectorGroup = _topLevelSelectorGroup; } else { // Generate new selector groups from the nested rules. _nestedSelectorGroup = _mergeToFlatten(node); } _parentRuleSet = node; super.visitRuleSet(node); _parentRuleSet = oldParent; // Remove nested rules; they're all flatten and in the _expandedRuleSets. node.declarationGroup.declarations .removeWhere((declaration) => declaration is RuleSet); _nestedSelectorGroup = oldNestedSelectorGroups; // If any expandedRuleSets and we're back at the top-level rule set then // there were nested rule set(s). if (_parentRuleSet == null) { if (_expandedRuleSets.isNotEmpty) { // Remember ruleset to replace with these flattened rulesets. _expansions[node] = _expandedRuleSets; _expandedRuleSets = []; } assert(_flatDeclarationGroup == null); assert(_nestedSelectorGroup == null); } } /// Build up the list of all inherited sequences from the parent selector /// [node] is the current nested selector and it's parent is the last entry in /// the [_nestedSelectorGroup]. SelectorGroup _mergeToFlatten(RuleSet node) { // Create a new SelectorGroup for this nesting level. var nestedSelectors = _nestedSelectorGroup.selectors; var selectors = node.selectorGroup.selectors; // Create a merged set of previous parent selectors and current selectors. var newSelectors = <Selector>[]; for (var selector in selectors) { for (var nestedSelector in nestedSelectors) { var seq = _mergeNestedSelector(nestedSelector.simpleSelectorSequences, selector.simpleSelectorSequences); newSelectors.add(Selector(seq, node.span)); } } return SelectorGroup(newSelectors, node.span); } /// Merge the nested selector sequences [current] to the [parent] sequences or /// substitue any & with the parent selector. List<SimpleSelectorSequence> _mergeNestedSelector( List<SimpleSelectorSequence> parent, List<SimpleSelectorSequence> current) { // If any & operator then the parent selector will be substituted otherwise // the parent selector is pre-pended to the current selector. var hasThis = current.any((s) => s.simpleSelector.isThis); var newSequence = <SimpleSelectorSequence>[]; if (!hasThis) { // If no & in the sector group then prefix with the parent selector. newSequence.addAll(parent); newSequence.addAll(_convertToDescendentSequence(current)); } else { for (var sequence in current) { if (sequence.simpleSelector.isThis) { // Substitue the & with the parent selector and only use a combinator // descendant if & is prefix by a sequence with an empty name e.g., // "... + &", "&", "... ~ &", etc. var hasPrefix = newSequence.isNotEmpty && newSequence.last.simpleSelector.name.isNotEmpty; newSequence.addAll( hasPrefix ? _convertToDescendentSequence(parent) : parent); } else { newSequence.add(sequence); } } } return newSequence; } /// Return selector sequences with first sequence combinator being a /// descendant. Used for nested selectors when the parent selector needs to /// be prefixed to a nested selector or to substitute the this (&) with the /// parent selector. List<SimpleSelectorSequence> _convertToDescendentSequence( List<SimpleSelectorSequence> sequences) { if (sequences.isEmpty) return sequences; var newSequences = <SimpleSelectorSequence>[]; var first = sequences.first; newSequences.add(SimpleSelectorSequence( first.simpleSelector, first.span, TokenKind.COMBINATOR_DESCENDANT)); newSequences.addAll(sequences.skip(1)); return newSequences; } @override void visitDeclarationGroup(DeclarationGroup node) { var span = node.span; var currentGroup = DeclarationGroup([], span); var oldGroup = _flatDeclarationGroup; _flatDeclarationGroup = currentGroup; var expandedLength = _expandedRuleSets.length; super.visitDeclarationGroup(node); // We're done with the group. _flatDeclarationGroup = oldGroup; // No nested rule to process it's a top-level rule. if (_nestedSelectorGroup == _topLevelSelectorGroup) return; // If flatten selector's declaration is empty skip this selector, no need // to emit an empty nested selector. if (currentGroup.declarations.isEmpty) return; var selectorGroup = _nestedSelectorGroup; // Build new rule set from the nested selectors and declarations. var newRuleSet = RuleSet(selectorGroup, currentGroup, span); // Place in order so outer-most rule is first. if (expandedLength == _expandedRuleSets.length) { _expandedRuleSets.add(newRuleSet); } else { _expandedRuleSets.insert(expandedLength, newRuleSet); } } // Record all declarations in a nested selector (Declaration, VarDefinition // and MarginGroup) but not the nested rule in the Declaration. @override void visitDeclaration(Declaration node) { if (_parentRuleSet != null) { _flatDeclarationGroup.declarations.add(node); } super.visitDeclaration(node); } @override void visitVarDefinition(VarDefinition node) { if (_parentRuleSet != null) { _flatDeclarationGroup.declarations.add(node); } super.visitVarDefinition(node); } @override void visitExtendDeclaration(ExtendDeclaration node) { if (_parentRuleSet != null) { _flatDeclarationGroup.declarations.add(node); } super.visitExtendDeclaration(node); } @override void visitMarginGroup(MarginGroup node) { if (_parentRuleSet != null) { _flatDeclarationGroup.declarations.add(node); } super.visitMarginGroup(node); } /// Replace the rule set that contains nested rules with the flatten rule /// sets. void flatten(StyleSheet styleSheet) { // TODO(terry): Iterate over topLevels instead of _expansions it's already // a map (this maybe quadratic). _expansions.forEach((RuleSet ruleSet, List<RuleSet> newRules) { var index = styleSheet.topLevels.indexOf(ruleSet); if (index == -1) { // Check any @media directives for nested rules and replace them. var found = _MediaRulesReplacer.replace(styleSheet, ruleSet, newRules); assert(found); } else { styleSheet.topLevels.insertAll(index + 1, newRules); } }); _expansions.clear(); } } class _MediaRulesReplacer extends Visitor { final RuleSet _ruleSet; final List<RuleSet> _newRules; bool _foundAndReplaced = false; /// Look for the [ruleSet] inside of an @media directive; if found then /// replace with the [newRules]. If [ruleSet] is found and replaced return /// true. static bool replace( StyleSheet styleSheet, RuleSet ruleSet, List<RuleSet> newRules) { var visitor = _MediaRulesReplacer(ruleSet, newRules); visitor.visitStyleSheet(styleSheet); return visitor._foundAndReplaced; } _MediaRulesReplacer(this._ruleSet, this._newRules); @override void visitMediaDirective(MediaDirective node) { var index = node.rules.indexOf(_ruleSet); if (index != -1) { node.rules.insertAll(index + 1, _newRules); _foundAndReplaced = true; } } } /// Expand all @include at the top-level the ruleset(s) associated with the /// mixin. class TopLevelIncludes extends Visitor { StyleSheet _styleSheet; final Messages _messages; /// Map of variable name key to it's definition. final map = <String, MixinDefinition>{}; MixinDefinition currDef; static void expand(Messages messages, List<StyleSheet> styleSheets) { TopLevelIncludes(messages, styleSheets); } bool _anyRulesets(MixinRulesetDirective def) => def.rulesets.any((rule) => rule is RuleSet); TopLevelIncludes(this._messages, List<StyleSheet> styleSheets) { for (var styleSheet in styleSheets) { visitTree(styleSheet); } } @override void visitStyleSheet(StyleSheet ss) { _styleSheet = ss; super.visitStyleSheet(ss); _styleSheet = null; } @override void visitIncludeDirective(IncludeDirective node) { if (map.containsKey(node.name)) { var mixinDef = map[node.name]; if (mixinDef is MixinRulesetDirective) { _TopLevelIncludeReplacer.replace( _messages, _styleSheet, node, mixinDef.rulesets); } else if (currDef is MixinRulesetDirective && _anyRulesets(currDef)) { // currDef is MixinRulesetDirective MixinRulesetDirective mixinRuleset = currDef; var index = mixinRuleset.rulesets.indexOf(node); mixinRuleset.rulesets.removeAt(index); _messages.warning( 'Using declaration mixin ${node.name} as top-level mixin', node.span); } } else { if (currDef is MixinRulesetDirective) { var rulesetDirect = currDef as MixinRulesetDirective; rulesetDirect.rulesets.removeWhere((entry) { if (entry == node) { _messages.warning('Undefined mixin ${node.name}', node.span); return true; } return false; }); } } super.visitIncludeDirective(node); } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { currDef = node; super.visitMixinRulesetDirective(node); // Replace with latest top-level mixin definition. map[node.name] = node; currDef = null; } @override void visitMixinDeclarationDirective(MixinDeclarationDirective node) { currDef = node; super.visitMixinDeclarationDirective(node); // Replace with latest mixin definition. map[node.name] = node; currDef = null; } } /// @include as a top-level with ruleset(s). class _TopLevelIncludeReplacer extends Visitor { final IncludeDirective _include; final List<TreeNode> _newRules; bool _foundAndReplaced = false; /// Look for the [ruleSet] inside of an @media directive; if found then /// replace with the [newRules]. If [ruleSet] is found and replaced return /// true. static bool replace(Messages messages, StyleSheet styleSheet, IncludeDirective include, List<TreeNode> newRules) { var visitor = _TopLevelIncludeReplacer(include, newRules); visitor.visitStyleSheet(styleSheet); return visitor._foundAndReplaced; } _TopLevelIncludeReplacer(this._include, this._newRules); @override void visitStyleSheet(StyleSheet node) { var index = node.topLevels.indexOf(_include); if (index != -1) { node.topLevels.insertAll(index + 1, _newRules); node.topLevels.replaceRange(index, index + 1, [NoOp()]); _foundAndReplaced = true; } super.visitStyleSheet(node); } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { var index = node.rulesets.indexOf(_include as dynamic); if (index != -1) { node.rulesets.insertAll(index + 1, _newRules); // Only the resolve the @include once. node.rulesets.replaceRange(index, index + 1, [NoOp()]); _foundAndReplaced = true; } super.visitMixinRulesetDirective(node); } } /// Utility function to match an include to a list of either Declarations or /// RuleSets, depending on type of mixin (ruleset or declaration). The include /// can be an include in a declaration or an include directive (top-level). int _findInclude(List list, TreeNode node) { IncludeDirective matchNode = (node is IncludeMixinAtDeclaration) ? node.include : node; var index = 0; for (var item in list) { var includeNode = (item is IncludeMixinAtDeclaration) ? item.include : item; if (includeNode == matchNode) return index; index++; } return -1; } /// Stamp out a mixin with the defined args substituted with the user's /// parameters. class CallMixin extends Visitor { final MixinDefinition mixinDef; List _definedArgs; Expressions _currExpressions; int _currIndex = -1; final varUsages = <String, Map<Expressions, Set<int>>>{}; /// Only var defs with more than one expression (comma separated). final Map<String, VarDefinition> varDefs; CallMixin(this.mixinDef, [this.varDefs]) { if (mixinDef is MixinRulesetDirective) { visitMixinRulesetDirective(mixinDef); } else { visitMixinDeclarationDirective(mixinDef); } } /// Given a mixin's defined arguments return a cloned mixin defintion that has /// replaced all defined arguments with user's supplied VarUsages. MixinDefinition transform(List<List<Expression>> callArgs) { // TODO(terry): Handle default arguments and varArgs. // Transform mixin with callArgs. for (var index = 0; index < _definedArgs.length; index++) { var definedArg = _definedArgs[index]; VarDefinition varDef; if (definedArg is VarDefinition) { varDef = definedArg; } else if (definedArg is VarDefinitionDirective) { var varDirective = definedArg; varDef = varDirective.def; } var callArg = callArgs[index]; // Is callArg a var definition with multi-args (expressions > 1). var defArgs = _varDefsAsCallArgs(callArg); if (defArgs.isNotEmpty) { // Replace call args with the var def parameters. callArgs.insertAll(index, defArgs); callArgs.removeAt(index + defArgs.length); callArg = callArgs[index]; } var expressions = varUsages[varDef.definedName]; expressions.forEach((k, v) { for (var usagesIndex in v) { k.expressions.replaceRange(usagesIndex, usagesIndex + 1, callArg); } }); } // Clone the mixin return mixinDef.clone(); } /// Rip apart var def with multiple parameters. List<List<Expression>> _varDefsAsCallArgs(var callArg) { var defArgs = <List<Expression>>[]; if (callArg is List && callArg[0] is VarUsage) { var varDef = varDefs[callArg[0].name]; var expressions = (varDef.expression as Expressions).expressions; assert(expressions.length > 1); for (var expr in expressions) { if (expr is! OperatorComma) { defArgs.add([expr]); } } } return defArgs; } @override void visitExpressions(Expressions node) { var oldExpressions = _currExpressions; var oldIndex = _currIndex; _currExpressions = node; for (_currIndex = 0; _currIndex < node.expressions.length; _currIndex++) { node.expressions[_currIndex].visit(this); } _currIndex = oldIndex; _currExpressions = oldExpressions; } void _addExpression(Map<Expressions, Set<int>> expressions) { var indexSet = <int>{}; indexSet.add(_currIndex); expressions[_currExpressions] = indexSet; } @override void visitVarUsage(VarUsage node) { assert(_currIndex != -1); assert(_currExpressions != null); if (varUsages.containsKey(node.name)) { var expressions = varUsages[node.name]; var allIndexes = expressions[_currExpressions]; if (allIndexes == null) { _addExpression(expressions); } else { allIndexes.add(_currIndex); } } else { var newExpressions = <Expressions, Set<int>>{}; _addExpression(newExpressions); varUsages[node.name] = newExpressions; } super.visitVarUsage(node); } @override void visitMixinDeclarationDirective(MixinDeclarationDirective node) { _definedArgs = node.definedArgs; super.visitMixinDeclarationDirective(node); } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { _definedArgs = node.definedArgs; super.visitMixinRulesetDirective(node); } } /// Expand all @include inside of a declaration associated with a mixin. class DeclarationIncludes extends Visitor { StyleSheet _styleSheet; final Messages _messages; /// Map of variable name key to it's definition. final Map<String, MixinDefinition> map = <String, MixinDefinition>{}; /// Cache of mixin called with parameters. final Map<String, CallMixin> callMap = <String, CallMixin>{}; MixinDefinition currDef; DeclarationGroup currDeclGroup; /// Var definitions with more than 1 expression. final varDefs = <String, VarDefinition>{}; static void expand(Messages messages, List<StyleSheet> styleSheets) { DeclarationIncludes(messages, styleSheets); } DeclarationIncludes(this._messages, List<StyleSheet> styleSheets) { for (var styleSheet in styleSheets) { visitTree(styleSheet); } } bool _allIncludes(rulesets) => rulesets.every((rule) => rule is IncludeDirective || rule is NoOp); CallMixin _createCallDeclMixin(MixinDefinition mixinDef) { callMap.putIfAbsent(mixinDef.name, () => callMap[mixinDef.name] = CallMixin(mixinDef, varDefs)); return callMap[mixinDef.name]; } @override void visitStyleSheet(StyleSheet ss) { _styleSheet = ss; super.visitStyleSheet(ss); _styleSheet = null; } @override void visitDeclarationGroup(DeclarationGroup node) { currDeclGroup = node; super.visitDeclarationGroup(node); currDeclGroup = null; } @override void visitIncludeMixinAtDeclaration(IncludeMixinAtDeclaration node) { if (map.containsKey(node.include.name)) { var mixinDef = map[node.include.name]; // Fix up any mixin that is really a Declaration but has includes. if (mixinDef is MixinRulesetDirective) { if (!_allIncludes(mixinDef.rulesets) && currDeclGroup != null) { var index = _findInclude(currDeclGroup.declarations, node); if (index != -1) { currDeclGroup.declarations.replaceRange(index, index + 1, [NoOp()]); } _messages.warning( 'Using top-level mixin ${node.include.name} as a declaration', node.span); } else { // We're a list of @include(s) inside of a mixin ruleset - convert // to a list of IncludeMixinAtDeclaration(s). var origRulesets = mixinDef.rulesets; var rulesets = <Declaration>[]; if (origRulesets.every((ruleset) => ruleset is IncludeDirective)) { origRulesets.forEach((ruleset) { rulesets.add(IncludeMixinAtDeclaration( ruleset as IncludeDirective, ruleset.span)); }); _IncludeReplacer.replace(_styleSheet, node, rulesets); } } } if (mixinDef.definedArgs.isNotEmpty && node.include.args.isNotEmpty) { var callMixin = _createCallDeclMixin(mixinDef); mixinDef = callMixin.transform(node.include.args); } if (mixinDef is MixinDeclarationDirective) { _IncludeReplacer.replace( _styleSheet, node, mixinDef.declarations.declarations); } } else { _messages.warning('Undefined mixin ${node.include.name}', node.span); } super.visitIncludeMixinAtDeclaration(node); } @override void visitIncludeDirective(IncludeDirective node) { if (map.containsKey(node.name)) { var mixinDef = map[node.name]; if (currDef is MixinDeclarationDirective && mixinDef is MixinDeclarationDirective) { _IncludeReplacer.replace( _styleSheet, node, mixinDef.declarations.declarations); } else if (currDef is MixinDeclarationDirective) { var decls = (currDef as MixinDeclarationDirective).declarations.declarations; var index = _findInclude(decls, node); if (index != -1) { decls.replaceRange(index, index + 1, [NoOp()]); } } } super.visitIncludeDirective(node); } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { currDef = node; super.visitMixinRulesetDirective(node); // Replace with latest top-level mixin definition. map[node.name] = node; currDef = null; } @override void visitMixinDeclarationDirective(MixinDeclarationDirective node) { currDef = node; super.visitMixinDeclarationDirective(node); // Replace with latest mixin definition. map[node.name] = node; currDef = null; } @override void visitVarDefinition(VarDefinition node) { // Only record var definitions that have multiple expressions (comma // separated for mixin parameter substitution. var exprs = (node.expression as Expressions).expressions; if (exprs.length > 1) { varDefs[node.definedName] = node; } super.visitVarDefinition(node); } @override void visitVarDefinitionDirective(VarDefinitionDirective node) { visitVarDefinition(node.def); } } /// @include as a top-level with ruleset(s). class _IncludeReplacer extends Visitor { final TreeNode _include; final List<TreeNode> _newDeclarations; /// Look for the [ruleSet] inside of a @media directive; if found then replace /// with the [newRules]. static void replace( StyleSheet ss, TreeNode include, List<TreeNode> newDeclarations) { var visitor = _IncludeReplacer(include, newDeclarations); visitor.visitStyleSheet(ss); } _IncludeReplacer(this._include, this._newDeclarations); @override void visitDeclarationGroup(DeclarationGroup node) { var index = _findInclude(node.declarations, _include); if (index != -1) { node.declarations.insertAll(index + 1, _newDeclarations); // Change @include to NoOp so it's processed only once. node.declarations.replaceRange(index, index + 1, [NoOp()]); } super.visitDeclarationGroup(node); } } /// Remove all @mixin and @include and any NoOp used as placeholder for /// @include. class MixinsAndIncludes extends Visitor { static void remove(StyleSheet styleSheet) { MixinsAndIncludes()..visitStyleSheet(styleSheet); } bool _nodesToRemove(node) => node is IncludeDirective || node is MixinDefinition || node is NoOp; @override void visitStyleSheet(StyleSheet ss) { var index = ss.topLevels.length; while (--index >= 0) { if (_nodesToRemove(ss.topLevels[index])) { ss.topLevels.removeAt(index); } } super.visitStyleSheet(ss); } @override void visitDeclarationGroup(DeclarationGroup node) { var index = node.declarations.length; while (--index >= 0) { if (_nodesToRemove(node.declarations[index])) { node.declarations.removeAt(index); } } super.visitDeclarationGroup(node); } } /// Find all @extend to create inheritance. class AllExtends extends Visitor { final inherits = <String, List<SelectorGroup>>{}; SelectorGroup _currSelectorGroup; int _currDeclIndex; final _extendsToRemove = <int>[]; @override void visitRuleSet(RuleSet node) { var oldSelectorGroup = _currSelectorGroup; _currSelectorGroup = node.selectorGroup; super.visitRuleSet(node); _currSelectorGroup = oldSelectorGroup; } @override void visitExtendDeclaration(ExtendDeclaration node) { var inheritName = ''; for (var selector in node.selectors) { inheritName += selector.toString(); } if (inherits.containsKey(inheritName)) { inherits[inheritName].add(_currSelectorGroup); } else { inherits[inheritName] = [_currSelectorGroup]; } // Remove this @extend _extendsToRemove.add(_currDeclIndex); super.visitExtendDeclaration(node); } @override void visitDeclarationGroup(DeclarationGroup node) { var oldDeclIndex = _currDeclIndex; var decls = node.declarations; for (_currDeclIndex = 0; _currDeclIndex < decls.length; _currDeclIndex++) { decls[_currDeclIndex].visit(this); } if (_extendsToRemove.isNotEmpty) { var removeTotal = _extendsToRemove.length - 1; for (var index = removeTotal; index >= 0; index--) { decls.removeAt(_extendsToRemove[index]); } _extendsToRemove.clear(); } _currDeclIndex = oldDeclIndex; } } // TODO(terry): Need to handle merging selector sequences // TODO(terry): Need to handle @extend-Only selectors. // TODO(terry): Need to handle !optional glag. /// Changes any selector that matches @extend. class InheritExtends extends Visitor { final AllExtends _allExtends; InheritExtends(Messages messages, this._allExtends); @override void visitSelectorGroup(SelectorGroup node) { for (var selectorsIndex = 0; selectorsIndex < node.selectors.length; selectorsIndex++) { var selectors = node.selectors[selectorsIndex]; var isLastNone = false; var selectorName = ''; for (var index = 0; index < selectors.simpleSelectorSequences.length; index++) { var simpleSeq = selectors.simpleSelectorSequences[index]; var namePart = simpleSeq.simpleSelector.toString(); selectorName = (isLastNone) ? (selectorName + namePart) : namePart; var matches = _allExtends.inherits[selectorName]; if (matches != null) { for (var match in matches) { // Create a new group. var newSelectors = selectors.clone(); var newSeq = match.selectors[0].clone(); if (isLastNone) { // Add the inherited selector. node.selectors.add(newSeq); } else { // Replace the selector sequence to the left of the pseudo class // or pseudo element. // Make new selector seq combinator the same as the original. var orgCombinator = newSelectors.simpleSelectorSequences[index].combinator; newSeq.simpleSelectorSequences[0].combinator = orgCombinator; newSelectors.simpleSelectorSequences.replaceRange( index, index + 1, newSeq.simpleSelectorSequences); node.selectors.add(newSelectors); } isLastNone = false; } } else { isLastNone = simpleSeq.isCombinatorNone; } } } super.visitSelectorGroup(node); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/tree_base.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of '../visitor.dart'; /// The base type for all nodes in a CSS abstract syntax tree. abstract class TreeNode { /// The source code this [TreeNode] represents. final SourceSpan span; TreeNode(this.span); TreeNode clone(); /// Classic double-dispatch visitor for implementing passes. dynamic visit(VisitorBase visitor); /// A multiline string showing the node and its children. String toDebugString() { var to = TreeOutput(); var tp = _TreePrinter(to, true); visit(tp); return to.buf.toString(); } } /// The base type for expressions. abstract class Expression extends TreeNode { Expression(SourceSpan span) : super(span); } /// Simple class to provide a textual dump of trees for debugging. class TreeOutput { int depth = 0; final StringBuffer buf = StringBuffer(); VisitorBase printer; void write(String s) { for (var i = 0; i < depth; i++) { buf.write(' '); } buf.write(s); } void writeln(String s) { write(s); buf.write('\n'); } void heading(String name, [span]) { write(name); if (span != null) { buf.write(' (${span.message('')})'); } buf.write('\n'); } String toValue(value) { if (value == null) { return 'null'; } else if (value is Identifier) { return value.name; } else { return value.toString(); } } void writeNode(String label, TreeNode node) { write('${label}: '); depth += 1; if (node != null) { node.visit(printer); } else { writeln('null'); } depth -= 1; } void writeValue(String label, value) { var v = toValue(value); writeln('${label}: ${v}'); } void writeNodeList(String label, List<TreeNode> list) { writeln('${label} ['); if (list != null) { depth += 1; for (var node in list) { if (node != null) { node.visit(printer); } else { writeln('null'); } } depth -= 1; writeln(']'); } } @override String toString() => buf.toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/css_printer.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. part of '../visitor.dart'; /// Visitor that produces a formatted string representation of the CSS tree. class CssPrinter extends Visitor { StringBuffer _buff = StringBuffer(); bool prettyPrint = true; /// Walk the [tree] Stylesheet. [pretty] if true emits line breaks, extra /// spaces, friendly property values, etc., if false emits compacted output. @override void visitTree(StyleSheet tree, {bool pretty = false}) { prettyPrint = pretty; _buff = StringBuffer(); visitStyleSheet(tree); } /// Appends [str] to the output buffer. void emit(String str) { _buff.write(str); } /// Returns the output buffer. @override String toString() => _buff.toString().trim(); String get _newLine => prettyPrint ? '\n' : ''; String get _sp => prettyPrint ? ' ' : ''; // TODO(terry): When adding obfuscation we'll need isOptimized (compact w/ // obufuscation) and have isTesting (compact no obfuscation) and // isCompact would be !prettyPrint. We'll need another boolean // flag for obfuscation. bool get _isTesting => !prettyPrint; @override void visitCalcTerm(CalcTerm node) { emit('${node.text}('); node.expr.visit(this); emit(')'); } @override void visitCssComment(CssComment node) { emit('/* ${node.comment} */'); } @override void visitCommentDefinition(CommentDefinition node) { emit('<!-- ${node.comment} -->'); } @override void visitMediaExpression(MediaExpression node) { emit(node.andOperator ? ' AND ' : ' '); emit('(${node.mediaFeature}'); if (node.exprs.expressions.isNotEmpty) { emit(':'); visitExpressions(node.exprs); } emit(')'); } @override void visitMediaQuery(MediaQuery query) { var unary = query.hasUnary ? ' ${query.unary}' : ''; var mediaType = query.hasMediaType ? ' ${query.mediaType}' : ''; emit('$unary$mediaType'); for (var expression in query.expressions) { visitMediaExpression(expression); } } void emitMediaQueries(List<MediaQuery> queries) { var queriesLen = queries.length; for (var i = 0; i < queriesLen; i++) { var query = queries[i]; if (i > 0) emit(','); visitMediaQuery(query); } } @override void visitDocumentDirective(DocumentDirective node) { emit('$_newLine@-moz-document '); node.functions.first.visit(this); for (var function in node.functions.skip(1)) { emit(',$_sp'); function.visit(this); } emit('$_sp{'); for (var ruleSet in node.groupRuleBody) { ruleSet.visit(this); } emit('$_newLine}'); } @override void visitSupportsDirective(SupportsDirective node) { emit('$_newLine@supports '); node.condition.visit(this); emit('$_sp{'); for (var rule in node.groupRuleBody) { rule.visit(this); } emit('$_newLine}'); } @override void visitSupportsConditionInParens(SupportsConditionInParens node) { emit('('); node.condition.visit(this); emit(')'); } @override void visitSupportsNegation(SupportsNegation node) { emit('not$_sp'); node.condition.visit(this); } @override void visitSupportsConjunction(SupportsConjunction node) { node.conditions.first.visit(this); for (var condition in node.conditions.skip(1)) { emit('${_sp}and$_sp'); condition.visit(this); } } @override void visitSupportsDisjunction(SupportsDisjunction node) { node.conditions.first.visit(this); for (var condition in node.conditions.skip(1)) { emit('${_sp}or$_sp'); condition.visit(this); } } @override void visitViewportDirective(ViewportDirective node) { emit('@${node.name}$_sp{$_newLine'); node.declarations.visit(this); emit('}'); } @override void visitMediaDirective(MediaDirective node) { emit('$_newLine@media'); emitMediaQueries(node.mediaQueries); emit('$_sp{'); for (var ruleset in node.rules) { ruleset.visit(this); } emit('$_newLine}'); } @override void visitHostDirective(HostDirective node) { emit('$_newLine@host$_sp{'); for (var ruleset in node.rules) { ruleset.visit(this); } emit('$_newLine}'); } /// @page : pseudoPage { /// decls /// } @override void visitPageDirective(PageDirective node) { emit('$_newLine@page'); if (node.hasIdent || node.hasPseudoPage) { if (node.hasIdent) emit(' '); emit(node._ident); emit(node.hasPseudoPage ? ':${node._pseudoPage}' : ''); } var declsMargin = node._declsMargin; var declsMarginLength = declsMargin.length; emit('$_sp{$_newLine'); for (var i = 0; i < declsMarginLength; i++) { declsMargin[i].visit(this); } emit('}'); } /// @charset "charset encoding" @override void visitCharsetDirective(CharsetDirective node) { emit('$_newLine@charset "${node.charEncoding}";'); } @override void visitImportDirective(ImportDirective node) { bool isStartingQuote(String ch) => ('\'"'.contains(ch[0])); if (_isTesting) { // Emit assuming url() was parsed; most suite tests use url function. emit(' @import url(${node.import})'); } else if (isStartingQuote(node.import)) { emit(' @import ${node.import}'); } else { // url(...) isn't needed only a URI can follow an @import directive; emit // url as a string. emit(' @import "${node.import}"'); } emitMediaQueries(node.mediaQueries); emit(';'); } @override void visitKeyFrameDirective(KeyFrameDirective node) { emit('$_newLine${node.keyFrameName} '); node.name.visit(this); emit('$_sp{$_newLine'); for (final block in node._blocks) { block.visit(this); } emit('}'); } @override void visitFontFaceDirective(FontFaceDirective node) { emit('$_newLine@font-face '); emit('$_sp{$_newLine'); node._declarations.visit(this); emit('}'); } @override void visitKeyFrameBlock(KeyFrameBlock node) { emit('$_sp$_sp'); node._blockSelectors.visit(this); emit('$_sp{$_newLine'); node._declarations.visit(this); emit('$_sp$_sp}$_newLine'); } @override void visitStyletDirective(StyletDirective node) { emit('/* @stylet export as ${node.dartClassName} */\n'); } @override void visitNamespaceDirective(NamespaceDirective node) { bool isStartingQuote(String ch) => ('\'"'.contains(ch)); if (isStartingQuote(node._uri)) { emit(' @namespace ${node.prefix}"${node._uri}"'); } else { if (_isTesting) { // Emit exactly was we parsed. emit(' @namespace ${node.prefix}url(${node._uri})'); } else { // url(...) isn't needed only a URI can follow a: // @namespace prefix directive. emit(' @namespace ${node.prefix}${node._uri}'); } } emit(';'); } @override void visitVarDefinitionDirective(VarDefinitionDirective node) { visitVarDefinition(node.def); emit(';$_newLine'); } @override void visitMixinRulesetDirective(MixinRulesetDirective node) { emit('@mixin ${node.name} {'); for (var ruleset in node.rulesets) { ruleset.visit(this); } emit('}'); } @override void visitMixinDeclarationDirective(MixinDeclarationDirective node) { emit('@mixin ${node.name} {\n'); visitDeclarationGroup(node.declarations); emit('}'); } /// Added optional newLine for handling @include at top-level vs/ inside of /// a declaration group. @override void visitIncludeDirective(IncludeDirective node, [bool topLevel = true]) { if (topLevel) emit(_newLine); emit('@include ${node.name}'); emit(';'); } @override void visitContentDirective(ContentDirective node) { // TODO(terry): TBD } @override void visitRuleSet(RuleSet node) { emit('$_newLine'); node._selectorGroup.visit(this); emit('$_sp{$_newLine'); node._declarationGroup.visit(this); emit('}'); } @override void visitDeclarationGroup(DeclarationGroup node) { var declarations = node.declarations; var declarationsLength = declarations.length; for (var i = 0; i < declarationsLength; i++) { if (i > 0) emit(_newLine); emit('$_sp$_sp'); declarations[i].visit(this); // Don't emit the last semicolon in compact mode. if (prettyPrint || i < declarationsLength - 1) { emit(';'); } } if (declarationsLength > 0) emit(_newLine); } @override void visitMarginGroup(MarginGroup node) { var margin_sym_name = TokenKind.idToValue(TokenKind.MARGIN_DIRECTIVES, node.margin_sym); emit('@$margin_sym_name$_sp{$_newLine'); visitDeclarationGroup(node); emit('}$_newLine'); } @override void visitDeclaration(Declaration node) { emit('${node.property}:$_sp'); node._expression.visit(this); if (node.important) { emit('$_sp!important'); } } @override void visitVarDefinition(VarDefinition node) { emit('var-${node.definedName}: '); node._expression.visit(this); } @override void visitIncludeMixinAtDeclaration(IncludeMixinAtDeclaration node) { // Don't emit a new line we're inside of a declaration group. visitIncludeDirective(node.include, false); } @override void visitExtendDeclaration(ExtendDeclaration node) { emit('@extend '); for (var selector in node.selectors) { selector.visit(this); } } @override void visitSelectorGroup(SelectorGroup node) { var selectors = node.selectors; var selectorsLength = selectors.length; for (var i = 0; i < selectorsLength; i++) { if (i > 0) emit(',$_sp'); selectors[i].visit(this); } } @override void visitSimpleSelectorSequence(SimpleSelectorSequence node) { emit('${node._combinatorToString}'); node.simpleSelector.visit(this); } @override void visitSimpleSelector(SimpleSelector node) { emit(node.name); } @override void visitNamespaceSelector(NamespaceSelector node) { emit(node.toString()); } @override void visitElementSelector(ElementSelector node) { emit(node.toString()); } @override void visitAttributeSelector(AttributeSelector node) { emit(node.toString()); } @override void visitIdSelector(IdSelector node) { emit(node.toString()); } @override void visitClassSelector(ClassSelector node) { emit(node.toString()); } @override void visitPseudoClassSelector(PseudoClassSelector node) { emit(node.toString()); } @override void visitPseudoElementSelector(PseudoElementSelector node) { emit(node.toString()); } @override void visitPseudoClassFunctionSelector(PseudoClassFunctionSelector node) { emit(':${node.name}('); node.argument.visit(this); emit(')'); } @override void visitPseudoElementFunctionSelector(PseudoElementFunctionSelector node) { emit('::${node.name}('); node.expression.visit(this); emit(')'); } @override void visitNegationSelector(NegationSelector node) { emit(':not('); node.negationArg.visit(this); emit(')'); } @override void visitSelectorExpression(SelectorExpression node) { var expressions = node.expressions; var expressionsLength = expressions.length; for (var i = 0; i < expressionsLength; i++) { // Add space seperator between terms without an operator. var expression = expressions[i]; expression.visit(this); } } @override void visitUnicodeRangeTerm(UnicodeRangeTerm node) { if (node.hasSecond) { emit('U+${node.first}-${node.second}'); } else { emit('U+${node.first}'); } } @override void visitLiteralTerm(LiteralTerm node) { emit(node.text); } @override void visitHexColorTerm(HexColorTerm node) { String mappedName; if (_isTesting && (node.value is! BAD_HEX_VALUE)) { mappedName = TokenKind.hexToColorName(node.value); } mappedName ??= '#${node.text}'; emit(mappedName); } @override void visitNumberTerm(NumberTerm node) { visitLiteralTerm(node); } @override void visitUnitTerm(UnitTerm node) { emit(node.toString()); } @override void visitLengthTerm(LengthTerm node) { emit(node.toString()); } @override void visitPercentageTerm(PercentageTerm node) { emit('${node.text}%'); } @override void visitEmTerm(EmTerm node) { emit('${node.text}em'); } @override void visitExTerm(ExTerm node) { emit('${node.text}ex'); } @override void visitAngleTerm(AngleTerm node) { emit(node.toString()); } @override void visitTimeTerm(TimeTerm node) { emit(node.toString()); } @override void visitFreqTerm(FreqTerm node) { emit(node.toString()); } @override void visitFractionTerm(FractionTerm node) { emit('${node.text}fr'); } @override void visitUriTerm(UriTerm node) { emit('url("${node.text}")'); } @override void visitResolutionTerm(ResolutionTerm node) { emit(node.toString()); } @override void visitViewportTerm(ViewportTerm node) { emit(node.toString()); } @override void visitFunctionTerm(FunctionTerm node) { // TODO(terry): Optimize rgb to a hexcolor. emit('${node.text}('); node._params.visit(this); emit(')'); } @override void visitGroupTerm(GroupTerm node) { emit('('); var terms = node._terms; var termsLength = terms.length; for (var i = 0; i < termsLength; i++) { if (i > 0) emit('$_sp'); terms[i].visit(this); } emit(')'); } @override void visitItemTerm(ItemTerm node) { emit('[${node.text}]'); } @override void visitIE8Term(IE8Term node) { visitLiteralTerm(node); } @override void visitOperatorSlash(OperatorSlash node) { emit('/'); } @override void visitOperatorComma(OperatorComma node) { emit(','); } @override void visitOperatorPlus(OperatorPlus node) { emit('+'); } @override void visitOperatorMinus(OperatorMinus node) { emit('-'); } @override void visitVarUsage(VarUsage node) { emit('var(${node.name}'); if (node.defaultValues.isNotEmpty) { emit(','); for (var defaultValue in node.defaultValues) { emit(' '); defaultValue.visit(this); } } emit(')'); } @override void visitExpressions(Expressions node) { var expressions = node.expressions; var expressionsLength = expressions.length; for (var i = 0; i < expressionsLength; i++) { // Add space seperator between terms without an operator. // TODO(terry): Should have a BinaryExpression to solve this problem. var expression = expressions[i]; if (i > 0 && !(expression is OperatorComma || expression is OperatorSlash)) { // If the previous expression is an operator, use `_sp` so the space is // collapsed when emitted in compact mode. If the previous expression // isn't an operator, the space is significant to delimit the two // expressions and can't be collapsed. var previous = expressions[i - 1]; if (previous is OperatorComma || previous is OperatorSlash) { emit(_sp); } else { emit(' '); } } expression.visit(this); } } @override void visitBinaryExpression(BinaryExpression node) { // TODO(terry): TBD throw UnimplementedError; } @override void visitUnaryExpression(UnaryExpression node) { // TODO(terry): TBD throw UnimplementedError; } @override void visitIdentifier(Identifier node) { emit(node.name); } @override void visitWildcard(Wildcard node) { emit('*'); } @override void visitDartStyleExpression(DartStyleExpression node) { // TODO(terry): TBD throw UnimplementedError; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/csslib/src/validate.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:csslib/visitor.dart'; import 'package:source_span/source_span.dart'; /// Can be thrown on any Css runtime problem includes source location. class CssSelectorException extends SourceSpanException { CssSelectorException(String message, [SourceSpan span]) : super(message, span); } List<String> classes = []; List<String> ids = []; class Validate { static int _classNameCheck(SimpleSelectorSequence selector, int matches) { if (selector.isCombinatorDescendant || (selector.isCombinatorNone && matches == 0)) { if (matches < 0) { var tooMany = selector.simpleSelector.toString(); throw CssSelectorException( 'Can not mix Id selector with class selector(s). Id ' 'selector must be singleton too many starting at $tooMany'); } return matches + 1; } else { var error = selector.toString(); throw CssSelectorException( 'Selectors can not have combinators (>, +, or ~) before $error'); } } static int _elementIdCheck(SimpleSelectorSequence selector, int matches) { if (selector.isCombinatorNone && matches == 0) { // Perfect just one element id returns matches of -1. return -1; } else if (selector.isCombinatorDescendant) { var tooMany = selector.simpleSelector.toString(); throw CssSelectorException( 'Use of Id selector must be singleton starting at $tooMany'); } else { var error = selector.simpleSelector.toString(); throw CssSelectorException( 'Selectors can not have combinators (>, +, or ~) before $error'); } } // Validate the @{css expression} only .class and #elementId are valid inside // of @{...}. static void template(List<Selector> selectors) { var found = false; // signal if a selector is matched. var matches = 0; // < 0 IdSelectors, > 0 ClassSelector // At most one selector group (any number of simple selector sequences). assert(selectors.length <= 1); for (final sels in selectors) { for (final selector in sels.simpleSelectorSequences) { found = false; var simpleSelector = selector.simpleSelector; if (simpleSelector is ClassSelector) { // Any class name starting with an underscore is a private class name // that doesn't have to match the world of known classes. if (!simpleSelector.name.startsWith('_')) { // TODO(terry): For now iterate through all classes look for faster // mechanism hash map, etc. for (final className in classes) { if (selector.simpleSelector.name == className) { matches = _classNameCheck(selector, matches); found = true; // .class found. break; } for (final className2 in classes) { print(className2); } } } else { // Don't check any class name that is prefixed with an underscore. // However, signal as found and bump up matches; it's a valid class // name. matches = _classNameCheck(selector, matches); found = true; // ._class are always okay. } } else if (simpleSelector is IdSelector) { // Any element id starting with an underscore is a private element id // that doesn't have to match the world of known elemtn ids. if (!simpleSelector.name.startsWith('_')) { for (final id in ids) { if (simpleSelector.name == id) { matches = _elementIdCheck(selector, matches); found = true; // #id found. break; } } } else { // Don't check any element ID that is prefixed with an underscore. // Signal as found and bump up matches; it's a valid element ID. matches = _elementIdCheck(selector, matches); found = true; // #_id are always okay } } else { var badSelector = simpleSelector.toString(); throw CssSelectorException('Invalid template selector $badSelector'); } if (!found) { var unknownName = simpleSelector.toString(); throw CssSelectorException('Unknown selector name $unknownName'); } } } // Every selector must match. var selector = selectors[0]; assert((matches >= 0 ? matches : -matches) == selector.simpleSelectorSequences.length); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/source_span.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. export 'src/file.dart'; export 'src/location.dart'; export 'src/location_mixin.dart'; export 'src/span.dart'; export 'src/span_exception.dart'; export 'src/span_mixin.dart'; export 'src/span_with_context.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/location.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. import 'span.dart'; // TODO(nweiz): Use SourceLocationMixin once we decide to cut a release with // breaking changes. See SourceLocationMixin for details. /// A class that describes a single location within a source file. /// /// This class should not be extended. Instead, [SourceLocationBase] should be /// extended instead. class SourceLocation implements Comparable<SourceLocation> { /// URL of the source containing this location. /// /// This may be null, indicating that the source URL is unknown or /// unavailable. final Uri sourceUrl; /// The 0-based offset of this location in the source. final int offset; /// The 0-based line of this location in the source. final int line; /// The 0-based column of this location in the source final int column; /// Returns a representation of this location in the `source:line:column` /// format used by text editors. /// /// This prints 1-based lines and columns. String get toolString { final source = sourceUrl ?? 'unknown source'; return '$source:${line + 1}:${column + 1}'; } /// Creates a new location indicating [offset] within [sourceUrl]. /// /// [line] and [column] default to assuming the source is a single line. This /// means that [line] defaults to 0 and [column] defaults to [offset]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. SourceLocation(this.offset, {sourceUrl, int line, int column}) : sourceUrl = sourceUrl is String ? Uri.parse(sourceUrl) : sourceUrl as Uri, line = line ?? 0, column = column ?? offset { if (offset < 0) { throw RangeError('Offset may not be negative, was $offset.'); } else if (line != null && line < 0) { throw RangeError('Line may not be negative, was $line.'); } else if (column != null && column < 0) { throw RangeError('Column may not be negative, was $column.'); } } /// Returns the distance in characters between `this` and [other]. /// /// This always returns a non-negative value. int distance(SourceLocation other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' "\"${other.sourceUrl}\" don't match."); } return (offset - other.offset).abs(); } /// Returns a span that covers only a single point: this location. SourceSpan pointSpan() => SourceSpan(this, this, ''); /// Compares two locations. /// /// [other] must have the same source URL as `this`. @override int compareTo(SourceLocation other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' "\"${other.sourceUrl}\" don't match."); } return offset - other.offset; } @override bool operator ==(other) => other is SourceLocation && sourceUrl == other.sourceUrl && offset == other.offset; @override int get hashCode => sourceUrl.hashCode + offset; @override String toString() => '<$runtimeType: $offset $toolString>'; } /// A base class for source locations with [offset], [line], and [column] known /// at construction time. class SourceLocationBase extends SourceLocation { SourceLocationBase(int offset, {sourceUrl, int line, int column}) : super(offset, sourceUrl: sourceUrl, line: line, column: column); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/span_mixin.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. import 'package:path/path.dart' as p; import 'highlighter.dart'; import 'span.dart'; import 'span_with_context.dart'; import 'utils.dart'; /// A mixin for easily implementing [SourceSpan]. /// /// This implements the [SourceSpan] methods in terms of [start], [end], and /// [text]. This assumes that [start] and [end] have the same source URL, that /// [start] comes before [end], and that [text] has a number of characters equal /// to the distance between [start] and [end]. abstract class SourceSpanMixin implements SourceSpan { @override Uri get sourceUrl => start.sourceUrl; @override int get length => end.offset - start.offset; @override int compareTo(SourceSpan other) { final result = start.compareTo(other.start); return result == 0 ? end.compareTo(other.end) : result; } @override SourceSpan union(SourceSpan other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' " \"${other.sourceUrl}\" don't match."); } final start = min(this.start, other.start); final end = max(this.end, other.end); final beginSpan = start == this.start ? this : other; final endSpan = end == this.end ? this : other; if (beginSpan.end.compareTo(endSpan.start) < 0) { throw ArgumentError('Spans $this and $other are disjoint.'); } final text = beginSpan.text + endSpan.text.substring(beginSpan.end.distance(endSpan.start)); return SourceSpan(start, end, text); } @override String message(String message, {color}) { final buffer = StringBuffer() ..write('line ${start.line + 1}, column ${start.column + 1}'); if (sourceUrl != null) buffer.write(' of ${p.prettyUri(sourceUrl)}'); buffer.write(': $message'); final highlight = this.highlight(color: color); if (highlight.isNotEmpty) { buffer ..writeln() ..write(highlight); } return buffer.toString(); } @override String highlight({color}) { if (this is! SourceSpanWithContext && length == 0) return ''; return Highlighter(this, color: color).highlight(); } @override bool operator ==(other) => other is SourceSpan && start == other.start && end == other.end; @override int get hashCode => start.hashCode + (31 * end.hashCode); @override String toString() => '<$runtimeType: from $start to $end "$text">'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/highlighter.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:math' as math; import 'package:charcode/charcode.dart'; import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:term_glyph/term_glyph.dart' as glyph; import 'colors.dart' as colors; import 'location.dart'; import 'span.dart'; import 'span_with_context.dart'; import 'utils.dart'; /// A class for writing a chunk of text with a particular span highlighted. class Highlighter { /// The lines to display, including context around the highlighted spans. final List<_Line> _lines; /// The color to highlight the primary [_Highlight] within its context, or /// `null` if it should not be colored. final String _primaryColor; /// The color to highlight the secondary [_Highlight]s within their context, /// or `null` if they should not be colored. final String _secondaryColor; /// The number of characters before the bar in the sidebar. final int _paddingBeforeSidebar; /// The maximum number of multiline spans that cover any part of a single /// line in [_lines]. final int _maxMultilineSpans; /// Whether [_lines] includes lines from multiple different files. final bool _multipleFiles; /// The buffer to which to write the result. final _buffer = StringBuffer(); /// The number of spaces to render for hard tabs that appear in `_span.text`. /// /// We don't want to render raw tabs, because they'll mess up our character /// alignment. static const _spacesPerTab = 4; /// Creates a [Highlighter] that will return a string highlighting [span] /// within the text of its file when [highlight] is called. /// /// [color] may either be a [String], a [bool], or `null`. If it's a string, /// it indicates an [ANSI terminal color escape][] that should be used to /// highlight [span]'s text (for example, `"\u001b[31m"` will color red). If /// it's `true`, it indicates that the text should be highlighted using the /// default color. If it's `false` or `null`, it indicates that no color /// should be used. /// /// [ANSI terminal color escape]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors Highlighter(SourceSpan span, {color}) : this._(_collateLines([_Highlight(span, primary: true)]), () { if (color == true) return colors.red; if (color == false) return null; return color as String; }(), null); /// Creates a [Highlighter] that will return a string highlighting /// [primarySpan] as well as all the spans in [secondarySpans] within the text /// of their file when [highlight] is called. /// /// Each span has an associated label that will be written alongside it. For /// [primarySpan] this message is [primaryLabel], and for [secondarySpans] the /// labels are the map values. /// /// If [color] is `true`, this will use [ANSI terminal color escapes][] to /// highlight the text. The [primarySpan] will be highlighted with /// [primaryColor] (which defaults to red), and the [secondarySpans] will be /// highlighted with [secondaryColor] (which defaults to blue). These /// arguments are ignored if [color] is `false`. /// /// [ANSI terminal color escape]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors Highlighter.multiple(SourceSpan primarySpan, String primaryLabel, Map<SourceSpan, String> secondarySpans, {bool color = false, String primaryColor, String secondaryColor}) : this._( _collateLines([ _Highlight(primarySpan, label: primaryLabel, primary: true), for (var entry in secondarySpans.entries) _Highlight(entry.key, label: entry.value) ]), color ? (primaryColor ?? colors.red) : null, color ? (secondaryColor ?? colors.blue) : null); Highlighter._(this._lines, this._primaryColor, this._secondaryColor) : _paddingBeforeSidebar = 1 + math.max<int>( // In a purely mathematical world, floor(log10(n)) would give the // number of digits in n, but floating point errors render that // unreliable in practice. (_lines.last.number + 1).toString().length, // If [_lines] aren't contiguous, we'll write "..." in place of a // line number. _contiguous(_lines) ? 0 : 3), _maxMultilineSpans = _lines .map((line) => line.highlights .where((highlight) => isMultiline(highlight.span)) .length) .reduce(math.max), _multipleFiles = !isAllTheSame(_lines.map((line) => line.url)); /// Returns whether [lines] contains any adjacent lines from the same source /// file that aren't adjacent in the original file. static bool _contiguous(List<_Line> lines) { for (var i = 0; i < lines.length - 1; i++) { final thisLine = lines[i]; final nextLine = lines[i + 1]; if (thisLine.number + 1 != nextLine.number && thisLine.url == nextLine.url) { return false; } } return true; } /// Collect all the source lines from the contexts of all spans in /// [highlights], and associates them with the highlights that cover them. static List<_Line> _collateLines(List<_Highlight> highlights) { final highlightsByUrl = groupBy(highlights, (highlight) => highlight.span.sourceUrl); for (var list in highlightsByUrl.values) { list.sort((highlight1, highlight2) => highlight1.span.compareTo(highlight2.span)); } return highlightsByUrl.values.expand((highlightsForFile) { // First, create a list of all the lines in the current file that we have // context for along with their line numbers. final lines = <_Line>[]; for (var highlight in highlightsForFile) { final context = highlight.span.context; // If [highlight.span.context] contains lines prior to the one // [highlight.span.text] appears on, write those first. final lineStart = findLineStart( context, highlight.span.text, highlight.span.start.column); assert(lineStart != null); // enforced by [_normalizeContext] final linesBeforeSpan = '\n'.allMatches(context.substring(0, lineStart)).length; final url = highlight.span.sourceUrl; var lineNumber = highlight.span.start.line - linesBeforeSpan; for (var line in context.split('\n')) { // Only add a line if it hasn't already been added for a previous span. if (lines.isEmpty || lineNumber > lines.last.number) { lines.add(_Line(line, lineNumber, url)); } lineNumber++; } } // Next, associate each line with each highlights that covers it. final activeHighlights = <_Highlight>[]; var highlightIndex = 0; for (var line in lines) { activeHighlights.removeWhere((highlight) => highlight.span.sourceUrl != line.url || highlight.span.end.line < line.number); final oldHighlightLength = activeHighlights.length; for (var highlight in highlightsForFile.skip(highlightIndex)) { if (highlight.span.start.line > line.number) break; if (highlight.span.sourceUrl != line.url) break; activeHighlights.add(highlight); } highlightIndex += activeHighlights.length - oldHighlightLength; line.highlights.addAll(activeHighlights); } return lines; }).toList(); } /// Returns the highlighted span text. /// /// This method should only be called once. String highlight() { _writeFileStart(_lines.first.url); // Each index of this list represents a column after the sidebar that could // contain a line indicating an active highlight. If it's `null`, that // column is empty; if it contains a highlight, it should be drawn for that column. final highlightsByColumn = List<_Highlight>(_maxMultilineSpans); for (var i = 0; i < _lines.length; i++) { final line = _lines[i]; if (i > 0) { final lastLine = _lines[i - 1]; if (lastLine.url != line.url) { _writeSidebar(end: glyph.upEnd); _buffer.writeln(); _writeFileStart(line.url); } else if (lastLine.number + 1 != line.number) { _writeSidebar(text: '...'); _buffer.writeln(); } } // If a highlight covers the entire first line other than initial // whitespace, don't bother pointing out exactly where it begins. Iterate // in reverse so that longer highlights (which are sorted after shorter // highlights) appear further out, leading to fewer crossed lines. for (var highlight in line.highlights.reversed) { if (isMultiline(highlight.span) && highlight.span.start.line == line.number && _isOnlyWhitespace( line.text.substring(0, highlight.span.start.column))) { replaceFirstNull(highlightsByColumn, highlight); } } _writeSidebar(line: line.number); _buffer.write(' '); _writeMultilineHighlights(line, highlightsByColumn); if (highlightsByColumn.isNotEmpty) _buffer.write(' '); final primary = line.highlights .firstWhere((highlight) => highlight.isPrimary, orElse: () => null); if (primary != null) { _writeHighlightedText( line.text, primary.span.start.line == line.number ? primary.span.start.column : 0, primary.span.end.line == line.number ? primary.span.end.column : line.text.length, color: _primaryColor); } else { _writeText(line.text); } _buffer.writeln(); // Always write the primary span's indicator first so that it's right next // to the highlighted text. if (primary != null) _writeIndicator(line, primary, highlightsByColumn); for (var highlight in line.highlights) { if (highlight.isPrimary) continue; _writeIndicator(line, highlight, highlightsByColumn); } } _writeSidebar(end: glyph.upEnd); return _buffer.toString(); } /// Writes the beginning of the file highlight for the file with the given /// [url]. void _writeFileStart(Uri url) { if (!_multipleFiles || url == null) { _writeSidebar(end: glyph.downEnd); } else { _writeSidebar(end: glyph.topLeftCorner); _colorize(() => _buffer.write('${glyph.horizontalLine * 2}>'), color: colors.blue); _buffer.write(' ${p.prettyUri(url)}'); } _buffer.writeln(); } /// Writes the post-sidebar highlight bars for [line] according to /// [highlightsByColumn]. /// /// If [current] is passed, it's the highlight for which an indicator is being /// written. If it appears in [highlightsByColumn], a horizontal line is /// written from its column to the rightmost column. void _writeMultilineHighlights( _Line line, List<_Highlight> highlightsByColumn, {_Highlight current}) { // Whether we've written a sidebar indicator for opening a new span on this // line, and which color should be used for that indicator's rightward line. var openedOnThisLine = false; String openedOnThisLineColor; final currentColor = current == null ? null : current.isPrimary ? _primaryColor : _secondaryColor; var foundCurrent = false; for (var highlight in highlightsByColumn) { final startLine = highlight?.span?.start?.line; final endLine = highlight?.span?.end?.line; if (current != null && highlight == current) { foundCurrent = true; assert(startLine == line.number || endLine == line.number); _colorize(() { _buffer.write(startLine == line.number ? glyph.topLeftCorner : glyph.bottomLeftCorner); }, color: currentColor); } else if (foundCurrent) { _colorize(() { _buffer.write(highlight == null ? glyph.horizontalLine : glyph.cross); }, color: currentColor); } else if (highlight == null) { if (openedOnThisLine) { _colorize(() => _buffer.write(glyph.horizontalLine), color: openedOnThisLineColor); } else { _buffer.write(' '); } } else { _colorize(() { final vertical = openedOnThisLine ? glyph.cross : glyph.verticalLine; if (current != null) { _buffer.write(vertical); } else if (startLine == line.number) { _colorize(() { _buffer .write(glyph.glyphOrAscii(openedOnThisLine ? '┬' : '┌', '/')); }, color: openedOnThisLineColor); openedOnThisLine = true; openedOnThisLineColor ??= highlight.isPrimary ? _primaryColor : _secondaryColor; } else if (endLine == line.number && highlight.span.end.column == line.text.length) { _buffer.write(highlight.label == null ? glyph.glyphOrAscii('└', '\\') : vertical); } else { _colorize(() { _buffer.write(vertical); }, color: openedOnThisLineColor); } }, color: highlight.isPrimary ? _primaryColor : _secondaryColor); } } } // Writes [text], with text between [startColumn] and [endColumn] colorized in // the same way as [_colorize]. void _writeHighlightedText(String text, int startColumn, int endColumn, {@required String color}) { _writeText(text.substring(0, startColumn)); _colorize(() => _writeText(text.substring(startColumn, endColumn)), color: color); _writeText(text.substring(endColumn, text.length)); } /// Writes an indicator for where [highlight] starts, ends, or both below /// [line]. /// /// This may either add or remove [highlight] from [highlightsByColumn]. void _writeIndicator( _Line line, _Highlight highlight, List<_Highlight> highlightsByColumn) { final color = highlight.isPrimary ? _primaryColor : _secondaryColor; if (!isMultiline(highlight.span)) { _writeSidebar(); _buffer.write(' '); _writeMultilineHighlights(line, highlightsByColumn, current: highlight); if (highlightsByColumn.isNotEmpty) _buffer.write(' '); _colorize(() { _writeUnderline(line, highlight.span, highlight.isPrimary ? '^' : glyph.horizontalLineBold); _writeLabel(highlight.label); }, color: color); _buffer.writeln(); } else if (highlight.span.start.line == line.number) { if (highlightsByColumn.contains(highlight)) return; replaceFirstNull(highlightsByColumn, highlight); _writeSidebar(); _buffer.write(' '); _writeMultilineHighlights(line, highlightsByColumn, current: highlight); _colorize(() => _writeArrow(line, highlight.span.start.column), color: color); _buffer.writeln(); } else if (highlight.span.end.line == line.number) { final coversWholeLine = highlight.span.end.column == line.text.length; if (coversWholeLine && highlight.label == null) { replaceWithNull(highlightsByColumn, highlight); return; } _writeSidebar(); _buffer.write(' '); _writeMultilineHighlights(line, highlightsByColumn, current: highlight); _colorize(() { if (coversWholeLine) { _buffer.write(glyph.horizontalLine * 3); } else { _writeArrow(line, math.max(highlight.span.end.column - 1, 0), beginning: false); } _writeLabel(highlight.label); }, color: color); _buffer.writeln(); replaceWithNull(highlightsByColumn, highlight); } } /// Underlines the portion of [line] covered by [span] with repeated instances /// of [character]. void _writeUnderline(_Line line, SourceSpan span, String character) { assert(!isMultiline(span)); assert(line.text.contains(span.text)); var startColumn = span.start.column; var endColumn = span.end.column; // Adjust the start and end columns to account for any tabs that were // converted to spaces. final tabsBefore = _countTabs(line.text.substring(0, startColumn)); final tabsInside = _countTabs(line.text.substring(startColumn, endColumn)); startColumn += tabsBefore * (_spacesPerTab - 1); endColumn += (tabsBefore + tabsInside) * (_spacesPerTab - 1); _buffer ..write(' ' * startColumn) ..write(character * math.max(endColumn - startColumn, 1)); } /// Write an arrow pointing to column [column] in [line]. /// /// If the arrow points to a tab character, this will point to the beginning /// of the tab if [beginning] is `true` and the end if it's `false`. void _writeArrow(_Line line, int column, {bool beginning = true}) { final tabs = _countTabs(line.text.substring(0, column + (beginning ? 0 : 1))); _buffer ..write(glyph.horizontalLine * (1 + column + tabs * (_spacesPerTab - 1))) ..write('^'); } /// Writes a space followed by [label] if [label] isn't `null`. void _writeLabel(String label) { if (label != null) _buffer.write(' $label'); } /// Writes a snippet from the source text, converting hard tab characters into /// plain indentation. void _writeText(String text) { for (var char in text.codeUnits) { if (char == $tab) { _buffer.write(' ' * _spacesPerTab); } else { _buffer.writeCharCode(char); } } } // Writes a sidebar to [buffer] that includes [line] as the line number if // given and writes [end] at the end (defaults to [glyphs.verticalLine]). // // If [text] is given, it's used in place of the line number. It can't be // passed at the same time as [line]. void _writeSidebar({int line, String text, String end}) { assert(line == null || text == null); // Add 1 to line to convert from computer-friendly 0-indexed line numbers to // human-friendly 1-indexed line numbers. if (line != null) text = (line + 1).toString(); _colorize(() { _buffer ..write((text ?? '').padRight(_paddingBeforeSidebar)) ..write(end ?? glyph.verticalLine); }, color: colors.blue); } /// Returns the number of hard tabs in [text]. int _countTabs(String text) { var count = 0; for (var char in text.codeUnits) { if (char == $tab) count++; } return count; } /// Returns whether [text] contains only space or tab characters. bool _isOnlyWhitespace(String text) { for (var char in text.codeUnits) { if (char != $space && char != $tab) return false; } return true; } /// Colors all text written to [_buffer] during [callback], if colorization is /// enabled and [color] is not `null`. void _colorize(void Function() callback, {@required String color}) { if (_primaryColor != null && color != null) _buffer.write(color); callback(); if (_primaryColor != null && color != null) _buffer.write(colors.none); } } /// Information about how to highlight a single section of a source file. class _Highlight { /// The section of the source file to highlight. /// /// This is normalized to make it easier for [Highlighter] to work with. final SourceSpanWithContext span; /// Whether this is the primary span in the highlight. /// /// The primary span is highlighted with a different character and colored /// differently than non-primary spans. final bool isPrimary; /// The label to include inline when highlighting [span]. /// /// This helps distinguish clarify what each highlight means when multiple are /// used in the same message. final String label; _Highlight(SourceSpan span, {this.label, bool primary = false}) : span = (() { var newSpan = _normalizeContext(span); newSpan = _normalizeNewlines(newSpan); newSpan = _normalizeTrailingNewline(newSpan); return _normalizeEndOfLine(newSpan); })(), isPrimary = primary; /// Normalizes [span] to ensure that it's a [SourceSpanWithContext] whose /// context actually contains its text at the expected column. /// /// If it's not already a [SourceSpanWithContext], adjust the start and end /// locations' line and column fields so that the highlighter can assume they /// match up with the context. static SourceSpanWithContext _normalizeContext(SourceSpan span) => span is SourceSpanWithContext && findLineStart(span.context, span.text, span.start.column) != null ? span : SourceSpanWithContext( SourceLocation(span.start.offset, sourceUrl: span.sourceUrl, line: 0, column: 0), SourceLocation(span.end.offset, sourceUrl: span.sourceUrl, line: countCodeUnits(span.text, $lf), column: _lastLineLength(span.text)), span.text, span.text); /// Normalizes [span] to replace Windows-style newlines with Unix-style /// newlines. static SourceSpanWithContext _normalizeNewlines(SourceSpanWithContext span) { final text = span.text; if (!text.contains('\r\n')) return span; var endOffset = span.end.offset; for (var i = 0; i < text.length - 1; i++) { if (text.codeUnitAt(i) == $cr && text.codeUnitAt(i + 1) == $lf) { endOffset--; } } return SourceSpanWithContext( span.start, SourceLocation(endOffset, sourceUrl: span.sourceUrl, line: span.end.line, column: span.end.column), text.replaceAll('\r\n', '\n'), span.context.replaceAll('\r\n', '\n')); } /// Normalizes [span] to remove a trailing newline from `span.context`. /// /// If necessary, also adjust `span.end` so that it doesn't point past where /// the trailing newline used to be. static SourceSpanWithContext _normalizeTrailingNewline( SourceSpanWithContext span) { if (!span.context.endsWith('\n')) return span; // If there's a full blank line on the end of [span.context], it's probably // significant, so we shouldn't trim it. if (span.text.endsWith('\n\n')) return span; final context = span.context.substring(0, span.context.length - 1); var text = span.text; var start = span.start; var end = span.end; if (span.text.endsWith('\n') && _isTextAtEndOfContext(span)) { text = span.text.substring(0, span.text.length - 1); if (text.isEmpty) { end = start; } else { end = SourceLocation(span.end.offset - 1, sourceUrl: span.sourceUrl, line: span.end.line - 1, column: _lastLineLength(context)); start = span.start.offset == span.end.offset ? end : span.start; } } return SourceSpanWithContext(start, end, text, context); } /// Normalizes [span] so that the end location is at the end of a line rather /// than at the beginning of the next line. static SourceSpanWithContext _normalizeEndOfLine(SourceSpanWithContext span) { if (span.end.column != 0) return span; if (span.end.line == span.start.line) return span; final text = span.text.substring(0, span.text.length - 1); return SourceSpanWithContext( span.start, SourceLocation(span.end.offset - 1, sourceUrl: span.sourceUrl, line: span.end.line - 1, column: text.length - text.lastIndexOf('\n') - 1), text, // If the context also ends with a newline, it's possible that we don't // have the full context for that line, so we shouldn't print it at all. span.context.endsWith('\n') ? span.context.substring(0, span.context.length - 1) : span.context); } /// Returns the length of the last line in [text], whether or not it ends in a /// newline. static int _lastLineLength(String text) { if (text.isEmpty) { return 0; } else if (text.codeUnitAt(text.length - 1) == $lf) { return text.length == 1 ? 0 : text.length - text.lastIndexOf('\n', text.length - 2) - 1; } else { return text.length - text.lastIndexOf('\n') - 1; } } /// Returns whether [span]'s text runs all the way to the end of its context. static bool _isTextAtEndOfContext(SourceSpanWithContext span) => findLineStart(span.context, span.text, span.start.column) + span.start.column + span.length == span.context.length; @override String toString() { final buffer = StringBuffer(); if (isPrimary) buffer.write('primary '); buffer.write('${span.start.line}:${span.start.column}-' '${span.end.line}:${span.end.column}'); if (label != null) buffer.write(' ($label)'); return buffer.toString(); } } /// A single line of the source file being highlighted. class _Line { /// The text of the line, not including the trailing newline. final String text; /// The 0-based line number in the source file. final int number; /// The URL of the source file in which this line appears. final Uri url; /// All highlights that cover any portion of this line, in source span order. /// /// This is populated after the initial line is created. final highlights = <_Highlight>[]; _Line(this.text, this.number, this.url); @override String toString() => '$number: "$text" (${highlights.join(', ')})'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/span_exception.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. import 'span.dart'; /// A class for exceptions that have source span information attached. class SourceSpanException implements Exception { // This is a getter so that subclasses can override it. /// A message describing the exception. String get message => _message; final String _message; // This is a getter so that subclasses can override it. /// The span associated with this exception. /// /// This may be `null` if the source location can't be determined. SourceSpan get span => _span; final SourceSpan _span; SourceSpanException(this._message, this._span); /// Returns a string representation of `this`. /// /// [color] may either be a [String], a [bool], or `null`. If it's a string, /// it indicates an ANSI terminal color escape that should be used to /// highlight the span's text. If it's `true`, it indicates that the text /// should be highlighted using the default color. If it's `false` or `null`, /// it indicates that the text shouldn't be highlighted. @override String toString({color}) { if (span == null) return message; return 'Error on ${span.message(message, color: color)}'; } } /// A [SourceSpanException] that's also a [FormatException]. class SourceSpanFormatException extends SourceSpanException implements FormatException { @override final dynamic source; @override int get offset => span?.start?.offset; SourceSpanFormatException(String message, SourceSpan span, [this.source]) : super(message, span); } /// A [SourceSpanException] that also highlights some secondary spans to provide /// the user with extra context. /// /// Each span has a label ([primaryLabel] for the primary, and the values of the /// [secondarySpans] map for the secondary spans) that's used to indicate to the /// user what that particular span represents. class MultiSourceSpanException extends SourceSpanException { /// A label to attach to [span] that provides additional information and helps /// distinguish it from [secondarySpans]. final String primaryLabel; /// A map whose keys are secondary spans that should be highlighted. /// /// Each span's value is a label to attach to that span that provides /// additional information and helps distinguish it from [secondarySpans]. final Map<SourceSpan, String> secondarySpans; MultiSourceSpanException(String message, SourceSpan span, this.primaryLabel, Map<SourceSpan, String> secondarySpans) : secondarySpans = Map.unmodifiable(secondarySpans), super(message, span); /// Returns a string representation of `this`. /// /// [color] may either be a [String], a [bool], or `null`. If it's a string, /// it indicates an ANSI terminal color escape that should be used to /// highlight the primary span's text. If it's `true`, it indicates that the /// text should be highlighted using the default color. If it's `false` or /// `null`, it indicates that the text shouldn't be highlighted. /// /// If [color] is `true` or a string, [secondaryColor] is used to highlight /// [secondarySpans]. @override String toString({color, String secondaryColor}) { if (span == null) return message; var useColor = false; String primaryColor; if (color is String) { useColor = true; primaryColor = color; } else if (color == true) { useColor = true; } final formatted = span.messageMultiple( message, primaryLabel, secondarySpans, color: useColor, primaryColor: primaryColor, secondaryColor: secondaryColor); return 'Error on $formatted'; } } /// A [MultiSourceSpanException] that's also a [FormatException]. class MultiSourceSpanFormatException extends MultiSourceSpanException implements FormatException { @override final dynamic source; @override int get offset => span?.start?.offset; MultiSourceSpanFormatException(String message, SourceSpan span, String primaryLabel, Map<SourceSpan, String> secondarySpans, [this.source]) : super(message, span, primaryLabel, secondarySpans); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/file.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. import 'dart:math' as math; import 'dart:typed_data'; import 'location.dart'; import 'location_mixin.dart'; import 'span.dart'; import 'span_mixin.dart'; import 'span_with_context.dart'; // Constants to determine end-of-lines. const int _lf = 10; const int _cr = 13; /// A class representing a source file. /// /// This doesn't necessarily have to correspond to a file on disk, just a chunk /// of text usually with a URL associated with it. class SourceFile { /// The URL where the source file is located. /// /// This may be null, indicating that the URL is unknown or unavailable. final Uri url; /// An array of offsets for each line beginning in the file. /// /// Each offset refers to the first character *after* the newline. If the /// source file has a trailing newline, the final offset won't actually be in /// the file. final _lineStarts = <int>[0]; /// The code points of the characters in the file. final Uint32List _decodedChars; /// The length of the file in characters. int get length => _decodedChars.length; /// The number of lines in the file. int get lines => _lineStarts.length; /// The line that the offset fell on the last time [getLine] was called. /// /// In many cases, sequential calls to getLine() are for nearby, usually /// increasing offsets. In that case, we can find the line for an offset /// quickly by first checking to see if the offset is on the same line as the /// previous result. int _cachedLine; /// This constructor is deprecated. /// /// Use [new SourceFile.fromString] instead. @Deprecated('Will be removed in 2.0.0') SourceFile(String text, {url}) : this.decoded(text.runes, url: url); /// Creates a new source file from [text]. /// /// [url] may be either a [String], a [Uri], or `null`. SourceFile.fromString(String text, {url}) : this.decoded(text.codeUnits, url: url); /// Creates a new source file from a list of decoded code units. /// /// [url] may be either a [String], a [Uri], or `null`. /// /// Currently, if [decodedChars] contains characters larger than `0xFFFF`, /// they'll be treated as single characters rather than being split into /// surrogate pairs. **This behavior is deprecated**. For /// forwards-compatibility, callers should only pass in characters less than /// or equal to `0xFFFF`. SourceFile.decoded(Iterable<int> decodedChars, {url}) : url = url is String ? Uri.parse(url) : url as Uri, _decodedChars = Uint32List.fromList(decodedChars.toList()) { for (var i = 0; i < _decodedChars.length; i++) { var c = _decodedChars[i]; if (c == _cr) { // Return not followed by newline is treated as a newline final j = i + 1; if (j >= _decodedChars.length || _decodedChars[j] != _lf) c = _lf; } if (c == _lf) _lineStarts.add(i + 1); } } /// Returns a span from [start] to [end] (exclusive). /// /// If [end] isn't passed, it defaults to the end of the file. FileSpan span(int start, [int end]) { end ??= length; return _FileSpan(this, start, end); } /// Returns a location at [offset]. FileLocation location(int offset) => FileLocation._(this, offset); /// Gets the 0-based line corresponding to [offset]. int getLine(int offset) { if (offset < 0) { throw RangeError('Offset may not be negative, was $offset.'); } else if (offset > length) { throw RangeError('Offset $offset must not be greater than the number ' 'of characters in the file, $length.'); } if (offset < _lineStarts.first) return -1; if (offset >= _lineStarts.last) return _lineStarts.length - 1; if (_isNearCachedLine(offset)) return _cachedLine; _cachedLine = _binarySearch(offset) - 1; return _cachedLine; } /// Returns `true` if [offset] is near [_cachedLine]. /// /// Checks on [_cachedLine] and the next line. If it's on the next line, it /// updates [_cachedLine] to point to that. bool _isNearCachedLine(int offset) { if (_cachedLine == null) return false; // See if it's before the cached line. if (offset < _lineStarts[_cachedLine]) return false; // See if it's on the cached line. if (_cachedLine >= _lineStarts.length - 1 || offset < _lineStarts[_cachedLine + 1]) { return true; } // See if it's on the next line. if (_cachedLine >= _lineStarts.length - 2 || offset < _lineStarts[_cachedLine + 2]) { _cachedLine++; return true; } return false; } /// Binary search through [_lineStarts] to find the line containing [offset]. /// /// Returns the index of the line in [_lineStarts]. int _binarySearch(int offset) { var min = 0; var max = _lineStarts.length - 1; while (min < max) { final half = min + ((max - min) ~/ 2); if (_lineStarts[half] > offset) { max = half; } else { min = half + 1; } } return max; } /// Gets the 0-based column corresponding to [offset]. /// /// If [line] is passed, it's assumed to be the line containing [offset] and /// is used to more efficiently compute the column. int getColumn(int offset, {int line}) { if (offset < 0) { throw RangeError('Offset may not be negative, was $offset.'); } else if (offset > length) { throw RangeError('Offset $offset must be not be greater than the ' 'number of characters in the file, $length.'); } if (line == null) { line = getLine(offset); } else if (line < 0) { throw RangeError('Line may not be negative, was $line.'); } else if (line >= lines) { throw RangeError('Line $line must be less than the number of ' 'lines in the file, $lines.'); } final lineStart = _lineStarts[line]; if (lineStart > offset) { throw RangeError('Line $line comes after offset $offset.'); } return offset - lineStart; } /// Gets the offset for a [line] and [column]. /// /// [column] defaults to 0. int getOffset(int line, [int column]) { column ??= 0; if (line < 0) { throw RangeError('Line may not be negative, was $line.'); } else if (line >= lines) { throw RangeError('Line $line must be less than the number of ' 'lines in the file, $lines.'); } else if (column < 0) { throw RangeError('Column may not be negative, was $column.'); } final result = _lineStarts[line] + column; if (result > length || (line + 1 < lines && result >= _lineStarts[line + 1])) { throw RangeError("Line $line doesn't have $column columns."); } return result; } /// Returns the text of the file from [start] to [end] (exclusive). /// /// If [end] isn't passed, it defaults to the end of the file. String getText(int start, [int end]) => String.fromCharCodes(_decodedChars.sublist(start, end)); } /// A [SourceLocation] within a [SourceFile]. /// /// Unlike the base [SourceLocation], [FileLocation] lazily computes its line /// and column values based on its offset and the contents of [file]. /// /// A [FileLocation] can be created using [SourceFile.location]. class FileLocation extends SourceLocationMixin implements SourceLocation { /// The [file] that `this` belongs to. final SourceFile file; @override final int offset; @override Uri get sourceUrl => file.url; @override int get line => file.getLine(offset); @override int get column => file.getColumn(offset); FileLocation._(this.file, this.offset) { if (offset < 0) { throw RangeError('Offset may not be negative, was $offset.'); } else if (offset > file.length) { throw RangeError('Offset $offset must not be greater than the number ' 'of characters in the file, ${file.length}.'); } } @override FileSpan pointSpan() => _FileSpan(file, offset, offset); } /// A [SourceSpan] within a [SourceFile]. /// /// Unlike the base [SourceSpan], [FileSpan] lazily computes its line and column /// values based on its offset and the contents of [file]. [SourceSpan.message] /// is also able to provide more context then [SourceSpan.message], and /// [SourceSpan.union] will return a [FileSpan] if possible. /// /// A [FileSpan] can be created using [SourceFile.span]. abstract class FileSpan implements SourceSpanWithContext { /// The [file] that `this` belongs to. SourceFile get file; @override FileLocation get start; @override FileLocation get end; /// Returns a new span that covers both `this` and [other]. /// /// Unlike [union], [other] may be disjoint from `this`. If it is, the text /// between the two will be covered by the returned span. FileSpan expand(FileSpan other); } /// The implementation of [FileSpan]. /// /// This is split into a separate class so that `is _FileSpan` checks can be run /// to make certain operations more efficient. If we used `is FileSpan`, that /// would break if external classes implemented the interface. class _FileSpan extends SourceSpanMixin implements FileSpan { @override final SourceFile file; /// The offset of the beginning of the span. /// /// [start] is lazily generated from this to avoid allocating unnecessary /// objects. final int _start; /// The offset of the end of the span. /// /// [end] is lazily generated from this to avoid allocating unnecessary /// objects. final int _end; @override Uri get sourceUrl => file.url; @override int get length => _end - _start; @override FileLocation get start => FileLocation._(file, _start); @override FileLocation get end => FileLocation._(file, _end); @override String get text => file.getText(_start, _end); @override String get context { final endLine = file.getLine(_end); final endColumn = file.getColumn(_end); int endOffset; if (endColumn == 0 && endLine != 0) { // If [end] is at the very beginning of the line, the span covers the // previous newline, so we only want to include the previous line in the // context... if (length == 0) { // ...unless this is a point span, in which case we want to include the // next line (or the empty string if this is the end of the file). return endLine == file.lines - 1 ? '' : file.getText( file.getOffset(endLine), file.getOffset(endLine + 1)); } endOffset = _end; } else if (endLine == file.lines - 1) { // If the span covers the last line of the file, the context should go all // the way to the end of the file. endOffset = file.length; } else { // Otherwise, the context should cover the full line on which [end] // appears. endOffset = file.getOffset(endLine + 1); } return file.getText(file.getOffset(file.getLine(_start)), endOffset); } _FileSpan(this.file, this._start, this._end) { if (_end < _start) { throw ArgumentError('End $_end must come after start $_start.'); } else if (_end > file.length) { throw RangeError('End $_end must not be greater than the number ' 'of characters in the file, ${file.length}.'); } else if (_start < 0) { throw RangeError('Start may not be negative, was $_start.'); } } @override int compareTo(SourceSpan other) { if (other is! _FileSpan) return super.compareTo(other); final otherFile = other as _FileSpan; final result = _start.compareTo(otherFile._start); return result == 0 ? _end.compareTo(otherFile._end) : result; } @override SourceSpan union(SourceSpan other) { if (other is! FileSpan) return super.union(other); final span = expand(other as _FileSpan); if (other is _FileSpan) { if (_start > other._end || other._start > _end) { throw ArgumentError('Spans $this and $other are disjoint.'); } } else { if (_start > other.end.offset || other.start.offset > _end) { throw ArgumentError('Spans $this and $other are disjoint.'); } } return span; } @override bool operator ==(other) { if (other is! FileSpan) return super == other; if (other is! _FileSpan) { return super == other && sourceUrl == other.sourceUrl; } return _start == other._start && _end == other._end && sourceUrl == other.sourceUrl; } // Eliminates dart2js warning about overriding `==`, but not `hashCode` @override int get hashCode => super.hashCode; /// Returns a new span that covers both `this` and [other]. /// /// Unlike [union], [other] may be disjoint from `this`. If it is, the text /// between the two will be covered by the returned span. @override FileSpan expand(FileSpan other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' " \"${other.sourceUrl}\" don't match."); } if (other is _FileSpan) { final start = math.min(_start, other._start); final end = math.max(_end, other._end); return _FileSpan(file, start, end); } else { final start = math.min(_start, other.start.offset); final end = math.max(_end, other.end.offset); return _FileSpan(file, start, end); } } /// See `SourceSpanExtension.subspan`. FileSpan subspan(int start, [int end]) { RangeError.checkValidRange(start, end, length); if (start == 0 && (end == null || end == length)) return this; return file.span(_start + start, end == null ? _end : _start + end); } } // TODO(#52): Move these to instance methods in the next breaking release. /// Extension methods on the [FileSpan] API. extension FileSpanExtension on FileSpan { /// See `SourceSpanExtension.subspan`. FileSpan subspan(int start, [int end]) { RangeError.checkValidRange(start, end, length); if (start == 0 && (end == null || end == length)) return this; final startOffset = this.start.offset; return file.span( startOffset + start, end == null ? this.end.offset : startOffset + end); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/span.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. import 'package:charcode/charcode.dart'; import 'package:path/path.dart' as p; import 'package:term_glyph/term_glyph.dart' as glyph; import 'file.dart'; import 'highlighter.dart'; import 'location.dart'; import 'span_mixin.dart'; import 'span_with_context.dart'; /// A class that describes a segment of source text. abstract class SourceSpan implements Comparable<SourceSpan> { /// The start location of this span. SourceLocation get start; /// The end location of this span, exclusive. SourceLocation get end; /// The source text for this span. String get text; /// The URL of the source (typically a file) of this span. /// /// This may be null, indicating that the source URL is unknown or /// unavailable. Uri get sourceUrl; /// The length of this span, in characters. int get length; /// Creates a new span from [start] to [end] (exclusive) containing [text]. /// /// [start] and [end] must have the same source URL and [start] must come /// before [end]. [text] must have a number of characters equal to the /// distance between [start] and [end]. factory SourceSpan(SourceLocation start, SourceLocation end, String text) => SourceSpanBase(start, end, text); /// Creates a new span that's the union of `this` and [other]. /// /// The two spans must have the same source URL and may not be disjoint. /// [text] is computed by combining `this.text` and `other.text`. SourceSpan union(SourceSpan other); /// Compares two spans. /// /// [other] must have the same source URL as `this`. This orders spans by /// [start] then [length]. @override int compareTo(SourceSpan other); /// Formats [message] in a human-friendly way associated with this span. /// /// [color] may either be a [String], a [bool], or `null`. If it's a string, /// it indicates an [ANSI terminal color escape][] that should /// be used to highlight the span's text (for example, `"\u001b[31m"` will /// color red). If it's `true`, it indicates that the text should be /// highlighted using the default color. If it's `false` or `null`, it /// indicates that the text shouldn't be highlighted. /// /// This uses the full range of Unicode characters to highlight the source /// span if [glyph.ascii] is `false` (the default), but only uses ASCII /// characters if it's `true`. /// /// [ANSI terminal color escape]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors String message(String message, {color}); /// Prints the text associated with this span in a user-friendly way. /// /// This is identical to [message], except that it doesn't print the file /// name, line number, column number, or message. If [length] is 0 and this /// isn't a [SourceSpanWithContext], returns an empty string. /// /// [color] may either be a [String], a [bool], or `null`. If it's a string, /// it indicates an [ANSI terminal color escape][] that should /// be used to highlight the span's text (for example, `"\u001b[31m"` will /// color red). If it's `true`, it indicates that the text should be /// highlighted using the default color. If it's `false` or `null`, it /// indicates that the text shouldn't be highlighted. /// /// This uses the full range of Unicode characters to highlight the source /// span if [glyph.ascii] is `false` (the default), but only uses ASCII /// characters if it's `true`. /// /// [ANSI terminal color escape]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors String highlight({color}); } /// A base class for source spans with [start], [end], and [text] known at /// construction time. class SourceSpanBase extends SourceSpanMixin { @override final SourceLocation start; @override final SourceLocation end; @override final String text; SourceSpanBase(this.start, this.end, this.text) { if (end.sourceUrl != start.sourceUrl) { throw ArgumentError('Source URLs \"${start.sourceUrl}\" and ' " \"${end.sourceUrl}\" don't match."); } else if (end.offset < start.offset) { throw ArgumentError('End $end must come after start $start.'); } else if (text.length != start.distance(end)) { throw ArgumentError('Text "$text" must be ${start.distance(end)} ' 'characters long.'); } } } // TODO(#52): Move these to instance methods in the next breaking release. /// Extension methods on the base [SourceSpan] API. extension SourceSpanExtension on SourceSpan { /// Like [SourceSpan.message], but also highlights [secondarySpans] to provide /// the user with additional context. /// /// Each span takes a label ([label] for this span, and the values of the /// [secondarySpans] map for the secondary spans) that's used to indicate to /// the user what that particular span represents. /// /// If [color] is `true`, [ANSI terminal color escapes][] are used to color /// the resulting string. By default this span is colored red and the /// secondary spans are colored blue, but that can be customized by passing /// ANSI escape strings to [primaryColor] or [secondaryColor]. /// /// [ANSI terminal color escapes]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors /// /// Each span in [secondarySpans] must refer to the same document as this /// span. Throws an [ArgumentError] if any secondary span has a different /// source URL than this span. /// /// Note that while this will work with plain [SourceSpan]s, it will produce /// much more useful output with [SourceSpanWithContext]s (including /// [FileSpan]s). String messageMultiple( String message, String label, Map<SourceSpan, String> secondarySpans, {bool color = false, String primaryColor, String secondaryColor}) { final buffer = StringBuffer() ..write('line ${start.line + 1}, column ${start.column + 1}'); if (sourceUrl != null) buffer.write(' of ${p.prettyUri(sourceUrl)}'); buffer ..writeln(': $message') ..write(highlightMultiple(label, secondarySpans, color: color, primaryColor: primaryColor, secondaryColor: secondaryColor)); return buffer.toString(); } /// Like [SourceSpan.highlight], but also highlights [secondarySpans] to /// provide the user with additional context. /// /// Each span takes a label ([label] for this span, and the values of the /// [secondarySpans] map for the secondary spans) that's used to indicate to /// the user what that particular span represents. /// /// If [color] is `true`, [ANSI terminal color escapes][] are used to color /// the resulting string. By default this span is colored red and the /// secondary spans are colored blue, but that can be customized by passing /// ANSI escape strings to [primaryColor] or [secondaryColor]. /// /// [ANSI terminal color escapes]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors /// /// Each span in [secondarySpans] must refer to the same document as this /// span. Throws an [ArgumentError] if any secondary span has a different /// source URL than this span. /// /// Note that while this will work with plain [SourceSpan]s, it will produce /// much more useful output with [SourceSpanWithContext]s (including /// [FileSpan]s). String highlightMultiple(String label, Map<SourceSpan, String> secondarySpans, {bool color = false, String primaryColor, String secondaryColor}) => Highlighter.multiple(this, label, secondarySpans, color: color, primaryColor: primaryColor, secondaryColor: secondaryColor) .highlight(); /// Returns a span from [start] code units (inclusive) to [end] code units /// (exclusive) after the beginning of this span. SourceSpan subspan(int start, [int end]) { RangeError.checkValidRange(start, end, length); if (start == 0 && (end == null || end == length)) return this; final text = this.text; final startLocation = this.start; var line = startLocation.line; var column = startLocation.column; // Adjust [line] and [column] as necessary if the character at [i] in [text] // is a newline. void consumeCodePoint(int i) { final codeUnit = text.codeUnitAt(i); if (codeUnit == $lf || // A carriage return counts as a newline, but only if it's not // followed by a line feed. (codeUnit == $cr && (i + 1 == text.length || text.codeUnitAt(i + 1) != $lf))) { line += 1; column = 0; } else { column += 1; } } for (var i = 0; i < start; i++) { consumeCodePoint(i); } final newStartLocation = SourceLocation(startLocation.offset + start, sourceUrl: sourceUrl, line: line, column: column); SourceLocation newEndLocation; if (end == null || end == length) { newEndLocation = this.end; } else if (end == start) { newEndLocation = newStartLocation; } else if (end != null && end != length) { for (var i = start; i < end; i++) { consumeCodePoint(i); } newEndLocation = SourceLocation(startLocation.offset + end, sourceUrl: sourceUrl, line: line, column: column); } return SourceSpan( newStartLocation, newEndLocation, text.substring(start, end)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/colors.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. // Color constants used for generating messages. const String red = '\u001b[31m'; const String yellow = '\u001b[33m'; const String blue = '\u001b[34m'; const String none = '\u001b[0m';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/utils.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. import 'span.dart'; /// Returns the minimum of [obj1] and [obj2] according to /// [Comparable.compareTo]. T min<T extends Comparable>(T obj1, T obj2) => obj1.compareTo(obj2) > 0 ? obj2 : obj1; /// Returns the maximum of [obj1] and [obj2] according to /// [Comparable.compareTo]. T max<T extends Comparable>(T obj1, T obj2) => obj1.compareTo(obj2) > 0 ? obj1 : obj2; /// Returns whether all elements of [iter] are the same value, according to /// `==`. /// /// Assumes [iter] doesn't contain any `null` values. bool isAllTheSame(Iterable<Object> iter) { Object lastValue; for (var value in iter) { if (lastValue == null) { lastValue = value; } else if (value != lastValue) { return false; } } return true; } /// Returns whether [span] covers multiple lines. bool isMultiline(SourceSpan span) => span.start.line != span.end.line; /// Sets the first `null` element of [list] to [element]. void replaceFirstNull<E>(List<E> list, E element) { final index = list.indexOf(null); if (index < 0) throw ArgumentError('$list contains no null elements.'); list[index] = element; } /// Sets the element of [list] that currently contains [element] to `null`. void replaceWithNull<E>(List<E> list, E element) { final index = list.indexOf(element); if (index < 0) { throw ArgumentError('$list contains no elements matching $element.'); } list[index] = null; } /// Returns the number of instances of [codeUnit] in [string]. int countCodeUnits(String string, int codeUnit) { var count = 0; for (var codeUnitToCheck in string.codeUnits) { if (codeUnitToCheck == codeUnit) count++; } return count; } /// Finds a line in [context] containing [text] at the specified [column]. /// /// Returns the index in [context] where that line begins, or null if none /// exists. int findLineStart(String context, String text, int column) { // If the text is empty, we just want to find the first line that has at least // [column] characters. if (text.isEmpty) { var beginningOfLine = 0; while (true) { final index = context.indexOf('\n', beginningOfLine); if (index == -1) { return context.length - beginningOfLine >= column ? beginningOfLine : null; } if (index - beginningOfLine >= column) return beginningOfLine; beginningOfLine = index + 1; } } var index = context.indexOf(text); while (index != -1) { // Start looking before [index] in case [text] starts with a newline. final lineStart = index == 0 ? 0 : context.lastIndexOf('\n', index - 1) + 1; final textColumn = index - lineStart; if (column == textColumn) return lineStart; index = context.indexOf(text, index + 1); } // ignore: avoid_returning_null return null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/location_mixin.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 'location.dart'; import 'span.dart'; // Note: this class duplicates a lot of functionality of [SourceLocation]. This // is because in order for SourceLocation to use SourceLocationMixin, // SourceLocationMixin couldn't implement SourceLocation. In SourceSpan we // handle this by making the class itself non-extensible, but that would be a // breaking change for SourceLocation. So until we want to endure the pain of // cutting a release with breaking changes, we duplicate the code here. /// A mixin for easily implementing [SourceLocation]. abstract class SourceLocationMixin implements SourceLocation { @override String get toolString { final source = sourceUrl ?? 'unknown source'; return '$source:${line + 1}:${column + 1}'; } @override int distance(SourceLocation other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' "\"${other.sourceUrl}\" don't match."); } return (offset - other.offset).abs(); } @override SourceSpan pointSpan() => SourceSpan(this, this, ''); @override int compareTo(SourceLocation other) { if (sourceUrl != other.sourceUrl) { throw ArgumentError('Source URLs \"$sourceUrl\" and ' "\"${other.sourceUrl}\" don't match."); } return offset - other.offset; } @override bool operator ==(other) => other is SourceLocation && sourceUrl == other.sourceUrl && offset == other.offset; @override int get hashCode => sourceUrl.hashCode + offset; @override String toString() => '<$runtimeType: $offset $toolString>'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/source_span/src/span_with_context.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. import 'location.dart'; import 'span.dart'; import 'utils.dart'; /// A class that describes a segment of source text with additional context. class SourceSpanWithContext extends SourceSpanBase { // This is a getter so that subclasses can override it. /// Text around the span, which includes the line containing this span. String get context => _context; final String _context; /// Creates a new span from [start] to [end] (exclusive) containing [text], in /// the given [context]. /// /// [start] and [end] must have the same source URL and [start] must come /// before [end]. [text] must have a number of characters equal to the /// distance between [start] and [end]. [context] must contain [text], and /// [text] should start at `start.column` from the beginning of a line in /// [context]. SourceSpanWithContext( SourceLocation start, SourceLocation end, String text, this._context) : super(start, end, text) { if (!context.contains(text)) { throw ArgumentError('The context line "$context" must contain "$text".'); } if (findLineStart(context, text, start.column) == null) { throw ArgumentError('The span text "$text" must start at ' 'column ${start.column + 1} in a line within "$context".'); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/stream_transform.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. export 'src/async_map.dart'; export 'src/combine_latest.dart'; export 'src/concatenate.dart'; export 'src/merge.dart'; export 'src/rate_limit.dart'; export 'src/scan.dart'; export 'src/switch.dart'; export 'src/take_until.dart'; export 'src/tap.dart'; export 'src/where.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/rate_limit.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 'aggregate_sample.dart'; import 'from_handlers.dart'; /// Utilities to rate limit events. /// /// - [debounce] - emit the the _first_ or _last_ event of a series of closely /// spaced events. /// - [debounceBuffer] - emit _all_ events at the _end_ of a series of closely /// spaced events. /// - [throttle] - emit the _first_ event at the _beginning_ of the period. /// - [audit] - emit the _last_ event at the _end_ of the period. /// - [buffer] - emit _all_ events on a _trigger_. extension RateLimit<T> on Stream<T> { /// Returns a Stream which suppresses events with less inter-event spacing /// than [duration]. /// /// Events which are emitted with less than [duration] elapsed between them /// are considered to be part of the same "series". If [leading] is `true`, /// the first event of this series is emitted immediately. If [trailing] is /// `true` the last event of this series is emitted with a delay of at least /// [duration]. By default only trailing events are emitted, both arguments /// must be specified with `leading: true, trailing: false` to emit only /// leading events. /// /// If the source stream is a broadcast stream, the result will be as well. /// Errors are forwarded immediately. /// /// If there is a trailing event waiting during the debounce period when the /// source stream closes the returned stream will wait to emit it following /// the debounce period before closing. If there is no pending debounced event /// when the source stream closes the returned stream will close immediately. /// /// For example: /// /// source.debouce(Duration(seconds: 1)); /// /// source: 1-2-3---4---5-6-| /// result: ------3---4-----6| /// /// source.debouce(Duration(seconds: 1), leading: true, trailing: false); /// /// source: 1-2-3---4---5-6-| /// result: 1-------4---5---| /// /// source.debouce(Duration(seconds: 1), leading: true); /// /// source: 1-2-3---4---5-6-| /// result: 1-----3-4---5---6| /// /// To collect values emitted during the debounce period see [debounceBuffer]. Stream<T> debounce(Duration duration, {bool leading = false, bool trailing = true}) => transform(_debounceAggregate(duration, _dropPrevious, leading: leading, trailing: trailing)); /// Returns a Stream which collects values until the source stream does not /// emit for [duration] then emits the collected values. /// /// Values will always be delayed by at least [duration], and values which /// come within this time will be aggregated into the same list. /// /// If the source stream is a broadcast stream, the result will be as well. /// Errors are forwarded immediately. /// /// If there are events waiting during the debounce period when the source /// stream closes the returned stream will wait to emit them following the /// debounce period before closing. If there are no pending debounced events /// when the source stream closes the returned stream will close immediately. /// /// To keep only the most recent event during the debounce perios see /// [debounce]. Stream<List<T>> debounceBuffer(Duration duration) => transform(_debounceAggregate(duration, _collectToList, leading: false, trailing: true)); /// Returns a stream which only emits once per [duration], at the beginning of /// the period. /// /// Events emitted by the source stream within [duration] following an emitted /// event will be discarded. Errors are always forwarded immediately. Stream<T> throttle(Duration duration) { Timer timer; return transform(fromHandlers(handleData: (data, sink) { if (timer == null) { sink.add(data); timer = Timer(duration, () { timer = null; }); } })); } /// Returns a Stream which only emits once per [duration], at the end of the /// period. /// /// If the source stream is a broadcast stream, the result will be as well. /// Errors are forwarded immediately. /// /// If there is no pending event when the source stream closes the output /// stream will close immediately. If there is a pending event the output /// stream will wait to emit it before closing. /// /// Differs from `throttle` in that it always emits the most recently received /// event rather than the first in the period. The events that are emitted are /// always delayed by some amount. If the event that started the period is the /// one that is emitted it will be delayed by [duration]. If a later event /// comes in within the period it's delay will be shorter by the difference in /// arrival times. /// /// Differs from `debounce` in that a value will always be emitted after /// [duration], the output will not be starved by values coming in repeatedly /// within [duration]. /// /// For example: /// /// source.audit(Duration(seconds: 5)); /// /// source: a------b--c----d--| /// output: -----a------c--------d| Stream<T> audit(Duration duration) { Timer timer; var shouldClose = false; T recentData; return transform(fromHandlers(handleData: (T data, EventSink<T> sink) { recentData = data; timer ??= Timer(duration, () { sink.add(recentData); timer = null; if (shouldClose) { sink.close(); } }); }, handleDone: (EventSink<T> sink) { if (timer != null) { shouldClose = true; } else { sink.close(); } })); } /// Returns a Stream which collects values and emits when it sees a value on /// [trigger]. /// /// If there are no pending values when [trigger] emits, the next value on the /// source Stream will immediately flow through. Otherwise, the pending values /// are released when [trigger] emits. /// /// If the source stream is a broadcast stream, the result will be as well. /// Errors from the source stream or the trigger are immediately forwarded to /// the output. Stream<List<T>> buffer(Stream<void> trigger) => transform(AggregateSample<T, List<T>>(trigger, _collect)); } List<T> _collectToList<T>(T element, List<T> soFar) { soFar ??= <T>[]; soFar.add(element); return soFar; } T _dropPrevious<T>(T element, _) => element; /// Creates a StreamTransformer which aggregates values until the source stream /// does not emit for [duration], then emits the aggregated values. StreamTransformer<T, R> _debounceAggregate<T, R>( Duration duration, R Function(T element, R soFar) collect, {bool leading, bool trailing}) { Timer timer; R soFar; var shouldClose = false; var emittedLatestAsLeading = false; return fromHandlers(handleData: (T value, EventSink<R> sink) { timer?.cancel(); soFar = collect(value, soFar); if (timer == null && leading) { emittedLatestAsLeading = true; sink.add(soFar); } else { emittedLatestAsLeading = false; } timer = Timer(duration, () { if (trailing && !emittedLatestAsLeading) sink.add(soFar); if (shouldClose) { sink.close(); } soFar = null; timer = null; }); }, handleDone: (EventSink<R> sink) { if (soFar != null && trailing) { shouldClose = true; } else { timer?.cancel(); sink.close(); } }); } List<T> _collect<T>(T event, List<T> soFar) => (soFar ?? <T>[])..add(event);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/concatenate.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'; /// Utilities to append or prepend to a stream. extension Concatenate<T> on Stream<T> { /// Returns a stream which emits values and errors from [next] after the /// original stream is complete. /// /// If the source stream never finishes, the [next] stream will never be /// listened to. /// /// If the source stream is a broadcast stream, the result will be as well. /// If a single-subscription follows a broadcast stream it may be listened /// to and never canceled since there may be broadcast listeners added later. /// /// If a broadcast stream follows any other stream it will miss any events or /// errors which occur before the first stream is done. If a broadcast stream /// follows a single-subscription stream, pausing the stream while it is /// listening to the second stream will cause events to be dropped rather than /// buffered. Stream<T> followedBy(Stream<T> next) => transform(_FollowedBy(next)); /// Returns a stream which emits [initial] before any values from the original /// stream. /// /// If the original stream is a broadcast stream the result will be as well. Stream<T> startWith(T initial) => startWithStream(Future.value(initial).asStream()); /// Returns a stream which emits all values in [initial] before any values /// from the original stream. /// /// If the original stream is a broadcast stream the result will be as well. /// If the original stream is a broadcast stream it will miss any events which /// occur before the initial values are all emitted. Stream<T> startWithMany(Iterable<T> initial) => startWithStream(Stream.fromIterable(initial)); /// Returns a stream which emits all values in [initial] before any values /// from the original stream. /// /// If the original stream is a broadcast stream the result will be as well. If /// the original stream is a broadcast stream it will miss any events which /// occur before [initial] closes. Stream<T> startWithStream(Stream<T> initial) { if (isBroadcast && !initial.isBroadcast) { initial = initial.asBroadcastStream(); } return initial.followedBy(this); } } class _FollowedBy<T> extends StreamTransformerBase<T, T> { final Stream<T> _next; _FollowedBy(this._next); @override Stream<T> bind(Stream<T> first) { var controller = first.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); var next = first.isBroadcast && !_next.isBroadcast ? _next.asBroadcastStream() : _next; StreamSubscription<T> subscription; var currentStream = first; var firstDone = false; var secondDone = false; Function currentDoneHandler; void listen() { subscription = currentStream.listen(controller.add, onError: controller.addError, onDone: () => currentDoneHandler()); } void onSecondDone() { secondDone = true; controller.close(); } void onFirstDone() { firstDone = true; currentStream = next; currentDoneHandler = onSecondDone; listen(); } currentDoneHandler = onFirstDone; controller.onListen = () { assert(subscription == null); listen(); if (!first.isBroadcast) { controller ..onPause = () { if (!firstDone || !next.isBroadcast) return subscription.pause(); subscription.cancel(); subscription = null; } ..onResume = () { if (!firstDone || !next.isBroadcast) return subscription.resume(); listen(); }; } controller.onCancel = () { if (secondDone) return null; var toCancel = subscription; subscription = null; return toCancel.cancel(); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/async_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:async'; import 'aggregate_sample.dart'; import 'from_handlers.dart'; import 'rate_limit.dart'; /// Alternatives to [asyncMap]. /// /// The built in [asyncMap] will not overlap execution of the passed callback, /// and every event will be sent to the callback individually. /// /// - [asyncMapBuffer] prevents the callback from overlapping execution and /// collects events while it is executing to process in batches. /// - [asyncMapSample] prevents overlapping execution and discards events while /// it is executing. /// - [concurrentAsyncMap] allows overlap and removes ordering guarantees. extension AsyncMap<T> on Stream<T> { /// Like [asyncMap] but events are buffered until previous events have been /// processed by [convert]. /// /// If the source stream is a broadcast stream the result will be as well. When /// used with a broadcast stream behavior also differs from [Stream.asyncMap] in /// that the [convert] function is only called once per event, rather than once /// per listener per event. /// /// The first event from the source stream is always passed to [convert] as a /// List with a single element. After that events are buffered until the /// previous Future returned from [convert] has fired. /// /// Errors from the source stream are forwarded directly to the result stream. /// Errors during the conversion are also forwarded to the result stream and /// are considered completing work so the next values are let through. /// /// The result stream will not close until the source stream closes and all /// pending conversions have finished. Stream<S> asyncMapBuffer<S>(Future<S> Function(List<T>) convert) { var workFinished = StreamController<void>() // Let the first event through. ..add(null); return buffer(workFinished.stream) .transform(_asyncMapThen(convert, workFinished.add)); } /// Like [asyncMap] but events are discarded while work is happening in /// [convert]. /// /// If the source stream is a broadcast stream the result will be as well. When /// used with a broadcast stream behavior also differs from [Stream.asyncMap] in /// that the [convert] function is only called once per event, rather than once /// per listener per event. /// /// If no work is happening when an event is emitted it will be immediately /// passed to [convert]. If there is ongoing work when an event is emitted it /// will be held until the work is finished. New events emitted will replace a /// pending event. /// /// Errors from the source stream are forwarded directly to the result stream. /// Errors during the conversion are also forwarded to the result stream and are /// considered completing work so the next values are let through. /// /// The result stream will not close until the source stream closes and all /// pending conversions have finished. Stream<S> asyncMapSample<S>(Future<S> Function(T) convert) { var workFinished = StreamController<void>() // Let the first event through. ..add(null); return transform(AggregateSample(workFinished.stream, _dropPrevious)) .transform(_asyncMapThen(convert, workFinished.add)); } /// Like [asyncMap] but the [convert] callback may be called for an element /// before processing for the previous element is finished. /// /// Events on the result stream will be emitted in the order that [convert] /// completed which may not match the order of the original stream. /// /// If the source stream is a broadcast stream the result will be as well. /// When used with a broadcast stream behavior also differs from [asyncMap] in /// that the [convert] function is only called once per event, rather than /// once per listener per event. The [convert] callback won't be called for /// events while a broadcast stream has no listener. /// /// Errors from [convert] or the source stream are forwarded directly to the /// result stream. /// /// The result stream will not close until the source stream closes and all /// pending conversions have finished. Stream<S> concurrentAsyncMap<S>(FutureOr<S> Function(T) convert) { var valuesWaiting = 0; var sourceDone = false; return transform(fromHandlers(handleData: (element, sink) { valuesWaiting++; () async { try { sink.add(await convert(element)); } catch (e, st) { sink.addError(e, st); } valuesWaiting--; if (valuesWaiting <= 0 && sourceDone) sink.close(); }(); }, handleDone: (sink) { sourceDone = true; if (valuesWaiting <= 0) sink.close(); })); } } T _dropPrevious<T>(T event, _) => event; /// Like [Stream.asyncMap] but the [convert] is only called once per event, /// rather than once per listener, and [then] is called after completing the /// work. StreamTransformer<S, T> _asyncMapThen<S, T>( Future<T> Function(S) convert, void Function(void) then) { Future<void> pendingEvent; return fromHandlers(handleData: (event, sink) { pendingEvent = convert(event).then(sink.add).catchError(sink.addError).then(then); }, handleDone: (sink) { if (pendingEvent != null) { pendingEvent.then((_) => sink.close()); } else { sink.close(); } }); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/from_handlers.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'; /// Like [new StreamTransformer.fromHandlers] but the handlers are called once /// per event rather than once per listener for broadcast streams. StreamTransformer<S, T> fromHandlers<S, T>( {void Function(S, EventSink<T>) handleData, void Function(Object, StackTrace, EventSink<T>) handleError, void Function(EventSink<T>) handleDone}) => _StreamTransformer( handleData: handleData, handleError: handleError, handleDone: handleDone); class _StreamTransformer<S, T> extends StreamTransformerBase<S, T> { final void Function(S, EventSink<T>) _handleData; final void Function(EventSink<T>) _handleDone; final void Function(Object, StackTrace, EventSink<T>) _handleError; _StreamTransformer( {void Function(S, EventSink<T>) handleData, void Function(Object, StackTrace, EventSink<T>) handleError, void Function(EventSink<T>) handleDone}) : _handleData = handleData ?? _defaultHandleData, _handleError = handleError ?? _defaultHandleError, _handleDone = handleDone ?? _defaultHandleDone; static void _defaultHandleData<S, T>(S value, EventSink<T> sink) { sink.add(value as T); } static void _defaultHandleError<T>( Object error, StackTrace stackTrace, EventSink<T> sink) { sink.addError(error, stackTrace); } static void _defaultHandleDone<T>(EventSink<T> sink) { sink.close(); } @override Stream<T> bind(Stream<S> values) { var controller = values.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); StreamSubscription<S> subscription; controller.onListen = () { assert(subscription == null); var valuesDone = false; subscription = values.listen((value) => _handleData(value, controller), onError: (error, StackTrace stackTrace) { _handleError(error, stackTrace, controller); }, onDone: () { valuesDone = true; _handleDone(controller); }); if (!values.isBroadcast) { controller ..onPause = subscription.pause ..onResume = subscription.resume; } controller.onCancel = () { var toCancel = subscription; subscription = null; if (!valuesDone) return toCancel.cancel(); return null; }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/take_until.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 utility to end a stream based on an external trigger. extension TakeUntil<T> on Stream<T> { /// Returns a stream which emits values from the source stream until [trigger] /// fires. /// /// Completing [trigger] differs from canceling a subscription in that values /// which are emitted before the trigger, but have further asynchronous delays /// in transformations following the takeUtil, will still go through. /// Cancelling a subscription immediately stops values. Stream<T> takeUntil(Future<void> trigger) => transform(_TakeUntil(trigger)); } class _TakeUntil<T> extends StreamTransformerBase<T, T> { final Future<void> _trigger; _TakeUntil(this._trigger); @override Stream<T> bind(Stream<T> values) { var controller = values.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); StreamSubscription<T> subscription; var isDone = false; _trigger.then((_) { if (isDone) return; isDone = true; subscription?.cancel(); controller.close(); }); controller.onListen = () { if (isDone) return; subscription = values.listen(controller.add, onError: controller.addError, onDone: () { if (isDone) return; isDone = true; controller.close(); }); if (!values.isBroadcast) { controller ..onPause = subscription.pause ..onResume = subscription.resume; } controller.onCancel = () { if (isDone) return null; var toCancel = subscription; subscription = null; return toCancel.cancel(); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/scan.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 utility similar to [fold] which emits intermediate accumulations. extension Scan<T> on Stream<T> { /// Like [fold], but instead of producing a single value it yields each /// intermediate accumulation. /// /// If [combine] returns a Future it will not be called again for subsequent /// events from the source until it completes, therefore [combine] is always /// called for elements in order, and the result stream always maintains the /// same order as the original. Stream<S> scan<S>( S initialValue, FutureOr<S> Function(S soFar, T element) combine) { var accumulated = initialValue; return asyncMap((value) { var result = combine(accumulated, value); if (result is Future<S>) { return result.then((r) => accumulated = r); } else { return accumulated = result as S; } }); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/combine_latest.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'; /// Utilities to combine events from multiple streams through a callback or into /// a list. extension CombineLatest<T> on Stream<T> { /// Returns a stream which combines the latest value from the source stream /// with the latest value from [other] using [combine]. /// /// No event will be emitted until both the source stream and [other] have /// each emitted at least one event. If either the source stream or [other] /// emit multiple events before the other emits the first event, all but the /// last value will be discarded. Once both streams have emitted at least /// once, the result stream will emit any time either input stream emits. /// /// The result stream will not close until both the source stream and [other] /// have closed. /// /// For example: /// /// source.combineLatest(other, (a, b) => a + b); /// /// source: --1--2--------4--| /// other: -------3--| /// result: -------5------7--| /// /// Errors thrown by [combine], along with any errors on the source stream or /// [other], are forwarded to the result stream. /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless of [other]'s type. If a single subscription stream is /// combined with a broadcast stream it may never be canceled. Stream<S> combineLatest<T2, S>( Stream<T2> other, FutureOr<S> Function(T, T2) combine) => transform(_CombineLatest(other, combine)); /// Combine the latest value emitted from the source stream with the latest /// values emitted from [others]. /// /// [combineLatestAll] subscribes to the source stream and [others] and when /// any one of the streams emits, the result stream will emit a [List<T>] of /// the latest values emitted from all streams. /// /// No event will be emitted until all source streams emit at least once. If a /// source stream emits multiple values before another starts emitting, all /// but the last value will be discarded. Once all source streams have emitted /// at least once, the result stream will emit any time any source stream /// emits. /// /// The result stream will not close until all source streams have closed. When /// a source stream closes, the result stream will continue to emit the last /// value from the closed stream when the other source streams emit until the /// result stream has closed. If a source stream closes without emitting any /// value, the result stream will close as well. /// /// For example: /// /// final combined = first /// .combineLatestAll([second, third]) /// .map((data) => data.join()); /// /// first: a----b------------------c--------d---| /// second: --1---------2-----------------| /// third: -------&----------%---| /// combined: -------b1&--b2&---b2%---c2%------d2%-| /// /// Errors thrown by any source stream will be forwarded to the result stream. /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless of the types of [others]. If a single subscription stream /// is combined with a broadcast source stream, it may never be canceled. Stream<List<T>> combineLatestAll(Iterable<Stream<T>> others) => transform(_CombineLatestAll<T>(others)); } class _CombineLatest<S, T, R> extends StreamTransformerBase<S, R> { final Stream<T> _other; final FutureOr<R> Function(S, T) _combine; _CombineLatest(this._other, this._combine); @override Stream<R> bind(Stream<S> source) { final controller = source.isBroadcast ? StreamController<R>.broadcast(sync: true) : StreamController<R>(sync: true); final other = (source.isBroadcast && !_other.isBroadcast) ? _other.asBroadcastStream() : _other; StreamSubscription<S> sourceSubscription; StreamSubscription<T> otherSubscription; var sourceDone = false; var otherDone = false; S latestSource; T latestOther; var sourceStarted = false; var otherStarted = false; void emitCombined() { if (!sourceStarted || !otherStarted) return; FutureOr<R> result; try { result = _combine(latestSource, latestOther); } catch (e, s) { controller.addError(e, s); return; } if (result is Future<R>) { sourceSubscription.pause(); otherSubscription.pause(); result .then(controller.add, onError: controller.addError) .whenComplete(() { sourceSubscription.resume(); otherSubscription.resume(); }); } else { controller.add(result as R); } } controller.onListen = () { assert(sourceSubscription == null); sourceSubscription = source.listen( (s) { sourceStarted = true; latestSource = s; emitCombined(); }, onError: controller.addError, onDone: () { sourceDone = true; if (otherDone) { controller.close(); } else if (!sourceStarted) { // Nothing can ever be emitted otherSubscription.cancel(); controller.close(); } }); otherSubscription = other.listen( (o) { otherStarted = true; latestOther = o; emitCombined(); }, onError: controller.addError, onDone: () { otherDone = true; if (sourceDone) { controller.close(); } else if (!otherStarted) { // Nothing can ever be emitted sourceSubscription.cancel(); controller.close(); } }); if (!source.isBroadcast) { controller ..onPause = () { sourceSubscription.pause(); otherSubscription.pause(); } ..onResume = () { sourceSubscription.resume(); otherSubscription.resume(); }; } controller.onCancel = () { var cancels = [sourceSubscription.cancel(), otherSubscription.cancel()] .where((f) => f != null); sourceSubscription = null; otherSubscription = null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } } class _CombineLatestAll<T> extends StreamTransformerBase<T, List<T>> { final Iterable<Stream<T>> _others; _CombineLatestAll(this._others); @override Stream<List<T>> bind(Stream<T> first) { final controller = first.isBroadcast ? StreamController<List<T>>.broadcast(sync: true) : StreamController<List<T>>(sync: true); final allStreams = [ first, for (final other in _others) !first.isBroadcast || other.isBroadcast ? other : other.asBroadcastStream(), ]; controller.onListen = () { final subscriptions = <StreamSubscription<T>>[]; final latestData = List<T>(allStreams.length); final hasEmitted = <int>{}; void handleData(int index, T data) { latestData[index] = data; hasEmitted.add(index); if (hasEmitted.length == allStreams.length) { controller.add(List.from(latestData)); } } var streamId = 0; for (final stream in allStreams) { final index = streamId; final subscription = stream.listen((data) => handleData(index, data), onError: controller.addError); subscription.onDone(() { assert(subscriptions.contains(subscription)); subscriptions.remove(subscription); if (subscriptions.isEmpty || !hasEmitted.contains(index)) { controller.close(); } }); subscriptions.add(subscription); streamId++; } if (!first.isBroadcast) { controller ..onPause = () { for (final subscription in subscriptions) { subscription.pause(); } } ..onResume = () { for (final subscription in subscriptions) { subscription.resume(); } }; } controller.onCancel = () { var cancels = subscriptions .map((s) => s.cancel()) .where((f) => f != null) .toList(); if (cancels.isEmpty) return null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/where.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 'from_handlers.dart'; /// Utilities to filter events. extension Where<T> on Stream<T> { /// Returns a stream which emits only the events which have type [S]. /// /// If the source stream is a broadcast stream the result will be as well. /// /// Errors from the source stream are forwarded directly to the result stream. /// /// [S] should be a subtype of the stream's generic type, otherwise nothing of /// type [S] could possibly be emitted, however there is no static or runtime /// checking that this is the case. Stream<S> whereType<S>() => where((e) => e is S).cast<S>(); /// Like [where] but allows the [test] to return a [Future]. /// /// Events on the result stream will be emitted in the order that [test] /// completes which may not match the order of the original stream. /// /// If the source stream is a broadcast stream the result will be as well. When /// used with a broadcast stream behavior also differs from [Stream.where] in /// that the [test] function is only called once per event, rather than once /// per listener per event. /// /// Errors from the source stream are forwarded directly to the result stream. /// Errors from [test] are also forwarded to the result stream. /// /// The result stream will not close until the source stream closes and all /// pending [test] calls have finished. Stream<T> asyncWhere(FutureOr<bool> Function(T) test) { var valuesWaiting = 0; var sourceDone = false; return transform(fromHandlers(handleData: (element, sink) { valuesWaiting++; () async { try { if (await test(element)) sink.add(element); } catch (e, st) { sink.addError(e, st); } valuesWaiting--; if (valuesWaiting <= 0 && sourceDone) sink.close(); }(); }, handleDone: (sink) { sourceDone = true; if (valuesWaiting <= 0) sink.close(); })); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/aggregate_sample.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'; /// A StreamTransformer which aggregates values and emits when it sees a value /// on [_trigger]. /// /// If there are no pending values when [_trigger] emits the first value on the /// source Stream will immediately flow through. Otherwise, the pending values /// and released when [_trigger] emits. /// /// Errors from the source stream or the trigger are immediately forwarded to /// the output. class AggregateSample<S, T> extends StreamTransformerBase<S, T> { final Stream<void> _trigger; final T Function(S, T) _aggregate; AggregateSample(this._trigger, this._aggregate); @override Stream<T> bind(Stream<S> values) { var controller = values.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); T currentResults; var waitingForTrigger = true; var isTriggerDone = false; var isValueDone = false; StreamSubscription<S> valueSub; StreamSubscription<void> triggerSub; void emit() { controller.add(currentResults); currentResults = null; waitingForTrigger = true; } void onValue(S value) { currentResults = _aggregate(value, currentResults); if (!waitingForTrigger) emit(); if (isTriggerDone) { valueSub.cancel(); controller.close(); } } void onValuesDone() { isValueDone = true; if (currentResults == null) { triggerSub?.cancel(); controller.close(); } } void onTrigger(_) { waitingForTrigger = false; if (currentResults != null) emit(); if (isValueDone) { triggerSub.cancel(); controller.close(); } } void onTriggerDone() { isTriggerDone = true; if (waitingForTrigger) { valueSub?.cancel(); controller.close(); } } controller.onListen = () { assert(valueSub == null); valueSub = values.listen(onValue, onError: controller.addError, onDone: onValuesDone); if (triggerSub != null) { if (triggerSub.isPaused) triggerSub.resume(); } else { triggerSub = _trigger.listen(onTrigger, onError: controller.addError, onDone: onTriggerDone); } if (!values.isBroadcast) { controller ..onPause = () { valueSub?.pause(); triggerSub?.pause(); } ..onResume = () { valueSub?.resume(); triggerSub?.resume(); }; } controller.onCancel = () { var toCancel = <StreamSubscription<void>>[]; if (!isValueDone) toCancel.add(valueSub); valueSub = null; if (_trigger.isBroadcast || !values.isBroadcast) { if (!isTriggerDone) toCancel.add(triggerSub); triggerSub = null; } else { triggerSub.pause(); } var cancels = toCancel.map((s) => s.cancel()).where((f) => f != null).toList(); if (cancels.isEmpty) return null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/tap.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 'from_handlers.dart'; /// A utility to chain extra behavior on a stream. extension Tap<T> on Stream<T> { /// Taps into this stream to allow additional handling on a single-subscriber /// stream without first wrapping as a broadcast stream. /// /// The [onValue] callback will be called with every value from the source /// stream before it is forwarded to listeners on the resulting stream. May be /// null if only [onError] or [onDone] callbacks are needed. /// /// The [onError] callback will be called with every error from the source /// stream before it is forwarded to listeners on the resulting stream. /// /// The [onDone] callback will be called after the source stream closes and /// before the resulting stream is closed. /// /// Errors from any of the callbacks are caught and ignored. /// /// The callbacks may not be called until the tapped stream has a listener, /// and may not be called after the listener has canceled the subscription. Stream<T> tap(void Function(T) onValue, {void Function(Object, StackTrace) onError, void Function() onDone}) => transform(fromHandlers(handleData: (value, sink) { try { onValue?.call(value); } catch (_) {/*Ignore*/} sink.add(value); }, handleError: (error, stackTrace, sink) { try { onError?.call(error, stackTrace); } catch (_) {/*Ignore*/} sink.addError(error, stackTrace); }, handleDone: (sink) { try { onDone?.call(); } catch (_) {/*Ignore*/} sink.close(); })); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/switch.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 utility to take events from the most recent sub stream returned by a /// callback. extension Switch<T> on Stream<T> { /// Maps events to a Stream and emits values from the most recently created /// Stream. /// /// When the source emits a value it will be converted to a [Stream] using /// [convert] and the output will switch to emitting events from that result. /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless of the types of the streams produced by [convert]. Stream<S> switchMap<S>(Stream<S> Function(T) convert) { return map(convert).switchLatest(); } } /// A utility to take events from the most recent sub stream. extension SwitchLatest<T> on Stream<Stream<T>> { /// Emits values from the most recently emitted Stream. /// /// When the source emits a stream the output will switch to emitting events /// from that stream. /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless of the types of streams emitted. Stream<T> switchLatest() => transform(_SwitchTransformer<T>()); } class _SwitchTransformer<T> extends StreamTransformerBase<Stream<T>, T> { const _SwitchTransformer(); @override Stream<T> bind(Stream<Stream<T>> outer) { var controller = outer.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); controller.onListen = () { StreamSubscription<T> innerSubscription; var outerStreamDone = false; final outerSubscription = outer.listen( (innerStream) { innerSubscription?.cancel(); innerSubscription = innerStream.listen(controller.add, onError: controller.addError, onDone: () { innerSubscription = null; if (outerStreamDone) controller.close(); }); }, onError: controller.addError, onDone: () { outerStreamDone = true; if (innerSubscription == null) controller.close(); }); if (!outer.isBroadcast) { controller ..onPause = () { innerSubscription?.pause(); outerSubscription.pause(); } ..onResume = () { innerSubscription?.resume(); outerSubscription.resume(); }; } controller.onCancel = () { var cancels = [ if (!outerStreamDone) outerSubscription.cancel(), if (innerSubscription != null) innerSubscription.cancel(), ].where((f) => f != null); if (cancels.isEmpty) return null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stream_transform/src/merge.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'; /// Utilities to interleave events from multiple streams. extension Merge<T> on Stream<T> { /// Returns a stream which emits values and errors from the source stream and /// [other] in any order as they arrive. /// /// The result stream will not close until both the source stream and [other] /// have closed. /// /// For example: /// /// final result = source.merge(other); /// /// source: 1--2-----3--| /// other: ------4-------5--| /// result: 1--2--4--3----5--| /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless of [other]'s type. If a single subscription stream is /// merged into a broadcast stream it may never be canceled since there may be /// broadcast listeners added later. /// /// If a broadcast stream is merged into a single-subscription stream any /// events emitted by [other] before the result stream has a subscriber will /// be discarded. Stream<T> merge(Stream<T> other) => transform(_Merge([other])); /// Returns a stream which emits values and errors from the source stream and /// any stream in [others] in any order as they arrive. /// /// The result stream will not close until the source stream and all streams /// in [others] have closed. /// /// For example: /// /// final result = first.mergeAll([second, third]); /// /// first: 1--2--------3--| /// second: ---------4-------5--| /// third: ------6---------------7--| /// result: 1--2--6--4--3----5----7--| /// /// If the source stream is a broadcast stream, the result stream will be as /// well, regardless the types of streams in [others]. If a single /// subscription stream is merged into a broadcast stream it may never be /// canceled since there may be broadcast listeners added later. /// /// If a broadcast stream is merged into a single-subscription stream any /// events emitted by that stream before the result stream has a subscriber /// will be discarded. Stream<T> mergeAll(Iterable<Stream<T>> others) => transform(_Merge(others)); /// Like [asyncExpand] but the [convert] callback may be called for an element /// before the Stream emitted by the previous element has closed. /// /// Events on the result stream will be emitted in the order they are emitted /// by the sub streams, which may not match the order of the original stream. /// /// Errors from [convert], the source stream, or any of the sub streams are /// forwarded to the result stream. /// /// The result stream will not close until the source stream closes and all /// sub streams have closed. /// /// If the source stream is a broadcast stream the result will be as well, /// regardless of the types of streams created by [convert]. In this case, /// some care should be taken: /// - If [convert] returns a single subscription stream it may be listened to /// and never canceled. /// - For any period of time where there are no listeners on the result /// stream, any sub streams from previously emitted events will be ignored, /// regardless of whether they emit further events after a listener is added /// back. Stream<S> concurrentAsyncExpand<S>(Stream<S> Function(T) convert) => map(convert).transform(_MergeExpanded()); } class _Merge<T> extends StreamTransformerBase<T, T> { final Iterable<Stream<T>> _others; _Merge(this._others); @override Stream<T> bind(Stream<T> first) { final controller = first.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); final allStreams = [ first, for (final other in _others) !first.isBroadcast || other.isBroadcast ? other : other.asBroadcastStream(), ]; controller.onListen = () { final subscriptions = <StreamSubscription<T>>[]; for (final stream in allStreams) { final subscription = stream.listen(controller.add, onError: controller.addError); subscription.onDone(() { subscriptions.remove(subscription); if (subscriptions.isEmpty) controller.close(); }); subscriptions.add(subscription); } if (!first.isBroadcast) { controller ..onPause = () { for (final subscription in subscriptions) { subscription.pause(); } } ..onResume = () { for (final subscription in subscriptions) { subscription.resume(); } }; } controller.onCancel = () { var cancels = subscriptions .map((s) => s.cancel()) .where((f) => f != null) .toList(); if (cancels.isEmpty) return null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } } class _MergeExpanded<T> extends StreamTransformerBase<Stream<T>, T> { @override Stream<T> bind(Stream<Stream<T>> streams) { final controller = streams.isBroadcast ? StreamController<T>.broadcast(sync: true) : StreamController<T>(sync: true); controller.onListen = () { final subscriptions = <StreamSubscription<dynamic>>[]; final outerSubscription = streams.listen((inner) { if (streams.isBroadcast && !inner.isBroadcast) { inner = inner.asBroadcastStream(); } final subscription = inner.listen(controller.add, onError: controller.addError); subscription.onDone(() { subscriptions.remove(subscription); if (subscriptions.isEmpty) controller.close(); }); subscriptions.add(subscription); }, onError: controller.addError); outerSubscription.onDone(() { subscriptions.remove(outerSubscription); if (subscriptions.isEmpty) controller.close(); }); subscriptions.add(outerSubscription); if (!streams.isBroadcast) { controller ..onPause = () { for (final subscription in subscriptions) { subscription.pause(); } } ..onResume = () { for (final subscription in subscriptions) { subscription.resume(); } }; } controller.onCancel = () { var cancels = subscriptions .map((s) => s.cancel()) .where((f) => f != null) .toList(); if (cancels.isEmpty) return null; return Future.wait(cancels).then((_) => null); }; }; return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/term_glyph.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. export 'src/generated/glyph_set.dart'; export 'src/generated/top_level.dart'; import 'src/generated/ascii_glyph_set.dart'; import 'src/generated/glyph_set.dart'; import 'src/generated/unicode_glyph_set.dart'; /// A [GlyphSet] that always returns ASCII glyphs. const GlyphSet asciiGlyphs = const AsciiGlyphSet(); /// A [GlyphSet] that always returns Unicode glyphs. const GlyphSet unicodeGlyphs = const UnicodeGlyphSet(); /// Returns [asciiGlyphs] if [ascii] is `true` or [unicodeGlyphs] otherwise. /// /// Returns [unicodeGlyphs] by default. GlyphSet get glyphs => _glyphs; GlyphSet _glyphs = unicodeGlyphs; /// Whether the glyph getters return plain ASCII, as opposed to Unicode /// characters or sequences. /// /// Defaults to `false`. bool get ascii => glyphs == asciiGlyphs; set ascii(bool value) { _glyphs = value ? asciiGlyphs : unicodeGlyphs; } /// Returns [glyph] if Unicode glyph are allowed, and [alternative] if they /// aren't. String glyphOrAscii(String glyph, String alternative) => glyphs.glyphOrAscii(glyph, alternative);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src/generated/glyph_set.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. // Don't modify this file by hand! It's generated by tool/generate.dart. /// A class that provides access to every configurable glyph. /// /// This is provided as a class so that individual chunks of code can choose /// between [ascii] and [unicode] glyphs. For example: /// /// ```dart /// import 'package:term_glyph/term_glyph.dart' as glyph; /// /// /// Adds a vertical line to the left of [text]. /// /// /// /// If [ascii] is `true`, this uses plain ASCII for the line. If it's /// /// `false`, this uses Unicode characters. If it's `null`, it defaults /// /// to [glyph.ascii]. /// void addVerticalLine(String text, {bool ascii}) { /// var glyphs = /// (ascii ?? glyph.ascii) ? glyph.asciiGlyphs : glyph.unicodeGlyphs; /// /// return text /// .split("\n") /// .map((line) => "${glyphs.verticalLine} $line") /// .join("\n"); /// } /// ``` abstract class GlyphSet { /// Returns [glyph] if [this] supports Unicode glyphs and [alternative] /// otherwise. String glyphOrAscii(String glyph, String alternative); /// A bullet point. String get bullet; /// A left-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. String get leftArrow; /// A right-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. String get rightArrow; /// An upwards-pointing arrow. String get upArrow; /// A downwards-pointing arrow. String get downArrow; /// A two-character left-pointing arrow. String get longLeftArrow; /// A two-character right-pointing arrow. String get longRightArrow; /// A horizontal line that can be used to draw a box. String get horizontalLine; /// A vertical line that can be used to draw a box. String get verticalLine; /// The upper left-hand corner of a box. String get topLeftCorner; /// The upper right-hand corner of a box. String get topRightCorner; /// The lower left-hand corner of a box. String get bottomLeftCorner; /// The lower right-hand corner of a box. String get bottomRightCorner; /// An intersection of vertical and horizontal box lines. String get cross; /// A horizontal box line with a vertical line going up from the middle. String get teeUp; /// A horizontal box line with a vertical line going down from the middle. String get teeDown; /// A vertical box line with a horizontal line going left from the middle. String get teeLeft; /// A vertical box line with a horizontal line going right from the middle. String get teeRight; /// The top half of a vertical box line. String get upEnd; /// The bottom half of a vertical box line. String get downEnd; /// The left half of a horizontal box line. String get leftEnd; /// The right half of a horizontal box line. String get rightEnd; /// A bold horizontal line that can be used to draw a box. String get horizontalLineBold; /// A bold vertical line that can be used to draw a box. String get verticalLineBold; /// The bold upper left-hand corner of a box. String get topLeftCornerBold; /// The bold upper right-hand corner of a box. String get topRightCornerBold; /// The bold lower left-hand corner of a box. String get bottomLeftCornerBold; /// The bold lower right-hand corner of a box. String get bottomRightCornerBold; /// An intersection of bold vertical and horizontal box lines. String get crossBold; /// A bold horizontal box line with a vertical line going up from the middle. String get teeUpBold; /// A bold horizontal box line with a vertical line going down from the middle. String get teeDownBold; /// A bold vertical box line with a horizontal line going left from the middle. String get teeLeftBold; /// A bold vertical box line with a horizontal line going right from the middle. String get teeRightBold; /// The top half of a bold vertical box line. String get upEndBold; /// The bottom half of a bold vertical box line. String get downEndBold; /// The left half of a bold horizontal box line. String get leftEndBold; /// The right half of a bold horizontal box line. String get rightEndBold; /// A double horizontal line that can be used to draw a box. String get horizontalLineDouble; /// A double vertical line that can be used to draw a box. String get verticalLineDouble; /// The double upper left-hand corner of a box. String get topLeftCornerDouble; /// The double upper right-hand corner of a box. String get topRightCornerDouble; /// The double lower left-hand corner of a box. String get bottomLeftCornerDouble; /// The double lower right-hand corner of a box. String get bottomRightCornerDouble; /// An intersection of double vertical and horizontal box lines. String get crossDouble; /// A double horizontal box line with a vertical line going up from the middle. String get teeUpDouble; /// A double horizontal box line with a vertical line going down from the middle. String get teeDownDouble; /// A double vertical box line with a horizontal line going left from the middle. String get teeLeftDouble; /// A double vertical box line with a horizontal line going right from the middle. String get teeRightDouble; /// A dashed horizontal line that can be used to draw a box. String get horizontalLineDoubleDash; /// A bold dashed horizontal line that can be used to draw a box. String get horizontalLineDoubleDashBold; /// A dashed vertical line that can be used to draw a box. String get verticalLineDoubleDash; /// A bold dashed vertical line that can be used to draw a box. String get verticalLineDoubleDashBold; /// A dashed horizontal line that can be used to draw a box. String get horizontalLineTripleDash; /// A bold dashed horizontal line that can be used to draw a box. String get horizontalLineTripleDashBold; /// A dashed vertical line that can be used to draw a box. String get verticalLineTripleDash; /// A bold dashed vertical line that can be used to draw a box. String get verticalLineTripleDashBold; /// A dashed horizontal line that can be used to draw a box. String get horizontalLineQuadrupleDash; /// A bold dashed horizontal line that can be used to draw a box. String get horizontalLineQuadrupleDashBold; /// A dashed vertical line that can be used to draw a box. String get verticalLineQuadrupleDash; /// A bold dashed vertical line that can be used to draw a box. String get verticalLineQuadrupleDashBold; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src/generated/top_level.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. // Don't modify this file by hand! It's generated by tool/generate.dart. import '../../term_glyph.dart' as glyph; /// A bullet point. /// /// If [ascii] is `false`, this is "•". If it's `true`, this is /// "*" instead. String get bullet => glyph.glyphs.bullet; /// A left-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// If [ascii] is `false`, this is "←". If it's `true`, this is /// "<" instead. String get leftArrow => glyph.glyphs.leftArrow; /// A right-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// If [ascii] is `false`, this is "→". If it's `true`, this is /// ">" instead. String get rightArrow => glyph.glyphs.rightArrow; /// An upwards-pointing arrow. /// /// If [ascii] is `false`, this is "↑". If it's `true`, this is /// "^" instead. String get upArrow => glyph.glyphs.upArrow; /// A downwards-pointing arrow. /// /// If [ascii] is `false`, this is "↓". If it's `true`, this is /// "v" instead. String get downArrow => glyph.glyphs.downArrow; /// A two-character left-pointing arrow. /// /// If [ascii] is `false`, this is "◀━". If it's `true`, this is /// "<=" instead. String get longLeftArrow => glyph.glyphs.longLeftArrow; /// A two-character right-pointing arrow. /// /// If [ascii] is `false`, this is "━▶". If it's `true`, this is /// "=>" instead. String get longRightArrow => glyph.glyphs.longRightArrow; /// A horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "─". If it's `true`, this is /// "-" instead. String get horizontalLine => glyph.glyphs.horizontalLine; /// A vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "│". If it's `true`, this is /// "|" instead. String get verticalLine => glyph.glyphs.verticalLine; /// The upper left-hand corner of a box. /// /// If [ascii] is `false`, this is "┌". If it's `true`, this is /// "," instead. String get topLeftCorner => glyph.glyphs.topLeftCorner; /// The upper right-hand corner of a box. /// /// If [ascii] is `false`, this is "┐". If it's `true`, this is /// "," instead. String get topRightCorner => glyph.glyphs.topRightCorner; /// The lower left-hand corner of a box. /// /// If [ascii] is `false`, this is "└". If it's `true`, this is /// "'" instead. String get bottomLeftCorner => glyph.glyphs.bottomLeftCorner; /// The lower right-hand corner of a box. /// /// If [ascii] is `false`, this is "┘". If it's `true`, this is /// "'" instead. String get bottomRightCorner => glyph.glyphs.bottomRightCorner; /// An intersection of vertical and horizontal box lines. /// /// If [ascii] is `false`, this is "┼". If it's `true`, this is /// "+" instead. String get cross => glyph.glyphs.cross; /// A horizontal box line with a vertical line going up from the middle. /// /// If [ascii] is `false`, this is "┴". If it's `true`, this is /// "+" instead. String get teeUp => glyph.glyphs.teeUp; /// A horizontal box line with a vertical line going down from the middle. /// /// If [ascii] is `false`, this is "┬". If it's `true`, this is /// "+" instead. String get teeDown => glyph.glyphs.teeDown; /// A vertical box line with a horizontal line going left from the middle. /// /// If [ascii] is `false`, this is "┤". If it's `true`, this is /// "+" instead. String get teeLeft => glyph.glyphs.teeLeft; /// A vertical box line with a horizontal line going right from the middle. /// /// If [ascii] is `false`, this is "├". If it's `true`, this is /// "+" instead. String get teeRight => glyph.glyphs.teeRight; /// The top half of a vertical box line. /// /// If [ascii] is `false`, this is "╵". If it's `true`, this is /// "'" instead. String get upEnd => glyph.glyphs.upEnd; /// The bottom half of a vertical box line. /// /// If [ascii] is `false`, this is "╷". If it's `true`, this is /// "," instead. String get downEnd => glyph.glyphs.downEnd; /// The left half of a horizontal box line. /// /// If [ascii] is `false`, this is "╴". If it's `true`, this is /// "-" instead. String get leftEnd => glyph.glyphs.leftEnd; /// The right half of a horizontal box line. /// /// If [ascii] is `false`, this is "╶". If it's `true`, this is /// "-" instead. String get rightEnd => glyph.glyphs.rightEnd; /// A bold horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "━". If it's `true`, this is /// "=" instead. String get horizontalLineBold => glyph.glyphs.horizontalLineBold; /// A bold vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┃". If it's `true`, this is /// "|" instead. String get verticalLineBold => glyph.glyphs.verticalLineBold; /// The bold upper left-hand corner of a box. /// /// If [ascii] is `false`, this is "┏". If it's `true`, this is /// "," instead. String get topLeftCornerBold => glyph.glyphs.topLeftCornerBold; /// The bold upper right-hand corner of a box. /// /// If [ascii] is `false`, this is "┓". If it's `true`, this is /// "," instead. String get topRightCornerBold => glyph.glyphs.topRightCornerBold; /// The bold lower left-hand corner of a box. /// /// If [ascii] is `false`, this is "┗". If it's `true`, this is /// "'" instead. String get bottomLeftCornerBold => glyph.glyphs.bottomLeftCornerBold; /// The bold lower right-hand corner of a box. /// /// If [ascii] is `false`, this is "┛". If it's `true`, this is /// "'" instead. String get bottomRightCornerBold => glyph.glyphs.bottomRightCornerBold; /// An intersection of bold vertical and horizontal box lines. /// /// If [ascii] is `false`, this is "╋". If it's `true`, this is /// "+" instead. String get crossBold => glyph.glyphs.crossBold; /// A bold horizontal box line with a vertical line going up from the middle. /// /// If [ascii] is `false`, this is "┻". If it's `true`, this is /// "+" instead. String get teeUpBold => glyph.glyphs.teeUpBold; /// A bold horizontal box line with a vertical line going down from the middle. /// /// If [ascii] is `false`, this is "┳". If it's `true`, this is /// "+" instead. String get teeDownBold => glyph.glyphs.teeDownBold; /// A bold vertical box line with a horizontal line going left from the middle. /// /// If [ascii] is `false`, this is "┫". If it's `true`, this is /// "+" instead. String get teeLeftBold => glyph.glyphs.teeLeftBold; /// A bold vertical box line with a horizontal line going right from the middle. /// /// If [ascii] is `false`, this is "┣". If it's `true`, this is /// "+" instead. String get teeRightBold => glyph.glyphs.teeRightBold; /// The top half of a bold vertical box line. /// /// If [ascii] is `false`, this is "╹". If it's `true`, this is /// "'" instead. String get upEndBold => glyph.glyphs.upEndBold; /// The bottom half of a bold vertical box line. /// /// If [ascii] is `false`, this is "╻". If it's `true`, this is /// "," instead. String get downEndBold => glyph.glyphs.downEndBold; /// The left half of a bold horizontal box line. /// /// If [ascii] is `false`, this is "╸". If it's `true`, this is /// "-" instead. String get leftEndBold => glyph.glyphs.leftEndBold; /// The right half of a bold horizontal box line. /// /// If [ascii] is `false`, this is "╺". If it's `true`, this is /// "-" instead. String get rightEndBold => glyph.glyphs.rightEndBold; /// A double horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "═". If it's `true`, this is /// "=" instead. String get horizontalLineDouble => glyph.glyphs.horizontalLineDouble; /// A double vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "║". If it's `true`, this is /// "|" instead. String get verticalLineDouble => glyph.glyphs.verticalLineDouble; /// The double upper left-hand corner of a box. /// /// If [ascii] is `false`, this is "╔". If it's `true`, this is /// "," instead. String get topLeftCornerDouble => glyph.glyphs.topLeftCornerDouble; /// The double upper right-hand corner of a box. /// /// If [ascii] is `false`, this is "╗". If it's `true`, this is /// "," instead. String get topRightCornerDouble => glyph.glyphs.topRightCornerDouble; /// The double lower left-hand corner of a box. /// /// If [ascii] is `false`, this is "╚". If it's `true`, this is /// """ instead. String get bottomLeftCornerDouble => glyph.glyphs.bottomLeftCornerDouble; /// The double lower right-hand corner of a box. /// /// If [ascii] is `false`, this is "╝". If it's `true`, this is /// """ instead. String get bottomRightCornerDouble => glyph.glyphs.bottomRightCornerDouble; /// An intersection of double vertical and horizontal box lines. /// /// If [ascii] is `false`, this is "╬". If it's `true`, this is /// "+" instead. String get crossDouble => glyph.glyphs.crossDouble; /// A double horizontal box line with a vertical line going up from the middle. /// /// If [ascii] is `false`, this is "╩". If it's `true`, this is /// "+" instead. String get teeUpDouble => glyph.glyphs.teeUpDouble; /// A double horizontal box line with a vertical line going down from the middle. /// /// If [ascii] is `false`, this is "╦". If it's `true`, this is /// "+" instead. String get teeDownDouble => glyph.glyphs.teeDownDouble; /// A double vertical box line with a horizontal line going left from the middle. /// /// If [ascii] is `false`, this is "╣". If it's `true`, this is /// "+" instead. String get teeLeftDouble => glyph.glyphs.teeLeftDouble; /// A double vertical box line with a horizontal line going right from the middle. /// /// If [ascii] is `false`, this is "╠". If it's `true`, this is /// "+" instead. String get teeRightDouble => glyph.glyphs.teeRightDouble; /// A dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "╌". If it's `true`, this is /// "-" instead. String get horizontalLineDoubleDash => glyph.glyphs.horizontalLineDoubleDash; /// A bold dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "╍". If it's `true`, this is /// "-" instead. String get horizontalLineDoubleDashBold => glyph.glyphs.horizontalLineDoubleDashBold; /// A dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "╎". If it's `true`, this is /// "|" instead. String get verticalLineDoubleDash => glyph.glyphs.verticalLineDoubleDash; /// A bold dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "╏". If it's `true`, this is /// "|" instead. String get verticalLineDoubleDashBold => glyph.glyphs.verticalLineDoubleDashBold; /// A dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┄". If it's `true`, this is /// "-" instead. String get horizontalLineTripleDash => glyph.glyphs.horizontalLineTripleDash; /// A bold dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┅". If it's `true`, this is /// "-" instead. String get horizontalLineTripleDashBold => glyph.glyphs.horizontalLineTripleDashBold; /// A dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┆". If it's `true`, this is /// "|" instead. String get verticalLineTripleDash => glyph.glyphs.verticalLineTripleDash; /// A bold dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┇". If it's `true`, this is /// "|" instead. String get verticalLineTripleDashBold => glyph.glyphs.verticalLineTripleDashBold; /// A dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┈". If it's `true`, this is /// "-" instead. String get horizontalLineQuadrupleDash => glyph.glyphs.horizontalLineQuadrupleDash; /// A bold dashed horizontal line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┉". If it's `true`, this is /// "-" instead. String get horizontalLineQuadrupleDashBold => glyph.glyphs.horizontalLineQuadrupleDashBold; /// A dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┊". If it's `true`, this is /// "|" instead. String get verticalLineQuadrupleDash => glyph.glyphs.verticalLineQuadrupleDash; /// A bold dashed vertical line that can be used to draw a box. /// /// If [ascii] is `false`, this is "┋". If it's `true`, this is /// "|" instead. String get verticalLineQuadrupleDashBold => glyph.glyphs.verticalLineQuadrupleDashBold;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src/generated/ascii_glyph_set.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. // Don't modify this file by hand! It's generated by tool/generate.dart. import 'glyph_set.dart'; /// A [GlyphSet] that includes only ASCII glyphs. class AsciiGlyphSet implements GlyphSet { const AsciiGlyphSet(); /// Returns [glyph] if [this] supports Unicode glyphs and [alternative] /// otherwise. String glyphOrAscii(String glyph, String alternative) => alternative; /// A bullet point. /// /// Always "*" for [this]. String get bullet => "*"; /// A left-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// Always "<" for [this]. String get leftArrow => "<"; /// A right-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// Always ">" for [this]. String get rightArrow => ">"; /// An upwards-pointing arrow. /// /// Always "^" for [this]. String get upArrow => "^"; /// A downwards-pointing arrow. /// /// Always "v" for [this]. String get downArrow => "v"; /// A two-character left-pointing arrow. /// /// Always "<=" for [this]. String get longLeftArrow => "<="; /// A two-character right-pointing arrow. /// /// Always "=>" for [this]. String get longRightArrow => "=>"; /// A horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLine => "-"; /// A vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLine => "|"; /// The upper left-hand corner of a box. /// /// Always "," for [this]. String get topLeftCorner => ","; /// The upper right-hand corner of a box. /// /// Always "," for [this]. String get topRightCorner => ","; /// The lower left-hand corner of a box. /// /// Always "'" for [this]. String get bottomLeftCorner => "'"; /// The lower right-hand corner of a box. /// /// Always "'" for [this]. String get bottomRightCorner => "'"; /// An intersection of vertical and horizontal box lines. /// /// Always "+" for [this]. String get cross => "+"; /// A horizontal box line with a vertical line going up from the middle. /// /// Always "+" for [this]. String get teeUp => "+"; /// A horizontal box line with a vertical line going down from the middle. /// /// Always "+" for [this]. String get teeDown => "+"; /// A vertical box line with a horizontal line going left from the middle. /// /// Always "+" for [this]. String get teeLeft => "+"; /// A vertical box line with a horizontal line going right from the middle. /// /// Always "+" for [this]. String get teeRight => "+"; /// The top half of a vertical box line. /// /// Always "'" for [this]. String get upEnd => "'"; /// The bottom half of a vertical box line. /// /// Always "," for [this]. String get downEnd => ","; /// The left half of a horizontal box line. /// /// Always "-" for [this]. String get leftEnd => "-"; /// The right half of a horizontal box line. /// /// Always "-" for [this]. String get rightEnd => "-"; /// A bold horizontal line that can be used to draw a box. /// /// Always "=" for [this]. String get horizontalLineBold => "="; /// A bold vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineBold => "|"; /// The bold upper left-hand corner of a box. /// /// Always "," for [this]. String get topLeftCornerBold => ","; /// The bold upper right-hand corner of a box. /// /// Always "," for [this]. String get topRightCornerBold => ","; /// The bold lower left-hand corner of a box. /// /// Always "'" for [this]. String get bottomLeftCornerBold => "'"; /// The bold lower right-hand corner of a box. /// /// Always "'" for [this]. String get bottomRightCornerBold => "'"; /// An intersection of bold vertical and horizontal box lines. /// /// Always "+" for [this]. String get crossBold => "+"; /// A bold horizontal box line with a vertical line going up from the middle. /// /// Always "+" for [this]. String get teeUpBold => "+"; /// A bold horizontal box line with a vertical line going down from the middle. /// /// Always "+" for [this]. String get teeDownBold => "+"; /// A bold vertical box line with a horizontal line going left from the middle. /// /// Always "+" for [this]. String get teeLeftBold => "+"; /// A bold vertical box line with a horizontal line going right from the middle. /// /// Always "+" for [this]. String get teeRightBold => "+"; /// The top half of a bold vertical box line. /// /// Always "'" for [this]. String get upEndBold => "'"; /// The bottom half of a bold vertical box line. /// /// Always "," for [this]. String get downEndBold => ","; /// The left half of a bold horizontal box line. /// /// Always "-" for [this]. String get leftEndBold => "-"; /// The right half of a bold horizontal box line. /// /// Always "-" for [this]. String get rightEndBold => "-"; /// A double horizontal line that can be used to draw a box. /// /// Always "=" for [this]. String get horizontalLineDouble => "="; /// A double vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineDouble => "|"; /// The double upper left-hand corner of a box. /// /// Always "," for [this]. String get topLeftCornerDouble => ","; /// The double upper right-hand corner of a box. /// /// Always "," for [this]. String get topRightCornerDouble => ","; /// The double lower left-hand corner of a box. /// /// Always '"' for [this]. String get bottomLeftCornerDouble => '"'; /// The double lower right-hand corner of a box. /// /// Always '"' for [this]. String get bottomRightCornerDouble => '"'; /// An intersection of double vertical and horizontal box lines. /// /// Always "+" for [this]. String get crossDouble => "+"; /// A double horizontal box line with a vertical line going up from the middle. /// /// Always "+" for [this]. String get teeUpDouble => "+"; /// A double horizontal box line with a vertical line going down from the middle. /// /// Always "+" for [this]. String get teeDownDouble => "+"; /// A double vertical box line with a horizontal line going left from the middle. /// /// Always "+" for [this]. String get teeLeftDouble => "+"; /// A double vertical box line with a horizontal line going right from the middle. /// /// Always "+" for [this]. String get teeRightDouble => "+"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineDoubleDash => "-"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineDoubleDashBold => "-"; /// A dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineDoubleDash => "|"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineDoubleDashBold => "|"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineTripleDash => "-"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineTripleDashBold => "-"; /// A dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineTripleDash => "|"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineTripleDashBold => "|"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineQuadrupleDash => "-"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "-" for [this]. String get horizontalLineQuadrupleDashBold => "-"; /// A dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineQuadrupleDash => "|"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "|" for [this]. String get verticalLineQuadrupleDashBold => "|"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/term_glyph/src/generated/unicode_glyph_set.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. // Don't modify this file by hand! It's generated by tool/generate.dart. import 'glyph_set.dart'; /// A [GlyphSet] that includes only Unicode glyphs. class UnicodeGlyphSet implements GlyphSet { const UnicodeGlyphSet(); /// Returns [glyph] if [this] supports Unicode glyphs and [alternative] /// otherwise. String glyphOrAscii(String glyph, String alternative) => glyph; /// A bullet point. /// /// Always "•" for [this]. String get bullet => "•"; /// A left-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// Always "←" for [this]. String get leftArrow => "←"; /// A right-pointing arrow. /// /// Note that the Unicode arrow glyphs may overlap with adjacent characters in some /// terminal fonts, and should generally be surrounding by spaces. /// /// Always "→" for [this]. String get rightArrow => "→"; /// An upwards-pointing arrow. /// /// Always "↑" for [this]. String get upArrow => "↑"; /// A downwards-pointing arrow. /// /// Always "↓" for [this]. String get downArrow => "↓"; /// A two-character left-pointing arrow. /// /// Always "◀━" for [this]. String get longLeftArrow => "◀━"; /// A two-character right-pointing arrow. /// /// Always "━▶" for [this]. String get longRightArrow => "━▶"; /// A horizontal line that can be used to draw a box. /// /// Always "─" for [this]. String get horizontalLine => "─"; /// A vertical line that can be used to draw a box. /// /// Always "│" for [this]. String get verticalLine => "│"; /// The upper left-hand corner of a box. /// /// Always "┌" for [this]. String get topLeftCorner => "┌"; /// The upper right-hand corner of a box. /// /// Always "┐" for [this]. String get topRightCorner => "┐"; /// The lower left-hand corner of a box. /// /// Always "└" for [this]. String get bottomLeftCorner => "└"; /// The lower right-hand corner of a box. /// /// Always "┘" for [this]. String get bottomRightCorner => "┘"; /// An intersection of vertical and horizontal box lines. /// /// Always "┼" for [this]. String get cross => "┼"; /// A horizontal box line with a vertical line going up from the middle. /// /// Always "┴" for [this]. String get teeUp => "┴"; /// A horizontal box line with a vertical line going down from the middle. /// /// Always "┬" for [this]. String get teeDown => "┬"; /// A vertical box line with a horizontal line going left from the middle. /// /// Always "┤" for [this]. String get teeLeft => "┤"; /// A vertical box line with a horizontal line going right from the middle. /// /// Always "├" for [this]. String get teeRight => "├"; /// The top half of a vertical box line. /// /// Always "╵" for [this]. String get upEnd => "╵"; /// The bottom half of a vertical box line. /// /// Always "╷" for [this]. String get downEnd => "╷"; /// The left half of a horizontal box line. /// /// Always "╴" for [this]. String get leftEnd => "╴"; /// The right half of a horizontal box line. /// /// Always "╶" for [this]. String get rightEnd => "╶"; /// A bold horizontal line that can be used to draw a box. /// /// Always "━" for [this]. String get horizontalLineBold => "━"; /// A bold vertical line that can be used to draw a box. /// /// Always "┃" for [this]. String get verticalLineBold => "┃"; /// The bold upper left-hand corner of a box. /// /// Always "┏" for [this]. String get topLeftCornerBold => "┏"; /// The bold upper right-hand corner of a box. /// /// Always "┓" for [this]. String get topRightCornerBold => "┓"; /// The bold lower left-hand corner of a box. /// /// Always "┗" for [this]. String get bottomLeftCornerBold => "┗"; /// The bold lower right-hand corner of a box. /// /// Always "┛" for [this]. String get bottomRightCornerBold => "┛"; /// An intersection of bold vertical and horizontal box lines. /// /// Always "╋" for [this]. String get crossBold => "╋"; /// A bold horizontal box line with a vertical line going up from the middle. /// /// Always "┻" for [this]. String get teeUpBold => "┻"; /// A bold horizontal box line with a vertical line going down from the middle. /// /// Always "┳" for [this]. String get teeDownBold => "┳"; /// A bold vertical box line with a horizontal line going left from the middle. /// /// Always "┫" for [this]. String get teeLeftBold => "┫"; /// A bold vertical box line with a horizontal line going right from the middle. /// /// Always "┣" for [this]. String get teeRightBold => "┣"; /// The top half of a bold vertical box line. /// /// Always "╹" for [this]. String get upEndBold => "╹"; /// The bottom half of a bold vertical box line. /// /// Always "╻" for [this]. String get downEndBold => "╻"; /// The left half of a bold horizontal box line. /// /// Always "╸" for [this]. String get leftEndBold => "╸"; /// The right half of a bold horizontal box line. /// /// Always "╺" for [this]. String get rightEndBold => "╺"; /// A double horizontal line that can be used to draw a box. /// /// Always "═" for [this]. String get horizontalLineDouble => "═"; /// A double vertical line that can be used to draw a box. /// /// Always "║" for [this]. String get verticalLineDouble => "║"; /// The double upper left-hand corner of a box. /// /// Always "╔" for [this]. String get topLeftCornerDouble => "╔"; /// The double upper right-hand corner of a box. /// /// Always "╗" for [this]. String get topRightCornerDouble => "╗"; /// The double lower left-hand corner of a box. /// /// Always "╚" for [this]. String get bottomLeftCornerDouble => "╚"; /// The double lower right-hand corner of a box. /// /// Always "╝" for [this]. String get bottomRightCornerDouble => "╝"; /// An intersection of double vertical and horizontal box lines. /// /// Always "╬" for [this]. String get crossDouble => "╬"; /// A double horizontal box line with a vertical line going up from the middle. /// /// Always "╩" for [this]. String get teeUpDouble => "╩"; /// A double horizontal box line with a vertical line going down from the middle. /// /// Always "╦" for [this]. String get teeDownDouble => "╦"; /// A double vertical box line with a horizontal line going left from the middle. /// /// Always "╣" for [this]. String get teeLeftDouble => "╣"; /// A double vertical box line with a horizontal line going right from the middle. /// /// Always "╠" for [this]. String get teeRightDouble => "╠"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "╌" for [this]. String get horizontalLineDoubleDash => "╌"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "╍" for [this]. String get horizontalLineDoubleDashBold => "╍"; /// A dashed vertical line that can be used to draw a box. /// /// Always "╎" for [this]. String get verticalLineDoubleDash => "╎"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "╏" for [this]. String get verticalLineDoubleDashBold => "╏"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "┄" for [this]. String get horizontalLineTripleDash => "┄"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "┅" for [this]. String get horizontalLineTripleDashBold => "┅"; /// A dashed vertical line that can be used to draw a box. /// /// Always "┆" for [this]. String get verticalLineTripleDash => "┆"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "┇" for [this]. String get verticalLineTripleDashBold => "┇"; /// A dashed horizontal line that can be used to draw a box. /// /// Always "┈" for [this]. String get horizontalLineQuadrupleDash => "┈"; /// A bold dashed horizontal line that can be used to draw a box. /// /// Always "┉" for [this]. String get horizontalLineQuadrupleDashBold => "┉"; /// A dashed vertical line that can be used to draw a box. /// /// Always "┊" for [this]. String get verticalLineQuadrupleDash => "┊"; /// A bold dashed vertical line that can be used to draw a box. /// /// Always "┋" for [this]. String get verticalLineQuadrupleDashBold => "┋"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/builders.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:build_modules/build_modules.dart'; import 'package:build_modules/src/module_cleanup.dart'; import 'package:build_modules/src/module_library_builder.dart'; Builder moduleLibraryBuilder(_) => const ModuleLibraryBuilder(); PostProcessBuilder moduleCleanup(_) => const ModuleCleanup();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/build_modules.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. export 'src/errors.dart' show MissingModulesException, UnsupportedModules; export 'src/kernel_builder.dart' show KernelBuilder, multiRootScheme, reportUnusedKernelInputs; export 'src/meta_module_builder.dart' show MetaModuleBuilder, metaModuleExtension; export 'src/meta_module_clean_builder.dart' show MetaModuleCleanBuilder, metaModuleCleanExtension; export 'src/module_builder.dart' show ModuleBuilder, moduleExtension; export 'src/module_library_builder.dart' show ModuleLibraryBuilder, moduleLibraryExtension; export 'src/modules.dart'; export 'src/platform.dart' show DartPlatform; export 'src/scratch_space.dart' show scratchSpace, scratchSpaceResource; export 'src/workers.dart' show dart2JsWorkerResource, dartdevkDriverResource;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/module_cleanup.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 'module_library_builder.dart'; class ModuleCleanup implements PostProcessBuilder { const ModuleCleanup(); @override void build(PostProcessBuildStep buildStep) { buildStep.deletePrimaryInput(); } @override final inputExtensions = const [ moduleLibraryExtension, '.meta_module.raw', '.meta_module.clean', '.module', ]; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/scratch_space.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 'dart:math' as math; import 'package:build/build.dart'; import 'package:logging/logging.dart'; import 'package:scratch_space/scratch_space.dart'; import 'workers.dart'; final _logger = Logger('BuildModules'); /// A shared [ScratchSpace] for ddc and analyzer workers that persists /// throughout builds. final scratchSpace = ScratchSpace(); /// A shared [Resource] for a [ScratchSpace], which cleans up the contents of /// the [ScratchSpace] in dispose, but doesn't delete it entirely. final scratchSpaceResource = Resource<ScratchSpace>(() { if (!scratchSpace.exists) { scratchSpace.tempDir.createSync(recursive: true); scratchSpace.exists = true; } return scratchSpace; }, beforeExit: () async { // The workers are running inside the scratch space, so wait for them to // shut down before deleting it. await dartdevkWorkersAreDone; await frontendWorkersAreDone; await dart2jsWorkersAreDone; // Attempt to clean up the scratch space. Even after waiting for the workers // to shut down we might get file system exceptions on windows for an // arbitrary amount of time, so do retries with an exponential backoff. var numTries = 0; while (true) { numTries++; if (numTries > 3) { _logger .warning('Failed to clean up temp dir ${scratchSpace.tempDir.path}.'); return; } try { // TODO(https://github.com/dart-lang/build/issues/656): The scratch // space throws on `delete` if it thinks it was already deleted. // Manually clean up in this case. if (scratchSpace.exists) { await scratchSpace.delete(); } else { await scratchSpace.tempDir.delete(recursive: true); } return; } on FileSystemException { var delayMs = math.pow(10, numTries).floor(); _logger.info('Failed to delete temp dir ${scratchSpace.tempDir.path}, ' 'retrying in ${delayMs}ms'); await Future.delayed(Duration(milliseconds: delayMs)); } } });
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/workers.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:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:math' show min; import 'package:bazel_worker/driver.dart'; import 'package:build/build.dart'; import 'package:path/path.dart' as p; import 'package:pedantic/pedantic.dart'; import 'scratch_space.dart'; final sdkDir = p.dirname(p.dirname(Platform.resolvedExecutable)); // If no terminal is attached, prevent a new one from launching. final _processMode = stdin.hasTerminal ? ProcessStartMode.normal : ProcessStartMode.detachedWithStdio; /// Completes once the dartdevk workers have been shut down. Future<void> get dartdevkWorkersAreDone => _dartdevkWorkersAreDoneCompleter?.future ?? Future.value(); Completer<void> _dartdevkWorkersAreDoneCompleter; /// Completes once the dart2js workers have been shut down. Future<void> get dart2jsWorkersAreDone => _dart2jsWorkersAreDoneCompleter?.future ?? Future.value(); Completer<void> _dart2jsWorkersAreDoneCompleter; /// Completes once the common frontend workers have been shut down. Future<void> get frontendWorkersAreDone => _frontendWorkersAreDoneCompleter?.future ?? Future.value(); Completer<void> _frontendWorkersAreDoneCompleter; final int _defaultMaxWorkers = min((Platform.numberOfProcessors / 2).ceil(), 4); const _maxWorkersEnvVar = 'BUILD_MAX_WORKERS_PER_TASK'; final int _maxWorkersPerTask = () { var toParse = Platform.environment[_maxWorkersEnvVar] ?? '$_defaultMaxWorkers'; var parsed = int.tryParse(toParse); if (parsed == null) { log.warning('Invalid value for $_maxWorkersEnvVar environment variable, ' 'expected an int but got `$toParse`. Falling back to default value ' 'of $_defaultMaxWorkers.'); return _defaultMaxWorkers; } return parsed; }(); /// Manages a shared set of persistent dartdevk workers. BazelWorkerDriver get _dartdevkDriver { _dartdevkWorkersAreDoneCompleter ??= Completer<void>(); return __dartdevkDriver ??= BazelWorkerDriver( () => Process.start( p.join(sdkDir, 'bin', 'dart'), [ p.join(sdkDir, 'bin', 'snapshots', 'dartdevc.dart.snapshot'), '--kernel', '--persistent_worker' ], mode: _processMode, workingDirectory: scratchSpace.tempDir.path), maxWorkers: _maxWorkersPerTask); } BazelWorkerDriver __dartdevkDriver; /// Resource for fetching the current [BazelWorkerDriver] for dartdevk. final dartdevkDriverResource = Resource<BazelWorkerDriver>(() => _dartdevkDriver, beforeExit: () async { await _dartdevkDriver?.terminateWorkers(); _dartdevkWorkersAreDoneCompleter.complete(); _dartdevkWorkersAreDoneCompleter = null; __dartdevkDriver = null; }); /// Manages a shared set of persistent common frontend workers. BazelWorkerDriver get _frontendDriver { _frontendWorkersAreDoneCompleter ??= Completer<void>(); return __frontendDriver ??= BazelWorkerDriver( () => Process.start( p.join(sdkDir, 'bin', 'dart'), [ p.join(sdkDir, 'bin', 'snapshots', 'kernel_worker.dart.snapshot'), '--persistent_worker' ], mode: _processMode, workingDirectory: scratchSpace.tempDir.path), maxWorkers: _maxWorkersPerTask); } BazelWorkerDriver __frontendDriver; /// Resource for fetching the current [BazelWorkerDriver] for common frontend. final frontendDriverResource = Resource<BazelWorkerDriver>(() => _frontendDriver, beforeExit: () async { await _frontendDriver?.terminateWorkers(); _frontendWorkersAreDoneCompleter.complete(); _frontendWorkersAreDoneCompleter = null; __frontendDriver = null; }); const _dart2jsVmArgsEnvVar = 'BUILD_DART2JS_VM_ARGS'; final _dart2jsVmArgs = () { var env = Platform.environment[_dart2jsVmArgsEnvVar]; return env?.split(' ') ?? <String>[]; }(); /// Manages a shared set of persistent dart2js workers. Dart2JsBatchWorkerPool get _dart2jsWorkerPool { _dart2jsWorkersAreDoneCompleter ??= Completer<void>(); var librariesSpec = p.joinAll([sdkDir, 'lib', 'libraries.json']); return __dart2jsWorkerPool ??= Dart2JsBatchWorkerPool(() => Process.start( p.join(sdkDir, 'bin', 'dart'), [ ..._dart2jsVmArgs, p.join(sdkDir, 'bin', 'snapshots', 'dart2js.dart.snapshot'), '--libraries-spec=$librariesSpec', '--batch', ], mode: _processMode, workingDirectory: scratchSpace.tempDir.path)); } Dart2JsBatchWorkerPool __dart2jsWorkerPool; /// Resource for fetching the current [Dart2JsBatchWorkerPool] for dart2js. final dart2JsWorkerResource = Resource<Dart2JsBatchWorkerPool>( () => _dart2jsWorkerPool, beforeExit: () async { await _dart2jsWorkerPool.terminateWorkers(); _dart2jsWorkersAreDoneCompleter.complete(); _dart2jsWorkersAreDoneCompleter = null; }); /// Manages a pool of persistent [_Dart2JsWorker]s running in batch mode and /// schedules jobs among them. class Dart2JsBatchWorkerPool { final Future<Process> Function() _spawnWorker; final _workQueue = Queue<_Dart2JsJob>(); bool _queueIsActive = false; final _availableWorkers = Queue<_Dart2JsWorker>(); final _allWorkers = <_Dart2JsWorker>[]; Dart2JsBatchWorkerPool(this._spawnWorker); Future<Dart2JsResult> compile(List<String> args) async { var job = _Dart2JsJob(args); _workQueue.add(job); if (!_queueIsActive) _startWorkQueue(); return job.result; } void _startWorkQueue() { assert(!_queueIsActive); _queueIsActive = true; () async { while (_workQueue.isNotEmpty) { _Dart2JsWorker worker; if (_availableWorkers.isEmpty && _allWorkers.length < _maxWorkersPerTask) { worker = _Dart2JsWorker(_spawnWorker); _allWorkers.add(worker); } _Dart2JsWorker nextWorker() => _availableWorkers.isNotEmpty ? _availableWorkers.removeFirst() : null; worker ??= nextWorker(); while (worker == null) { // TODO: something smarter here? in practice this seems to work // reasonably well though and simplifies things a lot ¯\_(ツ)_/¯. await Future.delayed(Duration(seconds: 1)); worker = nextWorker(); } unawaited(worker .doJob(_workQueue.removeFirst()) .whenComplete(() => _availableWorkers.add(worker))); } _queueIsActive = false; }(); } Future<void> terminateWorkers() async { var allWorkers = _allWorkers.toList(); _allWorkers.clear(); _availableWorkers.clear(); await Future.wait(allWorkers.map((w) => w.terminate())); } } /// A single dart2js worker process running in batch mode. /// /// This may actually spawn multiple processes over time, if a running worker /// dies or it decides that it should be restarted for some reason. class _Dart2JsWorker { final Future<Process> Function() _spawnWorker; int _jobsSinceLastRestartCount = 0; static const int _jobsBeforeRestartMax = 5; static const int _retryCountMax = 2; Stream<String> __workerStderrLines; Stream<String> get _workerStderrLines { assert(__worker != null); return __workerStderrLines ??= __worker.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .asBroadcastStream(); } Stream<String> __workerStdoutLines; Stream<String> get _workerStdoutLines { assert(__worker != null); return __workerStdoutLines ??= __worker.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .asBroadcastStream(); } Process __worker; Future<Process> _spawningWorker; Future<Process> get _worker { if (__worker != null) return Future.value(__worker); return _spawningWorker ??= () async { if (__worker == null) { _jobsSinceLastRestartCount = 0; __worker ??= await _spawnWorker(); _spawningWorker = null; unawaited(_workerStdoutLines.drain().whenComplete(() { __worker = null; __workerStdoutLines = null; __workerStderrLines = null; _currentJobResult ?.completeError('Dart2js exited with an unknown error'); })); } return __worker; }(); } Completer<Dart2JsResult> _currentJobResult; _Dart2JsWorker(this._spawnWorker); /// Performs [job], gracefully handling worker failures by retrying /// [_retryCountMax] times and restarting the worker between jobs based on /// [_jobsBeforeRestartMax] to limit memory consumption. /// /// Only one job may be performed at a time. Future<void> doJob(_Dart2JsJob job) async { assert(_currentJobResult == null); var tryCount = 0; var succeeded = false; while (tryCount < _retryCountMax && !succeeded) { tryCount++; _jobsSinceLastRestartCount++; var worker = await _worker; var output = StringBuffer(); _currentJobResult = Completer<Dart2JsResult>(); var sawError = false; var stderrListener = _workerStderrLines.listen((line) { if (line == '>>> EOF STDERR') { _currentJobResult?.complete( Dart2JsResult(!sawError, 'Dart2Js finished with:\n\n$output')); } if (!line.startsWith('>>> ')) { output.writeln(line); } }); var stdoutListener = _workerStdoutLines.listen((line) { if (line.contains('>>> TEST FAIL')) { sawError = true; } if (!line.startsWith('>>> ')) { output.writeln(line); } }); log.info('Running dart2js with ${job.args.join(' ')}\n'); worker.stdin.writeln(job.args.join(' ')); Dart2JsResult result; try { result = await _currentJobResult.future; job.resultCompleter.complete(result); succeeded = true; } catch (e) { log.warning('Dart2Js failure: $e'); succeeded = false; if (tryCount >= _retryCountMax) { job.resultCompleter.complete(_currentJobResult.future); } } finally { _currentJobResult = null; // TODO: Remove this hack once dart-lang/sdk#33708 is resolved. if (_jobsSinceLastRestartCount >= _jobsBeforeRestartMax) { await terminate(); } await stderrListener.cancel(); await stdoutListener.cancel(); } } } Future<void> terminate() async { var worker = __worker ?? await _spawningWorker; var oldStdout = __workerStdoutLines; __worker = null; __workerStdoutLines = null; __workerStderrLines = null; if (worker != null) { worker.kill(); await worker.stdin.close(); } await oldStdout?.drain(); } } /// A single dart2js job, consisting of [args] and a [result]. class _Dart2JsJob { final List<String> args; final resultCompleter = Completer<Dart2JsResult>(); Future<Dart2JsResult> get result => resultCompleter.future; _Dart2JsJob(this.args); } /// The result of a [_Dart2JsJob] class Dart2JsResult { final bool succeeded; final String output; Dart2JsResult(this.succeeded, this.output); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/meta_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. import 'dart:async'; import 'package:build/build.dart'; import 'package:graphs/graphs.dart'; import 'package:path/path.dart' as p; import 'package:json_annotation/json_annotation.dart'; import 'common.dart'; import 'module_library.dart'; import 'modules.dart'; import 'platform.dart'; part 'meta_module.g.dart'; /// Returns the top level directory in [path]. /// /// Throws an [ArgumentError] if [path] is just a filename with no directory. String _topLevelDir(String path) { var parts = p.url.split(p.url.normalize(path)); String error; if (parts.length == 1) { error = 'The path `$path` does not contain a directory.'; } else if (parts.first == '..') { error = 'The path `$path` reaches outside the root directory.'; } if (error != null) { throw ArgumentError( 'Cannot compute top level dir for path `$path`. $error'); } return parts.first; } /// Creates a module containing [componentLibraries]. Module _moduleForComponent( List<ModuleLibrary> componentLibraries, DartPlatform platform) { // Name components based on first alphabetically sorted node, preferring // public srcs (not under lib/src). var sources = componentLibraries.map((n) => n.id).toSet(); var nonSrcIds = sources.where((id) => !id.path.startsWith('lib/src/')); var primaryId = nonSrcIds.isNotEmpty ? nonSrcIds.reduce(_min) : sources.reduce(_min); // Expand to include all the part files of each node, these aren't // included as individual `_AssetNodes`s in `connectedComponents`. sources.addAll(componentLibraries.expand((n) => n.parts)); var directDependencies = <AssetId>{} ..addAll(componentLibraries.expand((n) => n.depsForPlatform(platform))) ..removeAll(sources); var isSupported = componentLibraries .expand((l) => l.sdkDeps) .every(platform.supportsLibrary); return Module(primaryId, sources, directDependencies, platform, isSupported); } /// Gets the local (same top level dir of the same package) transitive deps of /// [module] using [assetsToModules]. Set<AssetId> _localTransitiveDeps( Module module, Map<AssetId, Module> assetsToModules) { var localTransitiveDeps = <AssetId>{}; var nextIds = module.directDependencies; var seenIds = <AssetId>{}; while (nextIds.isNotEmpty) { var ids = nextIds; seenIds.addAll(ids); nextIds = <AssetId>{}; for (var id in ids) { var module = assetsToModules[id]; if (module == null) continue; // Skip non-local modules if (localTransitiveDeps.add(module.primarySource)) { nextIds.addAll(module.directDependencies.difference(seenIds)); } } } return localTransitiveDeps; } /// Creates a map of modules to the entrypoint modules that transitively /// depend on those modules. Map<AssetId, Set<AssetId>> _findReverseEntrypointDeps( Iterable<Module> entrypointModules, Iterable<Module> modules) { var reverseDeps = <AssetId, Set<AssetId>>{}; var assetsToModules = <AssetId, Module>{}; for (var module in modules) { for (var assetId in module.sources) { assetsToModules[assetId] = module; } } for (var module in entrypointModules) { for (var moduleDep in _localTransitiveDeps(module, assetsToModules)) { reverseDeps .putIfAbsent(moduleDep, () => <AssetId>{}) .add(module.primarySource); } } return reverseDeps; } /// Merges [modules] into a minimum set of [Module]s using the /// following rules: /// /// * If it is an entrypoint module do not merge it. /// * If it is not depended on my any entrypoint do not merge it. /// * If it is depended on by no entrypoint merge it into the entrypoint /// modules /// * Else merge it into with others that are depended on by the same set of /// entrypoints List<Module> _mergeModules(Iterable<Module> modules, Set<AssetId> entrypoints) { var entrypointModules = modules.where((m) => m.sources.any(entrypoints.contains)).toList(); // Groups of modules that can be merged into an existing entrypoint module. var entrypointModuleGroups = { for (var m in entrypointModules) m.primarySource: [m], }; // Maps modules to entrypoint modules that transitively depend on them. var modulesToEntryPoints = _findReverseEntrypointDeps(entrypointModules, modules); // Modules which are not depended on by any entrypoint var standaloneModules = <Module>[]; // Modules which are merged with others. var mergedModules = <String, List<Module>>{}; for (var module in modules) { // Skip entrypoint modules. if (entrypointModuleGroups.containsKey(module.primarySource)) continue; // The entry points that transitively import this module. var entrypointIds = modulesToEntryPoints[module.primarySource]; // If no entrypoint imports the module, just leave it alone. if (entrypointIds == null || entrypointIds.isEmpty) { standaloneModules.add(module); continue; } // If there are multiple entry points for a given resource we must create // a new shared module. Use `$` to signal that it is a shared module. if (entrypointIds.length > 1) { var mId = (entrypointIds.toList()..sort()).map((m) => m.path).join('\$'); mergedModules.putIfAbsent(mId, () => []).add(module); } else { entrypointModuleGroups[entrypointIds.single].add(module); } } return mergedModules.values .map(Module.merge) .map(_withConsistentPrimarySource) .followedBy(entrypointModuleGroups.values.map(Module.merge)) .followedBy(standaloneModules) .toList(); } Module _withConsistentPrimarySource(Module m) => Module(m.sources.reduce(_min), m.sources, m.directDependencies, m.platform, m.isSupported); T _min<T extends Comparable<T>>(T a, T b) => a.compareTo(b) < 0 ? a : b; /// Compute modules for the internal strongly connected components of /// [libraries]. /// /// This should only be called with [libraries] all in the same package and top /// level directory within the package. /// /// A dependency is considered "internal" if it is within [libraries]. Any /// "external" deps are ignored during this computation since we are only /// considering the strongly connected components within [libraries], but they /// will be maintained as a dependency of the module to be used at a later step. /// /// Part files are also tracked but ignored during computation of strongly /// connected components, as they must always be a part of the containing /// library's module. List<Module> _computeModules( Map<AssetId, ModuleLibrary> libraries, DartPlatform platform) { assert(() { var dir = _topLevelDir(libraries.values.first.id.path); return libraries.values.every((l) => _topLevelDir(l.id.path) == dir); }()); final connectedComponents = stronglyConnectedComponents<ModuleLibrary>( libraries.values, (n) => n .depsForPlatform(platform) // Only "internal" dependencies .where(libraries.containsKey) .map((dep) => libraries[dep]), equals: (a, b) => a.id == b.id, hashCode: (l) => l.id.hashCode); final entryIds = libraries.values.where((l) => l.isEntryPoint).map((l) => l.id).toSet(); return _mergeModules( connectedComponents.map((c) => _moduleForComponent(c, platform)), entryIds); } @JsonSerializable() class MetaModule { @JsonKey(name: 'm', nullable: false) final List<Module> modules; MetaModule(List<Module> modules) : modules = List.unmodifiable(modules); /// Generated factory constructor. factory MetaModule.fromJson(Map<String, dynamic> json) => _$MetaModuleFromJson(json); Map<String, dynamic> toJson() => _$MetaModuleToJson(this); static Future<MetaModule> forLibraries( AssetReader reader, List<AssetId> libraryIds, ModuleStrategy strategy, DartPlatform platform) async { var libraries = <ModuleLibrary>[]; for (var id in libraryIds) { libraries.add(ModuleLibrary.deserialize( id.changeExtension('').changeExtension('.dart'), await reader.readAsString(id))); } switch (strategy) { case ModuleStrategy.fine: return _fineModulesForLibraries(reader, libraries, platform); case ModuleStrategy.coarse: return _coarseModulesForLibraries(reader, libraries, platform); } throw StateError('Unrecognized module strategy $strategy'); } } MetaModule _coarseModulesForLibraries( AssetReader reader, List<ModuleLibrary> libraries, DartPlatform platform) { var librariesByDirectory = <String, Map<AssetId, ModuleLibrary>>{}; for (var library in libraries) { final dir = _topLevelDir(library.id.path); if (!librariesByDirectory.containsKey(dir)) { librariesByDirectory[dir] = <AssetId, ModuleLibrary>{}; } librariesByDirectory[dir][library.id] = library; } final modules = librariesByDirectory.values .expand((libs) => _computeModules(libs, platform)) .toList(); _sortModules(modules); return MetaModule(modules); } MetaModule _fineModulesForLibraries( AssetReader reader, List<ModuleLibrary> libraries, DartPlatform platform) { var modules = libraries .map((library) => Module( library.id, library.parts.followedBy([library.id]), library.depsForPlatform(platform), platform, library.sdkDeps.every(platform.supportsLibrary))) .toList(); _sortModules(modules); return MetaModule(modules); } /// Sorts [modules] in place so we get deterministic output. void _sortModules(List<Module> modules) { modules.sort((a, b) => a.primarySource.compareTo(b.primarySource)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/module_builder.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'; import 'meta_module_clean_builder.dart'; import 'module_cache.dart'; import 'module_library.dart'; import 'module_library_builder.dart' show moduleLibraryExtension; import 'modules.dart'; import 'platform.dart'; /// The extension for serialized module assets. String moduleExtension(DartPlatform platform) => '.${platform.name}.module'; /// Creates `.module` files for any `.dart` file that is the primary dart /// source of a [Module]. class ModuleBuilder implements Builder { final DartPlatform _platform; ModuleBuilder(this._platform) : buildExtensions = { '.dart': [moduleExtension(_platform)] }; @override final Map<String, List<String>> buildExtensions; @override Future build(BuildStep buildStep) async { final cleanMetaModules = await buildStep.fetchResource(metaModuleCache); final metaModule = await cleanMetaModules.find( AssetId(buildStep.inputId.package, 'lib/${metaModuleCleanExtension(_platform)}'), buildStep); var outputModule = metaModule.modules.firstWhere( (m) => m.primarySource == buildStep.inputId, orElse: () => null); if (outputModule == null) { final serializedLibrary = await buildStep.readAsString( buildStep.inputId.changeExtension(moduleLibraryExtension)); final libraryModule = ModuleLibrary.deserialize(buildStep.inputId, serializedLibrary); if (libraryModule.hasMain) { outputModule = metaModule.modules .firstWhere((m) => m.sources.contains(buildStep.inputId)); } } if (outputModule == null) return; final modules = await buildStep.fetchResource(moduleCache); await modules.write( buildStep.inputId.changeExtension(moduleExtension(_platform)), buildStep, outputModule); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/modules.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'modules.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Module _$ModuleFromJson(Map<String, dynamic> json) { return Module( const _AssetIdConverter().fromJson(json['p'] as List), (json['s'] as List) .map((e) => const _AssetIdConverter().fromJson(e as List)), (json['d'] as List) .map((e) => const _AssetIdConverter().fromJson(e as List)), const _DartPlatformConverter().fromJson(json['pf'] as String), json['is'] as bool, isMissing: json['m'] as bool ?? false, ); } Map<String, dynamic> _$ModuleToJson(Module instance) => <String, dynamic>{ 'p': const _AssetIdConverter().toJson(instance.primarySource), 's': _toJsonAssetIds(instance.sources), 'd': _toJsonAssetIds(instance.directDependencies), 'm': instance.isMissing, 'is': instance.isSupported, 'pf': const _DartPlatformConverter().toJson(instance.platform), };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/platform.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. /// A supported "platform" for compilation of Dart libraries. /// /// Each "platform" has its own compilation pipeline and builders, and could /// differ from other platforms in many ways: /// /// - The core libs that are supported /// - The implementations of the core libs /// - The compilation steps that are required (frontends or backends could be /// different). /// /// Typically these should correspond to `libraries.json` files in the SDK. /// /// New platforms should be created with [register], and can later be /// fetched by name using the [DartPlatform.byName] static method. class DartPlatform { /// A list of all registered platforms by name, populated by /// [register]. static final _platformsByName = <String, DartPlatform>{}; final List<String> _supportedLibraries; final String name; /// Returns a [DartPlatform] instance by name. /// /// Throws an [UnrecognizedDartPlatform] if [name] has not been /// registered with [DartPlatform.register]. static DartPlatform byName(String name) => _platformsByName[name] ?? (throw UnrecognizedDartPlatform(name)); /// Registers a new [DartPlatform]. /// /// Throws a [DartPlatformAlreadyRegistered] if [name] has already /// been registered by somebody else. static DartPlatform register(String name, List<String> supportedLibraries) { if (_platformsByName.containsKey(name)) { throw DartPlatformAlreadyRegistered(name); } return _platformsByName[name] = DartPlatform._(name, List.unmodifiable(supportedLibraries)); } const DartPlatform._(this.name, this._supportedLibraries); /// Returns whether or not [library] is supported on this platform. /// /// The [library] is path portion of a `dart:` import (should not include the /// scheme). bool supportsLibrary(String library) => _supportedLibraries.contains(library); @override int get hashCode => name.hashCode; @override bool operator ==(other) => other is DartPlatform && other.name == name; } class DartPlatformAlreadyRegistered implements Exception { final String name; const DartPlatformAlreadyRegistered(this.name); @override String toString() => 'The platform `$name`, has already been registered.'; } class UnrecognizedDartPlatform implements Exception { final String name; const UnrecognizedDartPlatform(this.name); @override String toString() => 'Unrecognized platform `$name`, it must be registered ' 'first using `DartPlatform.register`'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/meta_module_clean_builder.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 'package:build/build.dart'; import 'package:graphs/graphs.dart'; import 'meta_module.dart'; import 'meta_module_builder.dart'; import 'module_cache.dart'; import 'modules.dart'; import 'platform.dart'; /// The extension for serialized clean meta module assets. /// /// Clean in this context means all dependencies are primary sources. /// Furthermore cyclic modules are merged into a single module. String metaModuleCleanExtension(DartPlatform platform) => '.${platform.name}.meta_module.clean'; /// Creates `.meta_module.clean` file for any Dart library. /// /// This file contains information about the full computed /// module structure for the package where each module's dependencies /// are only primary sources. /// /// Note if the raw meta module file can't be found for any of the /// module's transitive dependencies there will be no output. class MetaModuleCleanBuilder implements Builder { @override final Map<String, List<String>> buildExtensions; final DartPlatform _platform; MetaModuleCleanBuilder(this._platform) : buildExtensions = { metaModuleExtension(_platform): [metaModuleCleanExtension(_platform)] }; @override Future build(BuildStep buildStep) async { var assetToModule = (await buildStep.fetchResource(_assetToModule)) .putIfAbsent(_platform, () => {}); var assetToPrimary = (await buildStep.fetchResource(_assetToPrimary)) .putIfAbsent(_platform, () => {}); var modules = await _transitiveModules( buildStep, buildStep.inputId, assetToModule, assetToPrimary, _platform); var connectedComponents = stronglyConnectedComponents<Module>( modules, (m) => m.directDependencies.map((d) => assetToModule[d] ?? Module(d, [d], [], _platform, false, isMissing: true)), equals: (a, b) => a.primarySource == b.primarySource, hashCode: (m) => m.primarySource.hashCode); Module merge(List<Module> c) => _mergeComponent(c, assetToPrimary, _platform); bool primarySourceInPackage(Module m) => m.primarySource.package == buildStep.inputId.package; // Ensure deterministic output by sorting the modules. var cleanModules = SplayTreeSet<Module>( (a, b) => a.primarySource.compareTo(b.primarySource)) ..addAll(connectedComponents.map(merge).where(primarySourceInPackage)); await buildStep.writeAsString( AssetId(buildStep.inputId.package, 'lib/${metaModuleCleanExtension(_platform)}'), jsonEncode(MetaModule(cleanModules.toList()))); } } /// Map of [AssetId] to corresponding non clean containing [Module] per /// [DartPlatform]. final _assetToModule = Resource<Map<DartPlatform, Map<AssetId, Module>>>( () => {}, dispose: (map) => map.clear()); /// Map of [AssetId] to corresponding primary [AssetId] within the same /// clean [Module] per platform. final _assetToPrimary = Resource<Map<DartPlatform, Map<AssetId, AssetId>>>( () => {}, dispose: (map) => map.clear()); /// Returns a set of all modules transitively reachable from the provided meta /// module asset. Future<Set<Module>> _transitiveModules( BuildStep buildStep, AssetId metaAsset, Map<AssetId, Module> assetToModule, Map<AssetId, AssetId> assetToPrimary, DartPlatform platform) async { var dependentModules = <Module>{}; // Ensures we only process a meta file once. var seenMetas = <AssetId>{}..add(metaAsset); var metaModules = await buildStep.fetchResource(metaModuleCache); var meta = await metaModules.find(buildStep.inputId, buildStep); var nextModules = List.of(meta.modules); while (nextModules.isNotEmpty) { var module = nextModules.removeLast(); dependentModules.add(module); for (var source in module.sources) { assetToModule[source] = module; // The asset to primary map will be updated when the merged modules are // created. This is why we can't use the assetToModule map. assetToPrimary[source] = module.primarySource; } for (var dep in module.directDependencies) { var depMetaAsset = AssetId(dep.package, 'lib/${metaModuleExtension(platform)}'); // The testing package is an odd package used by package:frontend_end // which doesn't really exist. // https://github.com/dart-lang/sdk/issues/32952 if (seenMetas.contains(depMetaAsset) || dep.package == 'testing') { continue; } seenMetas.add(depMetaAsset); if (!await buildStep.canRead(depMetaAsset)) { log.warning('Unable to read module information for ' 'package:${depMetaAsset.package}, make sure you have a dependency ' 'on it in your pubspec.'); continue; } var depMeta = await metaModules.find(depMetaAsset, buildStep); nextModules.addAll(depMeta.modules); } } return dependentModules; } /// Merges the modules in a strongly connected component. /// /// Note this will clean the module dependencies as the merge happens. /// The result will be that all dependencies are primary sources. Module _mergeComponent(List<Module> connectedComponent, Map<AssetId, AssetId> assetToPrimary, DartPlatform platform) { var sources = <AssetId>{}; var deps = <AssetId>{}; // Sort the modules to deterministicly select the primary source. var components = SplayTreeSet<Module>((a, b) => a.primarySource.compareTo(b.primarySource)) ..addAll(connectedComponent); var primarySource = components.first.primarySource; var isSupported = true; for (var module in connectedComponent) { sources.addAll(module.sources); isSupported = isSupported && module.isSupported; for (var dep in module.directDependencies) { var primaryDep = assetToPrimary[dep]; if (primaryDep == null) continue; // This dep is now merged into sources so skip it. if (!components .map((c) => c.sources) .any((s) => s.contains(primaryDep))) { deps.add(primaryDep); } } } // Update map so that sources now point to the merged module. var mergedModule = Module(primarySource, sources, deps, platform, isSupported); for (var source in mergedModule.sources) { assetToPrimary[source] = mergedModule.primarySource; } return mergedModule; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/meta_module.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'meta_module.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** MetaModule _$MetaModuleFromJson(Map<String, dynamic> json) { return MetaModule( (json['m'] as List) .map((e) => Module.fromJson(e as Map<String, dynamic>)) .toList(), ); } Map<String, dynamic> _$MetaModuleToJson(MetaModule instance) => <String, dynamic>{ 'm': instance.modules, };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/meta_module_builder.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/build.dart'; import 'package:glob/glob.dart'; import 'common.dart'; import 'meta_module.dart'; import 'module_cache.dart'; import 'module_library_builder.dart'; import 'platform.dart'; /// The extension for serialized meta module assets for a specific platform. String metaModuleExtension(DartPlatform platform) => '.${platform.name}.meta_module.raw'; /// Creates `.meta_module` file for any Dart library. /// /// This file contains information about the full computed /// module structure for the package. class MetaModuleBuilder implements Builder { @override final Map<String, List<String>> buildExtensions; final ModuleStrategy strategy; final DartPlatform _platform; MetaModuleBuilder(this._platform, {ModuleStrategy strategy}) : strategy = strategy ?? ModuleStrategy.coarse, buildExtensions = { r'$lib$': [metaModuleExtension(_platform)] }; factory MetaModuleBuilder.forOptions( DartPlatform platform, BuilderOptions options) => MetaModuleBuilder(platform, strategy: moduleStrategy(options)); @override Future build(BuildStep buildStep) async { if (buildStep.inputId.package == r'$sdk') return; var libraryAssets = await buildStep.findAssets(Glob('**$moduleLibraryExtension')).toList(); var metaModule = await MetaModule.forLibraries( buildStep, libraryAssets, strategy, _platform); var id = AssetId( buildStep.inputId.package, 'lib/${metaModuleExtension(_platform)}'); var metaModules = await buildStep.fetchResource(metaModuleCache); await metaModules.write(id, buildStep, metaModule); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/module_library_builder.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/build.dart'; import 'module_library.dart'; const moduleLibraryExtension = '.module.library'; /// Creates `.module.library` assets listing the dependencies and parts for a /// Dart library, as well as whether it is an entrypoint. /// /// /// The output format is determined by [ModuleLibrary.serialize] and can be /// restored by [ModuleLibrary.deserialize]. /// /// Non-importable Dart source files will not get a `.module.library` asset /// output. See [ModuleLibrary.isImportable]. class ModuleLibraryBuilder implements Builder { const ModuleLibraryBuilder(); @override final buildExtensions = const { '.dart': [moduleLibraryExtension] }; @override Future build(BuildStep buildStep) async { final library = ModuleLibrary.fromSource( buildStep.inputId, await buildStep.readAsString(buildStep.inputId)); if (!library.isImportable) return; await buildStep.writeAsString( buildStep.inputId.changeExtension(moduleLibraryExtension), library.serialize()); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/common.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/build.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; import 'kernel_builder.dart'; final defaultAnalysisOptionsId = AssetId('build_modules', 'lib/src/analysis_options.default.yaml'); String defaultAnalysisOptionsArg(ScratchSpace scratchSpace) => '--options=${scratchSpace.fileFor(defaultAnalysisOptionsId).path}'; // TODO: better solution for a .packages file, today we just create a new one // for every kernel build action. Future<File> createPackagesFile(Iterable<AssetId> allAssets) async { var allPackages = allAssets.map((id) => id.package).toSet(); var packagesFileDir = await Directory.systemTemp.createTemp('kernel_builder_'); var packagesFile = File(p.join(packagesFileDir.path, '.packages')); await packagesFile.create(); await packagesFile.writeAsString(allPackages .map((pkg) => '$pkg:$multiRootScheme:///packages/$pkg') .join('\r\n')); return packagesFile; } enum ModuleStrategy { fine, coarse } ModuleStrategy moduleStrategy(BuilderOptions options) { var config = options.config['strategy'] as String ?? 'coarse'; switch (config) { case 'coarse': return ModuleStrategy.coarse; case 'fine': return ModuleStrategy.fine; default: throw ArgumentError('Unexpected ModuleBuilder strategy: $config'); } } /// Validates that [config] only has the top level keys [supportedOptions]. /// /// Throws an [ArgumentError] if not. void validateOptions(Map<String, dynamic> config, List<String> supportedOptions, String builderKey) { var unsupportedOptions = config.keys.where((o) => !supportedOptions.contains(o)); if (unsupportedOptions.isNotEmpty) { throw ArgumentError.value(unsupportedOptions.join(', '), builderKey, 'only $supportedOptions are supported options, but got'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/module_cache.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:convert'; import 'package:async/async.dart'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'meta_module.dart'; import 'modules.dart'; Map<String, dynamic> _deserialize(List<int> bytes) => jsonDecode(utf8.decode(bytes)) as Map<String, dynamic>; List<int> _serialize(Map<String, dynamic> data) => utf8.encode(jsonEncode(data)); final metaModuleCache = DecodingCache.resource( (m) => MetaModule.fromJson(_deserialize(m)), (m) => _serialize(m.toJson())); final moduleCache = DecodingCache.resource( (m) => Module.fromJson(_deserialize(m)), (m) => _serialize(m.toJson())); /// A cache of objects decoded from written assets suitable for use as a /// [Resource]. /// /// Instances that are decoded will be cached throughout the duration of a build /// and invalidated between builds. Instances that are shared through the cache /// should be treated as immutable to avoid leaking any information which was /// not loaded from the underlying asset. class DecodingCache<T> { /// Create a [Resource] which can decoded instances of [T] serialized via json /// to assets. static Resource<DecodingCache<T>> resource<T>( T Function(List<int>) fromBytes, List<int> Function(T) toBytes) => Resource<DecodingCache<T>>(() => DecodingCache._(fromBytes, toBytes), dispose: (c) => c._dispose()); final _cached = <AssetId, _Entry<T>>{}; final T Function(List<int>) _fromBytes; final List<int> Function(T) _toBytes; DecodingCache._(this._fromBytes, this._toBytes); void _dispose() { _cached.removeWhere((_, entry) => entry.digest == null); for (var entry in _cached.values) { entry.needsCheck = true; } } /// Find and deserialize a [T] stored in [id]. /// /// If the asset at [id] is unreadable the returned future will resolve to /// `null`. If the instance is cached it will not be decoded again, but the /// content dependencies will be tracked through [reader]. Future<T> find(AssetId id, AssetReader reader) async { if (!await reader.canRead(id)) return null; _Entry<T> entry; if (!_cached.containsKey(id)) { entry = _cached[id] = _Entry() ..needsCheck = false ..value = Result.capture(reader.readAsBytes(id).then(_fromBytes)) ..digest = Result.capture(reader.digest(id)); } else { entry = _cached[id]; if (entry.needsCheck) { await (entry.onGoingCheck ??= () async { var previousDigest = await Result.release(entry.digest); entry.digest = Result.capture(reader.digest(id)); if (await Result.release(entry.digest) != previousDigest) { entry.value = Result.capture(reader.readAsBytes(id).then(_fromBytes)); } entry ..needsCheck = false ..onGoingCheck = null; }()); } } return Result.release(entry.value); } /// Serialized and write a [T] to [id]. /// /// The instance will be cached so that later calls to [find] may return the /// instances without deserializing it. Future<void> write(AssetId id, AssetWriter writer, T instance) async { await writer.writeAsBytes(id, _toBytes(instance)); _cached[id] = _Entry() ..needsCheck = false ..value = Result.capture(Future.value(instance)); } } class _Entry<T> { bool needsCheck = false; Future<Result<T>> value; Future<Result<Digest>> digest; Future<void> onGoingCheck; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/module_library.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'; // ignore: deprecated_member_use import 'package:analyzer/analyzer.dart'; import 'package:build/build.dart'; import 'package:meta/meta.dart'; import 'platform.dart'; /// A Dart library within a module. /// /// Modules can be computed based on library dependencies (imports and exports) /// and parts. class ModuleLibrary { /// The AssetId of the original Dart source file. final AssetId id; /// Whether this library can be imported. /// /// This will be false if the source file is a "part of", or imports code that /// can't be used outside the SDK. final bool isImportable; /// Whether this library is an entrypoint. /// /// True if the library is in `lib/` but not `lib/src`, or if it is outside of /// `lib/` and contains a `main` method. Always false if this is not an /// importable library. final bool isEntryPoint; /// Deps that are imported with a conditional import. /// /// Keys are the stringified ast node for the conditional, and the default /// import is under the magic `$default` key. final List<Map<String, AssetId>> conditionalDeps; /// The IDs of libraries that are imported or exported by this library. /// /// Null if this is not an importable library. final Set<AssetId> _deps; /// The "part" files for this library. /// /// Null if this is not an importable library. final Set<AssetId> parts; /// The `dart:` libraries that this library directly depends on. final Set<String> sdkDeps; /// Whether this library has a `main` function. final bool hasMain; ModuleLibrary._(this.id, {@required this.isEntryPoint, @required Set<AssetId> deps, @required this.parts, @required this.conditionalDeps, @required this.sdkDeps, @required this.hasMain}) : _deps = deps, isImportable = true; ModuleLibrary._nonImportable(this.id) : isImportable = false, isEntryPoint = false, _deps = null, parts = null, conditionalDeps = null, sdkDeps = null, hasMain = false; factory ModuleLibrary._fromCompilationUnit( AssetId id, bool isEntryPoint, CompilationUnit parsed) { var deps = <AssetId>{}; var parts = <AssetId>{}; var sdkDeps = <String>{}; var conditionalDeps = <Map<String, AssetId>>[]; for (var directive in parsed.directives) { if (directive is! UriBasedDirective) continue; var path = (directive as UriBasedDirective).uri.stringValue; var uri = Uri.parse(path); if (uri.isScheme('dart-ext')) { // TODO: What should we do for native extensions? continue; } if (uri.scheme == 'dart') { sdkDeps.add(uri.path); continue; } var linkedId = AssetId.resolve(path, from: id); if (linkedId == null) continue; if (directive is PartDirective) { parts.add(linkedId); continue; } List<Configuration> conditionalDirectiveConfigurations; if (directive is ImportDirective && directive.configurations.isNotEmpty) { conditionalDirectiveConfigurations = directive.configurations; } else if (directive is ExportDirective && directive.configurations.isNotEmpty) { conditionalDirectiveConfigurations = directive.configurations; } if (conditionalDirectiveConfigurations != null) { var conditions = <String, AssetId>{r'$default': linkedId}; for (var condition in conditionalDirectiveConfigurations) { if (Uri.parse(condition.uri.stringValue).scheme == 'dart') { throw ArgumentError('Unsupported conditional import of ' '`${condition.uri.stringValue}` found in $id.'); } conditions[condition.name.toSource()] = AssetId.resolve(condition.uri.stringValue, from: id); } conditionalDeps.add(conditions); } else { deps.add(linkedId); } } return ModuleLibrary._(id, isEntryPoint: isEntryPoint, deps: deps, parts: parts, sdkDeps: sdkDeps, conditionalDeps: conditionalDeps, hasMain: _hasMainMethod(parsed)); } /// Parse the directives from [source] and compute the library information. static ModuleLibrary fromSource(AssetId id, String source) { final isLibDir = id.path.startsWith('lib/'); // ignore: deprecated_member_use final parsed = parseCompilationUnit(source, name: id.path, suppressErrors: true, parseFunctionBodies: false); // Packages within the SDK but published might have libraries that can't be // used outside the SDK. if (parsed.directives.any((d) => d is UriBasedDirective && d.uri.stringValue.startsWith('dart:_') && id.package != 'dart_internal')) { return ModuleLibrary._nonImportable(id); } if (_isPart(parsed)) { return ModuleLibrary._nonImportable(id); } final isEntryPoint = (isLibDir && !id.path.startsWith('lib/src/')) || _hasMainMethod(parsed); return ModuleLibrary._fromCompilationUnit(id, isEntryPoint, parsed); } /// Parses the output of [serialize] back into a [ModuleLibrary]. /// /// Importable libraries can be round tripped to a String. Non-importable /// libraries should not be printed or parsed. factory ModuleLibrary.deserialize(AssetId id, String encoded) { var json = jsonDecode(encoded); return ModuleLibrary._(id, isEntryPoint: json['isEntrypoint'] as bool, deps: _deserializeAssetIds(json['deps'] as Iterable), parts: _deserializeAssetIds(json['parts'] as Iterable), sdkDeps: Set.of((json['sdkDeps'] as Iterable).cast<String>()), conditionalDeps: (json['conditionalDeps'] as Iterable).map((conditions) { return Map.of((conditions as Map<String, dynamic>) .map((k, v) => MapEntry(k, AssetId.parse(v as String)))); }).toList(), hasMain: json['hasMain'] as bool); } String serialize() => jsonEncode({ 'isEntrypoint': isEntryPoint, 'deps': _deps.map((id) => id.toString()).toList(), 'parts': parts.map((id) => id.toString()).toList(), 'conditionalDeps': conditionalDeps .map((conditions) => conditions.map((k, v) => MapEntry(k, v.toString()))) .toList(), 'sdkDeps': sdkDeps.toList(), 'hasMain': hasMain, }); List<AssetId> depsForPlatform(DartPlatform platform) { return _deps.followedBy(conditionalDeps.map((conditions) { var selectedImport = conditions[r'$default']; assert(selectedImport != null); for (var condition in conditions.keys) { if (condition == r'$default') continue; if (!condition.startsWith('dart.library.')) { throw UnsupportedError( '$condition not supported for config specific imports. Only the ' 'dart.library.<name> constants are supported.'); } var library = condition.substring('dart.library.'.length); if (platform.supportsLibrary(library)) { selectedImport = conditions[condition]; break; } } return selectedImport; })).toList(); } } Set<AssetId> _deserializeAssetIds(Iterable serlialized) => Set.from(serlialized.map((decoded) => AssetId.parse(decoded as String))); bool _isPart(CompilationUnit dart) => dart.directives.any((directive) => directive is PartOfDirective); /// Allows two or fewer arguments to `main` so that entrypoints intended for /// use with `spawnUri` get counted. // // TODO: This misses the case where a Dart file doesn't contain main(), // but has a part that does, or it exports a `main` from another library. bool _hasMainMethod(CompilationUnit dart) => dart.declarations.any((node) => node is FunctionDeclaration && node.name.name == 'main' && node.functionExpression.parameters.parameters.length <= 2);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/errors.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'; // ignore: deprecated_member_use import 'package:analyzer/analyzer.dart'; import 'package:build/build.dart'; import 'module_library.dart'; import 'module_library_builder.dart'; import 'modules.dart'; /// An [Exception] that is thrown when a worker returns an error. abstract class _WorkerException implements Exception { final AssetId failedAsset; final String error; /// A message to prepend to [toString] output. String get message; _WorkerException(this.failedAsset, this.error); @override String toString() => '$message:$failedAsset\n\nResponse:$error\n'; } /// An [Exception] that is thrown when the analyzer fails to create a summary. class AnalyzerSummaryException extends _WorkerException { @override final String message = 'Error creating summary for module'; AnalyzerSummaryException(AssetId summaryId, String error) : super(summaryId, error); } /// An [Exception] that is thrown when the common frontend fails to create a /// kernel summary. class KernelException extends _WorkerException { @override final String message = 'Error creating kernel summary for module'; KernelException(AssetId summaryId, String error) : super(summaryId, error); } /// An [Exception] that is thrown when there are some missing modules. class MissingModulesException implements Exception { final String message; @override String toString() => message; MissingModulesException._(this.message); static Future<MissingModulesException> create(Set<AssetId> missingSources, Iterable<Module> transitiveModules, AssetReader reader) async { var buffer = StringBuffer(''' Unable to find modules for some sources, this is usually the result of either a bad import, a missing dependency in a package (or possibly a dev_dependency needs to move to a real dependency), or a build failure (if importing a generated file). Please check the following imports:\n '''); var checkedSourceDependencies = <AssetId, Set<AssetId>>{}; for (var module in transitiveModules) { var missingIds = module.directDependencies.intersection(missingSources); for (var missingId in missingIds) { var checkedAlready = checkedSourceDependencies.putIfAbsent(missingId, () => <AssetId>{}); for (var sourceId in module.sources) { if (checkedAlready.contains(sourceId)) { continue; } checkedAlready.add(sourceId); var message = await _missingImportMessage(sourceId, missingId, reader); if (message != null) buffer.writeln(message); } } } return MissingModulesException._(buffer.toString()); } } /// Checks if [sourceId] directly imports [missingId], and returns an error /// message if so. Future<String> _missingImportMessage( AssetId sourceId, AssetId missingId, AssetReader reader) async { var contents = await reader.readAsString(sourceId); // ignore: deprecated_member_use var parsed = parseDirectives(contents, suppressErrors: true); var import = parsed.directives.whereType<UriBasedDirective>().firstWhere((directive) { var uriString = directive.uri.stringValue; if (uriString.startsWith('dart:')) return false; var id = AssetId.resolve(uriString, from: sourceId); return id == missingId; }, orElse: () => null); if (import == null) return null; var lineInfo = parsed.lineInfo.getLocation(import.offset); return '`$import` from $sourceId at $lineInfo'; } /// An [Exception] that is thrown when there are some unsupported modules. class UnsupportedModules implements Exception { final Set<Module> unsupportedModules; UnsupportedModules(this.unsupportedModules); Stream<ModuleLibrary> exactLibraries(AssetReader reader) async* { for (var module in unsupportedModules) { for (var source in module.sources) { var libraryId = source.changeExtension(moduleLibraryExtension); ModuleLibrary library; if (await reader.canRead(libraryId)) { library = ModuleLibrary.deserialize( libraryId, await reader.readAsString(libraryId)); } else { // A missing .module.library file indicates a part file, which can't // have import statements, so we just skip them. continue; } if (library.sdkDeps .any((lib) => !module.platform.supportsLibrary(lib))) { yield library; } } } } @override String toString() => 'Some modules contained libraries that were incompatible ' 'with the current platform.'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/kernel_builder.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:collection'; import 'dart:convert'; import 'dart:io'; import 'package:bazel_worker/bazel_worker.dart'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'package:graphs/graphs.dart' show crawlAsync; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; import 'common.dart'; import 'errors.dart'; import 'module_builder.dart'; import 'module_cache.dart'; import 'modules.dart'; import 'platform.dart'; import 'scratch_space.dart'; import 'workers.dart'; const multiRootScheme = 'org-dartlang-app'; /// A builder which can output kernel files for a given sdk. /// /// This creates kernel files based on [moduleExtension] files, which are what /// determine the module structure of an application. class KernelBuilder implements Builder { @override final Map<String, List<String>> buildExtensions; final bool useIncrementalCompiler; final bool trackUnusedInputs; final String outputExtension; final DartPlatform platform; /// Whether this should create summary kernel files or full kernel files. /// /// Summary files only contain the "outline" of the module - you can think of /// this as everything but the method bodies. final bool summaryOnly; /// The sdk kernel file for the current platform. final String sdkKernelPath; /// The root directory of the platform's dart SDK. /// /// If not provided, defaults to the directory of /// [Platform.resolvedExecutable]. /// /// On flutter this is the path to the root of the flutter_patched_sdk /// directory, which contains the platform kernel files. final String platformSdk; /// The absolute path to the libraries file for the current platform. /// /// If not provided, defaults to "lib/libraries.json" in the sdk directory. final String librariesPath; /// The `--target` argument passed to the kernel worker. /// /// Optional. When omitted the [platform] name is used. final String kernelTargetName; /// Experiments to pass to kernel (as --enable-experiment=<experiment> args). final Iterable<String> experiments; KernelBuilder( {@required this.platform, @required this.summaryOnly, @required this.sdkKernelPath, @required this.outputExtension, String librariesPath, bool useIncrementalCompiler, bool trackUnusedInputs, String platformSdk, String kernelTargetName, Iterable<String> experiments}) : platformSdk = platformSdk ?? sdkDir, kernelTargetName = kernelTargetName ?? platform.name, librariesPath = librariesPath ?? p.join(platformSdk ?? sdkDir, 'lib', 'libraries.json'), useIncrementalCompiler = useIncrementalCompiler ?? false, trackUnusedInputs = trackUnusedInputs ?? false, buildExtensions = { moduleExtension(platform): [outputExtension] }, experiments = experiments ?? []; @override Future build(BuildStep buildStep) async { var module = Module.fromJson( json.decode(await buildStep.readAsString(buildStep.inputId)) as Map<String, dynamic>); // Entrypoints always have a `.module` file for ease of looking them up, // but they might not be the primary source. if (module.primarySource.changeExtension(moduleExtension(platform)) != buildStep.inputId) { return; } try { await _createKernel( module: module, buildStep: buildStep, summaryOnly: summaryOnly, outputExtension: outputExtension, targetName: kernelTargetName, dartSdkDir: platformSdk, sdkKernelPath: sdkKernelPath, librariesPath: librariesPath, useIncrementalCompiler: useIncrementalCompiler, trackUnusedInputs: trackUnusedInputs, experiments: experiments); } on MissingModulesException catch (e) { log.severe(e.toString()); } on KernelException catch (e, s) { log.severe( 'Error creating ' '${module.primarySource.changeExtension(outputExtension)}', e, s); } } } /// Creates a kernel file for [module]. Future<void> _createKernel( {@required Module module, @required BuildStep buildStep, @required bool summaryOnly, @required String outputExtension, @required String targetName, @required String dartSdkDir, @required String sdkKernelPath, @required String librariesPath, @required bool useIncrementalCompiler, @required bool trackUnusedInputs, @required Iterable<String> experiments}) async { var request = WorkRequest(); var scratchSpace = await buildStep.fetchResource(scratchSpaceResource); var outputId = module.primarySource.changeExtension(outputExtension); var outputFile = scratchSpace.fileFor(outputId); File packagesFile; var kernelDeps = <AssetId>[]; // Maps the inputs paths we provide to the kernel worker to asset ids, // if `trackUnusedInputs` is `true`. Map<String, AssetId> kernelInputPathToId; // If `trackUnusedInputs` is `true`, this is the file we will use to // communicate the used inputs with the kernel worker. File usedInputsFile; await buildStep.trackStage('CollectDeps', () async { var sourceDeps = <AssetId>[]; await _findModuleDeps( module, kernelDeps, sourceDeps, buildStep, outputExtension); var allAssetIds = <AssetId>{ ...module.sources, ...kernelDeps, ...sourceDeps, }; await scratchSpace.ensureAssets(allAssetIds, buildStep); packagesFile = await createPackagesFile(allAssetIds); if (trackUnusedInputs) { usedInputsFile = await File(p.join( (await Directory.systemTemp.createTemp('kernel_builder_')).path, 'used_inputs.txt')) .create(); kernelInputPathToId = {}; } await _addRequestArguments( request, module, kernelDeps, targetName, dartSdkDir, sdkKernelPath, librariesPath, outputFile, packagesFile, summaryOnly, useIncrementalCompiler, buildStep, experiments, usedInputsFile: usedInputsFile, kernelInputPathToId: kernelInputPathToId); }); // We need to make sure and clean up the temp dir, even if we fail to compile. try { var frontendWorker = await buildStep.fetchResource(frontendDriverResource); var response = await frontendWorker.doWork(request, trackWork: (response) => buildStep .trackStage('Kernel Generate', () => response, isExternal: true)); if (response.exitCode != EXIT_CODE_OK || !await outputFile.exists()) { throw KernelException( outputId, '${request.arguments.join(' ')}\n${response.output}'); } if (response.output?.isEmpty == false) { log.info(response.output); } // Copy the output back using the buildStep. await scratchSpace.copyOutput(outputId, buildStep, requireContent: true); // Note that we only want to do this on success, we can't trust the unused // inputs if there is a failure. if (usedInputsFile != null) { await reportUnusedKernelInputs( usedInputsFile, kernelDeps, kernelInputPathToId, buildStep); } } finally { await packagesFile.parent.delete(recursive: true); await usedInputsFile?.parent?.delete(recursive: true); } } /// Reports any unused kernel inputs based on the [usedInputsFile] we get /// back from the kernel/ddk workers. /// /// This file logs paths as they were given in the original [WorkRequest], /// so [inputPathToId] is used to map those paths back to the kernel asset ids. /// /// This function will not report any unused dependencies if: /// /// - It isn't able to match all reported used dependencies to an asset id (it /// would be unsafe to do so in that case). /// - No used dependencies are reported (it is assumed something went wrong /// or there were zero deps to begin with). Future<void> reportUnusedKernelInputs( File usedInputsFile, Iterable<AssetId> transitiveKernelDeps, Map<String, AssetId> inputPathToId, BuildStep buildStep) async { var usedPaths = await usedInputsFile.readAsLines(); if (usedPaths.isEmpty || usedPaths.first == '') return; String firstMissingInputPath; var usedIds = usedPaths.map((usedPath) { var id = inputPathToId[usedPath]; if (id == null) firstMissingInputPath ??= usedPath; return id; }).toSet(); if (firstMissingInputPath != null) { log.warning('Error reporting unused kernel deps, unable to map path: ' '`$firstMissingInputPath` back to an asset id.\n\nPlease file an issue ' 'at https://github.com/dart-lang/build/issues/new.'); return; } buildStep.reportUnusedAssets( transitiveKernelDeps.where((id) => !usedIds.contains(id))); } /// Finds the transitive dependencies of [root] and categorizes them as /// [kernelDeps] or [sourceDeps]. /// /// A module will have it's kernel file in [kernelDeps] if it and all of it's /// transitive dependencies have readable kernel files. If any module has no /// readable kernel file then it, and all of it's dependents will be categorized /// as [sourceDeps] which will have all of their [Module.sources]. Future<void> _findModuleDeps( Module root, List<AssetId> kernelDeps, List<AssetId> sourceDeps, BuildStep buildStep, String outputExtension) async { final resolvedModules = await _resolveTransitiveModules(root, buildStep); final sourceOnly = await _parentsOfMissingKernelFiles( resolvedModules, buildStep, outputExtension); for (final module in resolvedModules) { if (sourceOnly.contains(module.primarySource)) { sourceDeps.addAll(module.sources); } else { kernelDeps.add(module.primarySource.changeExtension(outputExtension)); } } } /// The transitive dependencies of [root], not including [root] itself. Future<List<Module>> _resolveTransitiveModules( Module root, BuildStep buildStep) async { var missing = <AssetId>{}; var modules = await crawlAsync<AssetId, Module>( [root.primarySource], (id) => buildStep.fetchResource(moduleCache).then((c) async { var moduleId = id.changeExtension(moduleExtension(root.platform)); var module = await c.find(moduleId, buildStep); if (module == null) { missing.add(moduleId); } else if (module.isMissing) { missing.add(module.primarySource); } return module; }), (id, module) => module.directDependencies) .skip(1) // Skip the root. .toList(); if (missing.isNotEmpty) { throw await MissingModulesException.create( missing, [...modules, root], buildStep); } return modules; } /// Finds the primary source of all transitive parents of any module which does /// not have a readable kernel file. /// /// Inverts the direction of the graph and then crawls to all reachables nodes /// from the modules which do not have a readable kernel file Future<Set<AssetId>> _parentsOfMissingKernelFiles( List<Module> modules, BuildStep buildStep, String outputExtension) async { final sourceOnly = <AssetId>{}; final parents = <AssetId, Set<AssetId>>{}; for (final module in modules) { for (final dep in module.directDependencies) { parents.putIfAbsent(dep, () => <AssetId>{}).add(module.primarySource); } if (!await buildStep .canRead(module.primarySource.changeExtension(outputExtension))) { sourceOnly.add(module.primarySource); } } final toCrawl = Queue.of(sourceOnly); while (toCrawl.isNotEmpty) { final current = toCrawl.removeFirst(); if (!parents.containsKey(current)) continue; for (final next in parents[current]) { if (!sourceOnly.add(next)) { toCrawl.add(next); } } } return sourceOnly; } /// Fills in all the required arguments for [request] in order to compile the /// kernel file for [module]. Future<void> _addRequestArguments( WorkRequest request, Module module, Iterable<AssetId> transitiveKernelDeps, String targetName, String sdkDir, String sdkKernelPath, String librariesPath, File outputFile, File packagesFile, bool summaryOnly, bool useIncrementalCompiler, AssetReader reader, Iterable<String> experiments, { File usedInputsFile, Map<String, AssetId> kernelInputPathToId, }) async { // Add all kernel outlines as summary inputs, with digests. var inputs = await Future.wait(transitiveKernelDeps.map((id) async { var relativePath = p.url.relative(scratchSpace.fileFor(id).uri.path, from: scratchSpace.tempDir.uri.path); var path = '$multiRootScheme:///$relativePath'; if (kernelInputPathToId != null) { kernelInputPathToId[path] = id; } return Input() ..path = path ..digest = (await reader.digest(id)).bytes; })); request.arguments.addAll([ '--dart-sdk-summary=${Uri.file(p.join(sdkDir, sdkKernelPath))}', '--output=${outputFile.path}', '--packages-file=${packagesFile.uri}', '--multi-root-scheme=$multiRootScheme', '--exclude-non-sources', summaryOnly ? '--summary-only' : '--no-summary-only', '--target=$targetName', '--libraries-file=${p.toUri(librariesPath)}', if (useIncrementalCompiler) ...[ '--reuse-compiler-result', '--use-incremental-compiler', ], if (usedInputsFile != null) '--used-inputs=${usedInputsFile.uri.toFilePath()}', for (var input in inputs) '--input-${summaryOnly ? 'summary' : 'linked'}=${input.path}', for (var experiment in experiments) '--enable-experiment=$experiment', for (var source in module.sources) _sourceArg(source), ]); request.inputs.addAll([ ...inputs, Input() ..path = '${Uri.file(p.join(sdkDir, sdkKernelPath))}' // Sdk updates fully invalidate the build anyways. ..digest = md5.convert(utf8.encode(targetName)).bytes, ]); } String _sourceArg(AssetId id) { var uri = id.path.startsWith('lib') ? canonicalUriFor(id) : '$multiRootScheme:///${id.path}'; return '--source=$uri'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_modules/src/modules.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:collection'; import 'package:build/build.dart'; import 'package:collection/collection.dart' show UnmodifiableSetView; import 'package:graphs/graphs.dart'; import 'package:json_annotation/json_annotation.dart'; import 'errors.dart'; import 'module_builder.dart'; import 'module_cache.dart'; import 'platform.dart'; part 'modules.g.dart'; /// A collection of Dart libraries in a strongly connected component of the /// import graph. /// /// Modules track their sources and the other modules they depend on. /// modules they depend on. /// Modules can span pub package boundaries when there are import cycles across /// packages. @JsonSerializable() @_AssetIdConverter() @_DartPlatformConverter() class Module { /// Merge the sources and dependencies from [modules] into a single module. /// /// All modules must have the same [platform]. /// [primarySource] will be the earliest value from the combined [sources] if /// they were sorted. /// [isMissing] will be true if any input module is missing. /// [isSupported] will be true if all input modules are supported. /// [directDependencies] will be merged for all modules, but if any module /// depended on a source from any other they will be filtered out. static Module merge(List<Module> modules) { assert(modules.isNotEmpty); if (modules.length == 1) return modules.single; assert(modules.every((m) => m.platform == modules.first.platform)); final allSources = HashSet.of(modules.expand((m) => m.sources)); final allDependencies = HashSet.of(modules.expand((m) => m.directDependencies)) ..removeAll(allSources); final primarySource = allSources.reduce((a, b) => a.compareTo(b) < 0 ? a : b); final isMissing = modules.any((m) => m.isMissing); final isSupported = modules.every((m) => m.isSupported); return Module(primarySource, allSources, allDependencies, modules.first.platform, isSupported, isMissing: isMissing); } /// The library which will be used to reference any library in [sources]. /// /// The assets which are built once per module, such as DDC compiled output or /// Analyzer summaries, will be named after the primary source and will /// encompass everything in [sources]. @JsonKey(name: 'p', nullable: false) final AssetId primarySource; /// The libraries in the strongly connected import cycle with [primarySource]. /// /// In most cases without cyclic imports this will contain only the primary /// source. For libraries with an import cycle all of the libraries in the /// cycle will be contained in `sources`. For example: /// /// ```dart /// library foo; /// /// import 'bar.dart'; /// ``` /// /// ```dart /// library bar; /// /// import 'foo.dart'; /// ``` /// /// Libraries `foo` and `bar` form an import cycle so they would be grouped in /// the same module. Every Dart library will only be contained in a single /// [Module]. @JsonKey(name: 's', nullable: false, toJson: _toJsonAssetIds) final Set<AssetId> sources; /// The [primarySource]s of the [Module]s which contain any library imported /// from any of the [sources] in this module. @JsonKey(name: 'd', nullable: false, toJson: _toJsonAssetIds) final Set<AssetId> directDependencies; /// Missing modules are created if a module depends on another non-existent /// module. /// /// We want to report these errors lazily to allow for builds to succeed if it /// won't actually impact any apps negatively. @JsonKey(name: 'm', nullable: true, defaultValue: false) final bool isMissing; /// Whether or not this module is supported for [platform]. /// /// Note that this only indicates support for the [sources] within this /// module, and not its transitive (or direct) dependencies. /// /// Compilers can use this to either silently skip compilation of this module /// or throw early errors or warnings. /// /// Modules are allowed to exist even if they aren't supported, which can help /// with discovering root causes of incompatibility. @JsonKey(name: 'is', nullable: false) final bool isSupported; @JsonKey(name: 'pf', nullable: false) final DartPlatform platform; Module(this.primarySource, Iterable<AssetId> sources, Iterable<AssetId> directDependencies, this.platform, this.isSupported, {bool isMissing}) : sources = UnmodifiableSetView(HashSet.of(sources)), directDependencies = UnmodifiableSetView(HashSet.of(directDependencies)), isMissing = isMissing ?? false; /// Generated factory constructor. factory Module.fromJson(Map<String, dynamic> json) => _$ModuleFromJson(json); Map<String, dynamic> toJson() => _$ModuleToJson(this); /// Returns all [Module]s in the transitive dependencies of this module in /// reverse dependency order. /// /// Throws a [MissingModulesException] if there are any missing modules. This /// typically means that somebody is trying to import a non-existing file. /// /// If [throwIfUnsupported] is `true`, then an [UnsupportedModules] /// will be thrown if there are any modules that are not supported. Future<List<Module>> computeTransitiveDependencies(BuildStep buildStep, {bool throwIfUnsupported = false, @deprecated Set<String> skipPlatformCheckPackages = const {}}) async { throwIfUnsupported ??= false; skipPlatformCheckPackages ??= const {}; final modules = await buildStep.fetchResource(moduleCache); var transitiveDeps = <AssetId, Module>{}; var modulesToCrawl = {primarySource}; var missingModuleSources = <AssetId>{}; var unsupportedModules = <Module>{}; while (modulesToCrawl.isNotEmpty) { var next = modulesToCrawl.last; modulesToCrawl.remove(next); if (transitiveDeps.containsKey(next)) continue; var nextModuleId = next.changeExtension(moduleExtension(platform)); var module = await modules.find(nextModuleId, buildStep); if (module == null || module.isMissing) { missingModuleSources.add(next); continue; } if (throwIfUnsupported && !module.isSupported && !skipPlatformCheckPackages.contains(module.primarySource.package)) { unsupportedModules.add(module); } // Don't include the root module in the transitive deps. if (next != primarySource) transitiveDeps[next] = module; modulesToCrawl.addAll(module.directDependencies); } if (missingModuleSources.isNotEmpty) { throw await MissingModulesException.create(missingModuleSources, transitiveDeps.values.toList()..add(this), buildStep); } if (throwIfUnsupported && unsupportedModules.isNotEmpty) { throw UnsupportedModules(unsupportedModules); } var orderedModules = stronglyConnectedComponents<Module>( transitiveDeps.values, (m) => m.directDependencies.map((s) => transitiveDeps[s]), equals: (a, b) => a.primarySource == b.primarySource, hashCode: (m) => m.primarySource.hashCode); return orderedModules.map((c) => c.single).toList(); } } class _AssetIdConverter implements JsonConverter<AssetId, List> { const _AssetIdConverter(); @override AssetId fromJson(List json) => AssetId.deserialize(json); @override List toJson(AssetId object) => object.serialize() as List; } class _DartPlatformConverter implements JsonConverter<DartPlatform, String> { const _DartPlatformConverter(); @override DartPlatform fromJson(String json) => DartPlatform.byName(json); @override String toJson(DartPlatform object) => object.name; } /// Ensure sets of asset IDs are sorted before writing them for a consistent /// output. List<List> _toJsonAssetIds(Set<AssetId> ids) => (ids.toList()..sort()).map((i) => i.serialize() as List).toList();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/js/js.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. /// Annotations to mark interfaces to JavaScript. library js; export 'dart:js' show allowInterop, allowInteropCaptureThis; /// An annotation that indicates a library, class, or member is implemented /// directly in JavaScript. /// /// All external members of a class or library with this annotation implicitly /// have it as well. /// /// Specifying [name] customizes the JavaScript name to use. By default the /// dart name is used. It is not valid to specify a custom [name] for class /// instance members. class JS { final String name; const JS([this.name]); } class _Anonymous { const _Anonymous(); } /// An annotation that indicates a [JS] annotated class is structural and does /// not have a known JavaScript prototype. /// /// A class marked with [anonymous] must have an unnamed factory constructor /// with no positional arguments, only named arguments. Invoking the constructor /// desugars to creating a JavaScript object literal with name-value pairs /// corresponding to the parameter names and values. const _Anonymous anonymous = _Anonymous();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/js/js_util.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. /// Utilities for interoperating with JavaScript. library js_util; export 'dart:js_util';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/js
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/js/src/varargs.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. /// Declarations for variable arguments support /// (rest params and spread operator). /// /// These are currently *not* supported by dart2js or Dartium. library js.varargs; class _Rest { const _Rest(); } /// Annotation to tag ES6 rest parameters (https://goo.gl/r0bJ1K). /// /// This is *not* supported by dart2js or Dartium (yet). /// /// This is meant to be used by the Dart Dev Compiler /// when compiling helper functions of its runtime to ES6. /// /// The following function: /// /// foo(a, b, @rest others) { ... } /// /// Will be compiled to ES6 code like the following: /// /// function foo(a, b, ...others) { ... } /// /// Which is roughly equivalent to the following ES5 code: /// /// function foo(a, b/*, ...others*/) { /// var others = [].splice.call(arguments, 2); /// ... /// } /// const _Rest rest = _Rest(); /// Intrinsic function that maps to the ES6 spread operator /// (https://goo.gl/NedHKr). /// /// This is *not* supported by dart2js or Dartium (yet), /// and *cannot* be called at runtime. /// /// This is meant to be used by the Dart Dev Compiler when /// compiling its runtime to ES6. /// /// The following expression: /// /// foo(a, b, spread(others)) /// /// Will be compiled to ES6 code like the following: /// /// foo(a, b, ...others) /// /// Which is roughly equivalent to the following ES5 code: /// /// foo.apply(null, [a, b].concat(others)) /// dynamic spread(args) { throw StateError('The spread function cannot be called, ' 'it should be compiled away.'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/package_resolver.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/package_resolver.dart'; export 'src/sync_package_resolver.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/package_root_resolver.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:path/path.dart' as p; import 'async_package_resolver.dart'; import 'package_resolver.dart'; import 'sync_package_resolver.dart'; import 'utils.dart'; /// A package resolution strategy based on a package root URI. class PackageRootResolver implements SyncPackageResolver { final packageConfigMap = null; final packageConfigUri = null; final Uri packageRoot; PackageResolver get asAsync => new AsyncPackageResolver(this); String get processArgument => "--package-root=$packageRoot"; PackageRootResolver(packageRoot) : packageRoot = ensureTrailingSlash(asUri(packageRoot, "packageRoot")); Uri resolveUri(packageUri) { packageUri = asPackageUri(packageUri, "packageUri"); // Following [Isolate.resolvePackageUri], "package:foo" resolves to null. if (packageUri.pathSegments.length == 1) return null; return packageRoot.resolve(packageUri.path); } Uri urlFor(String package, [String path]) { var result = packageRoot.resolve("$package/"); return path == null ? result : result.resolve(path); } Uri packageUriFor(url) { var packageRootString = packageRoot.toString(); url = asUri(url, "url").toString(); if (!p.url.isWithin(packageRootString, url)) return null; var relative = p.url.relative(url, from: packageRootString); if (!relative.contains("/")) relative += "/"; return Uri.parse("package:$relative"); } String packagePath(String package) => packagePathForRoot(package, packageRoot); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils_isolate_stub.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. Future<Uri> resolvePackageUri(Uri packageUri) => throw UnsupportedError('May not use a package URI');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/sync_package_resolver.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:http/http.dart' as http; import 'no_package_resolver.dart'; import 'package_config_resolver.dart'; import 'package_resolver.dart'; import 'package_root_resolver.dart'; import 'utils.dart'; /// A class that defines how to resolve `package:` URIs. /// /// This includes the information necessary to resolve `package:` URIs using /// either a package config or a package root. It can be used both as a standard /// cross-package representation of the user's configuration, and as a means of /// concretely locating packages and the assets they contain. /// /// Unlike [PackageResolver], all members on this are synchronous, which may /// require that more data be loaded up front. This is useful when primarily /// dealing with user-created package resolution strategies, whereas /// [PackageInfo] is usually preferable when the current Isolate's package /// resolution logic may be used. /// /// This class should not be implemented by user code. abstract class SyncPackageResolver { /// The map contained in the parsed package config. /// /// This maps package names to the base URIs for those packages. These are /// already resolved relative to [packageConfigUri], so if they're relative /// they should be considered relative to [Uri.base]. They're normalized to /// ensure that all URLs end with a trailing slash. /// /// [urlFor] should generally be used rather than looking up package URLs in /// this map, to ensure that code works with a package root as well as a /// package config. /// /// Returns `null` when using a [packageRoot] for resolution, or when no /// package resolution is being used. Map<String, Uri> get packageConfigMap; /// The URI for the package config. /// /// This is the URI from which [packageConfigMap] was parsed, if that's /// available. Otherwise, it's a `data:` URI containing a serialized /// representation of [packageConfigMap]. This `data:` URI should be accepted /// by all Dart tools. /// /// Note that if this is a `data:` URI, it's likely not safe to pass as a /// parameter to a Dart process due to length limits. /// /// Returns `null` when using a [packageRoot] for resolution, or when no /// package resolution is being used. Uri get packageConfigUri; /// The base URL for resolving `package:` URLs. /// /// This is normalized so that it always ends with a trailing slash. /// /// Returns `null` when using a [packageConfigMap] for resolution, or when no /// package resolution is being used. Uri get packageRoot; /// Returns a wrapper for [this] that implements [PackageResolver]. PackageResolver get asAsync; /// Returns the argument to pass to a subprocess to get it to use this package /// resolution strategy when resolving `package:` URIs. /// /// This uses the `--package-root` or `--package` flags, which are the /// convention supported by the Dart VM and dart2js. /// /// Note that if [packageConfigUri] is a `data:` URI, it may be too large to /// pass on the command line. /// /// Returns `null` if no package resolution is in use. String get processArgument; /// Returns a package resolution strategy describing how the current isolate /// resolves `package:` URIs. /// /// This may throw exceptions if loading or parsing the isolate's package map /// fails. static final Future<SyncPackageResolver> current = PackageResolver.current.asSync; /// Returns a package resolution strategy that is unable to resolve any /// `package:` URIs. static final SyncPackageResolver none = new NoPackageResolver(); /// Loads a package config file from [uri] and returns its package resolution /// strategy. /// /// This supports `file:`, `http:`, `data:` and `package:` URIs. It throws an /// [UnsupportedError] for any other schemes. If [client] is passed and an /// HTTP request is needed, it's used to make that request; otherwise, a /// default client is used. /// /// [uri] may be a [String] or a [Uri]. static Future<SyncPackageResolver> loadConfig(uri, {http.Client client}) async { uri = asUri(uri, "uri"); return new SyncPackageResolver.config( await loadConfigMap(uri, client: client), uri: uri); } /// Returns the package resolution strategy for the given [packageConfigMap]. /// /// If passed, [uri] specifies the URI from which [packageConfigMap] was /// loaded. It may be a [String] or a [Uri]. /// /// Whether or not [uri] is passed, [packageConfigMap] is expected to be /// fully-resolved. That is, any relative URIs in the original package config /// source should be resolved relative to its location. factory SyncPackageResolver.config(Map<String, Uri> packageConfigMap, {uri}) = PackageConfigResolver; /// Returns the package resolution strategy for the given [packageRoot], which /// may be a [String] or a [Uri]. factory SyncPackageResolver.root(packageRoot) = PackageRootResolver; /// Resolves [packageUri] according to this package resolution strategy. /// /// [packageUri] may be a [String] or a [Uri]. This throws a [FormatException] /// if [packageUri] isn't a `package:` URI or doesn't have at least one path /// segment. /// /// If [packageUri] refers to a package that's not in the package spec, this /// returns `null`. Uri resolveUri(packageUri); /// Returns the resolved URL for [package] and [path]. /// /// This is equivalent to `resolveUri("package:$package/")` or /// `resolveUri("package:$package/$path")`, depending on whether [path] was /// passed. /// /// If [package] refers to a package that's not in the package spec, this /// returns `null`. Uri urlFor(String package, [String path]); /// Returns the `package:` URI for [url]. /// /// If [url] can't be referred to using a `package:` URI, returns `null`. /// /// [url] may be a [String] or a [Uri]. Uri packageUriFor(url); /// Returns the path on the local filesystem to the root of [package], or /// `null` if the root cannot be found. /// /// **Note**: this assumes a pub-style package layout. In particular: /// /// * If a package root is being used, this assumes that it contains symlinks /// to packages' lib/ directories. /// /// * If a package config is being used, this assumes that each entry points /// to a package's lib/ directory. /// /// If these assumptions are broken, this may return `null` or it may return /// an invalid result. /// /// Returns `null` if the package root is not a `file:` URI, or if the package /// config entry for [package] is not a `file:` URI. String packagePath(String package); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils_io.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:path/path.dart' as p; Future<String> readFileAsString(Uri uri) { var path = uri.toFilePath(windows: Platform.isWindows); return new File(path).readAsString(); } String packagePathForRoot(String package, Uri root) { if (root.scheme != 'file') return null; var libLink = p.join(p.fromUri(root), package); if (!new Link(libLink).existsSync()) return null; return p.dirname(new Link(libLink).resolveSymbolicLinksSync()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/package_resolver.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:http/http.dart' as http; import 'package_config_resolver.dart'; import 'package_root_resolver.dart'; import 'sync_package_resolver.dart'; // ignore: uri_does_not_exist import 'current_isolate_resolver_stub.dart' // ignore: uri_does_not_exist if (dart.library.isolate) 'current_isolate_resolver.dart' as isolate; /// A class that defines how to resolve `package:` URIs. /// /// This includes the information necessary to resolve `package:` URIs using /// either a package config or a package root. It can be used both as a standard /// cross-package representation of the user's configuration, and as a means of /// concretely locating packages and the assets they contain. /// /// Unlike [SyncPackageResolver], this does not provide synchronous APIs. This /// is necessary when dealing with the current Isolate's package resolution /// strategy. /// /// This class should not be implemented by user code. abstract class PackageResolver { /// The map contained in the parsed package config. /// /// This maps package names to the base URIs for those packages. These are /// already resolved relative to [packageConfigUri], so if they're relative /// they should be considered relative to [Uri.base]. /// /// [urlFor] should generally be used rather than looking up package URLs in /// this map, to ensure that code works with a package root as well as a /// package config. /// /// Note that for some implementations, loading the map may require IO /// operations that could fail. /// /// Completes to `null` when using a [packageRoot] for resolution, or when no /// package resolution is being used. Future<Map<String, Uri>> get packageConfigMap; /// The URI for the package config. /// /// This is the URI from which [packageConfigMap] was parsed, if that's /// available. Otherwise, it's a `data:` URI containing a serialized /// representation of [packageConfigMap]. This `data:` URI should be accepted /// by all Dart tools. /// /// Note that if this is a `data:` URI, it may not be safe to pass as a /// parameter to a Dart process due to length limits. /// /// Completes to `null` when using a [packageRoot] for resolution, or when no /// package resolution is being used. Future<Uri> get packageConfigUri; /// The base URL for resolving `package:` URLs. /// /// Completes to `null` when using a [packageConfigMap] for resolution, or /// when no package resolution is being used. Future<Uri> get packageRoot; /// Fetches the package resolution for [this] and returns an object that /// provides synchronous access. /// /// This may throw exceptions if loading or parsing the package map fails. Future<SyncPackageResolver> get asSync; /// Returns the argument to pass to a subprocess to get it to use this package /// resolution strategy when resolving `package:` URIs. /// /// This uses the `--package-root` or `--package` flags, which are the /// conventions supported by the Dart VM and dart2js. /// /// Note that if [packageConfigUri] is a `data:` URI, it may be too large to /// pass on the command line. /// /// Returns `null` if no package resolution is in use. Future<String> get processArgument; /// Returns package resolution strategy describing how the current isolate /// resolves `package:` URIs. static final PackageResolver current = isolate.currentIsolateResolver(); /// Returns a package resolution strategy that is unable to resolve any /// `package:` URIs. static final PackageResolver none = SyncPackageResolver.none.asAsync; /// Loads a package config file from [uri] and returns its package resolution /// strategy. /// /// This supports `file:`, `http:`, `data:` and `package:` URIs. It throws an /// [UnsupportedError] for any other schemes. If [client] is passed and an /// HTTP request is needed, it's used to make that request; otherwise, a /// default client is used. /// /// [uri] may be a [String] or a [Uri]. static Future<PackageResolver> loadConfig(uri, {http.Client client}) async { var resolver = await SyncPackageResolver.loadConfig(uri, client: client); return resolver.asAsync; } /// Returns the package resolution strategy for the given [packageConfigMap]. /// /// If passed, [uri] specifies the URI from which [packageConfigMap] was /// loaded. It may be a [String] or a [Uri]. /// /// Whether or not [uri] is passed, [packageConfigMap] is expected to be /// fully-resolved. That is, any relative URIs in the original package config /// source should be resolved relative to its location. factory PackageResolver.config(Map<String, Uri> packageConfigMap, {uri}) => new PackageConfigResolver(packageConfigMap, uri: uri).asAsync; /// Returns the package resolution strategy for the given [packageRoot], which /// may be a [String] or a [Uri]. factory PackageResolver.root(packageRoot) => new PackageRootResolver(packageRoot).asAsync; /// Resolves [packageUri] according to this package resolution strategy. /// /// [packageUri] may be a [String] or a [Uri]. This throws a [FormatException] /// if [packageUri] isn't a `package:` URI or doesn't have at least one path /// segment. /// /// If [packageUri] refers to a package that's not in the package spec, this /// returns `null`. Future<Uri> resolveUri(packageUri); /// Returns the resolved URL for [package] and [path]. /// /// This is equivalent to `resolveUri("package:$package/")` or /// `resolveUri("package:$package/$path")`, depending on whether [path] was /// passed. /// /// If [package] refers to a package that's not in the package spec, this /// returns `null`. Future<Uri> urlFor(String package, [String path]); /// Returns the `package:` URI for [uri]. /// /// If [uri] can't be referred to using a `package:` URI, returns `null`. /// /// [uri] may be a [String] or a [Uri]. Future<Uri> packageUriFor(uri); /// Returns the path on the local filesystem to the root of [package], or /// `null` if the root cannot be found. /// /// **Note**: this assumes a pub-style package layout. In particular: /// /// * If a package root is being used, this assumes that it contains symlinks /// to packages' lib/ directories. /// /// * If a package config is being used, this assumes that each entry points /// to a package's lib/ directory. /// /// Returns `null` if the package root is not a `file:` URI, or if the package /// config entry for [package] is not a `file:` URI. Future<String> packagePath(String package); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/package_config_resolver.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 'package:collection/collection.dart'; import 'package:package_config/packages_file.dart' as packages_file; import 'package:path/path.dart' as p; import 'async_package_resolver.dart'; import 'package_resolver.dart'; import 'sync_package_resolver.dart'; import 'utils.dart'; /// A package resolution strategy based on a package config map. class PackageConfigResolver implements SyncPackageResolver { final packageRoot = null; final Map<String, Uri> packageConfigMap; Uri get packageConfigUri { if (_uri != null) return _uri; var buffer = new StringBuffer(); packages_file.write(buffer, packageConfigMap, comment: ""); _uri = new UriData.fromString(buffer.toString(), parameters: {"charset": "utf-8"}).uri; return _uri; } Uri _uri; PackageResolver get asAsync => new AsyncPackageResolver(this); String get processArgument => "--packages=$packageConfigUri"; PackageConfigResolver(Map<String, Uri> packageConfigMap, {uri}) : packageConfigMap = _normalizeMap(packageConfigMap), _uri = uri == null ? null : asUri(uri, "uri"); /// Normalizes the URIs in [map] to ensure that they all end in a trailing /// slash. static Map<String, Uri> _normalizeMap(Map<String, Uri> map) => new UnmodifiableMapView( mapMap(map, value: (_, uri) => ensureTrailingSlash(uri))); Uri resolveUri(packageUri) { var uri = asPackageUri(packageUri, "packageUri"); var baseUri = packageConfigMap[uri.pathSegments.first]; if (baseUri == null) return null; var segments = baseUri.pathSegments.toList() ..removeLast(); // Remove the trailing slash. // Following [Isolate.resolvePackageUri], "package:foo" resolves to null. if (uri.pathSegments.length == 1) return null; segments.addAll(uri.pathSegments.skip(1)); return baseUri.replace(pathSegments: segments); } Uri urlFor(String package, [String path]) { var baseUri = packageConfigMap[package]; if (baseUri == null) return null; if (path == null) return baseUri; return baseUri.resolve(path); } Uri packageUriFor(url) { url = asUri(url, "url").toString(); // Make sure isWithin works if [url] is exactly the base. var nested = p.url.join(url, "_"); for (var package in packageConfigMap.keys) { var base = packageConfigMap[package].toString(); if (!p.url.isWithin(base, nested)) continue; var relative = p.url.relative(url, from: base); if (relative == '.') relative = ''; return Uri.parse("package:$package/$relative"); } return null; } String packagePath(String package) { var lib = packageConfigMap[package]; if (lib == null) return null; if (lib.scheme != 'file') return null; return p.dirname(p.fromUri(lib)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils.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:convert'; import 'package:http/http.dart' as http; import 'package:package_config/packages_file.dart' as packages_file; // ignore: uri_does_not_exist import 'utils_io_stub.dart' // ignore: uri_does_not_exist if (dart.library.io) 'utils_io.dart' as io; // ignore: uri_does_not_exist import 'utils_isolate_stub.dart' // ignore: uri_does_not_exist if (dart.library.isolate) 'utils_isolate.dart' as isolate; /// Loads the configuration map from [uri]. /// /// This supports `http`, `file`, `data`, and `package` URIs. If [client] is /// passed and an HTTP request is needed, it's used to make that request; /// otherwise, a default client is used. Future<Map<String, Uri>> loadConfigMap(Uri uri, {http.Client client}) async { var resolved = Uri.base.resolveUri(uri); var text; if (resolved.scheme == 'http') { text = await (client == null ? http.read(resolved) : client.read(resolved)); } else if (resolved.scheme == 'file') { text = await io.readFileAsString(resolved); } else if (resolved.scheme == 'data') { text = resolved.data.contentAsString(); } else if (resolved.scheme == 'package') { return loadConfigMap(await isolate.resolvePackageUri(uri), client: client); } else { throw new UnsupportedError( 'PackageInfo.loadConfig doesn\'t support URI scheme "${uri.scheme}:".'); } return packages_file.parse(utf8.encode(text), resolved); } /// Converts [uri] to a [Uri] and verifies that it's a valid `package:` URI. /// /// Throws an [ArgumentError] if [uri] isn't a [String] or a [Uri]. [name] is /// used as the argument name in that error. /// /// Throws a [FormatException] if [uri] isn't a `package:` URI or doesn't have /// at least one path segment. Uri asPackageUri(uri, String name) { uri = asUri(uri, name); if (uri.scheme != 'package') { throw new FormatException( "Can only resolve a package: URI.", uri.toString(), 0); } else if (uri.pathSegments.isEmpty) { throw new FormatException( "Expected package name.", uri.toString(), "package:".length); } return uri; } /// Converts [uri] to a [Uri]. /// /// Throws an [ArgumentError] if [uri] isn't a [String] or a [Uri]. [name] is /// used as the argument name in that error. Uri asUri(uri, String name) { if (uri is Uri) return uri; if (uri is String) return Uri.parse(uri); throw new ArgumentError.value(uri, name, "Must be a String or a Uri."); } /// Returns a copy of [uri] with a trailing slash. /// /// If [uri] already ends in a slash, returns it as-is. Uri ensureTrailingSlash(Uri uri) { if (uri.pathSegments.isEmpty) return uri.replace(path: "/"); if (uri.pathSegments.last.isEmpty) return uri; return uri.replace(pathSegments: uri.pathSegments.toList()..add("")); } String packagePathForRoot(String package, Uri root) => io.packagePathForRoot(package, root);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/current_isolate_resolver_stub.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_resolver.dart'; PackageResolver currentIsolateResolver() => throw UnsupportedError('No current isolate support on this platform');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils_stub.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. Future<String> readFileAsString(Uri uri) => throw UnsupportedError( 'Reading files is only supported where dart:io is available.'); String packagePathForRoot(String package, Uri root) => throw UnsupportedError( 'Computing package paths from a root is only supported where dart:io is ' 'available.');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/no_package_resolver.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 'async_package_resolver.dart'; import 'package_resolver.dart'; import 'sync_package_resolver.dart'; import 'utils.dart'; /// A package resolution strategy that is unable to resolve any `package:` URIs. class NoPackageResolver implements SyncPackageResolver { Map<String, Uri> get packageConfigMap => null; Uri get packageConfigUri => null; Uri get packageRoot => null; String get processArgument => null; PackageResolver get asAsync => new AsyncPackageResolver(this); Uri resolveUri(packageUri) { // Verify that the URI is valid. asPackageUri(packageUri, "packageUri"); return null; } Uri urlFor(String package, [String path]) => null; Uri packageUriFor(url) { // Verify that the URI is a valid type. asUri(url, "url"); return null; } String packagePath(String package) => null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/current_isolate_resolver.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:isolate'; import 'package:path/path.dart' as p; import 'package_config_resolver.dart'; import 'package_resolver.dart'; import 'package_root_resolver.dart'; import 'sync_package_resolver.dart'; import 'utils.dart'; /// The package resolution strategy used by the current isolate. PackageResolver currentIsolateResolver() => _CurrentIsolateResolver(); class _CurrentIsolateResolver implements PackageResolver { Future<Map<String, Uri>> get packageConfigMap async { if (_packageConfigMap != null) return _packageConfigMap; var url = await Isolate.packageConfig; if (url == null) return null; return await loadConfigMap(url); } Map<String, Uri> _packageConfigMap; Future<Uri> get packageConfigUri => Isolate.packageConfig; // ignore: deprecated_member_use Future<Uri> get packageRoot => Isolate.packageRoot; Future<SyncPackageResolver> get asSync async { var root = await packageRoot; if (root != null) return new PackageRootResolver(root); var map = await packageConfigMap; // It's hard to imagine how there would be no package resolution strategy // for an Isolate that can load the package_resolver package, but it's easy // to handle that case so we do. if (map == null) return SyncPackageResolver.none; return new PackageConfigResolver(map, uri: await packageConfigUri); } Future<String> get processArgument async { var configUri = await packageConfigUri; if (configUri != null) return "--packages=$configUri"; var root = await packageRoot; if (root != null) return "--package-root=$root"; return null; } Future<Uri> resolveUri(packageUri) => Isolate.resolvePackageUri(asPackageUri(packageUri, "packageUri")); Future<Uri> urlFor(String package, [String path]) => Isolate.resolvePackageUri(Uri.parse("package:$package/${path ?? ''}")); Future<Uri> packageUriFor(url) async => (await asSync).packageUriFor(url); Future<String> packagePath(String package) async { var root = await packageRoot; if (root != null) return new PackageRootResolver(root).packagePath(package); return p.dirname(p.fromUri(await urlFor(package))); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/async_package_resolver.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_resolver.dart'; import 'sync_package_resolver.dart'; /// An implementation of [PackageResolver] that wraps a [SyncPackageResolver]. class AsyncPackageResolver implements PackageResolver { /// The wrapped [SyncPackageResolver]. final SyncPackageResolver _inner; AsyncPackageResolver(this._inner); Future<Map<String, Uri>> get packageConfigMap async => _inner.packageConfigMap; Future<Uri> get packageConfigUri async => _inner.packageConfigUri; Future<Uri> get packageRoot async => _inner.packageRoot; Future<SyncPackageResolver> get asSync async => _inner; Future<String> get processArgument async => _inner.processArgument; Future<Uri> resolveUri(packageUri) async => _inner.resolveUri(packageUri); Future<Uri> urlFor(String package, [String path]) async => _inner.urlFor(package, path); Future<Uri> packageUriFor(url) async => _inner.packageUriFor(url); Future<String> packagePath(String package) async => _inner.packagePath(package); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils_io_stub.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. Future<String> readFileAsString(Uri uri) => throw UnsupportedError( 'Reading files is only supported where dart:io is available.'); String packagePathForRoot(String package, Uri root) => throw UnsupportedError( 'Computing package paths from a root is only supported where dart:io is ' 'available.');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_resolver/src/utils_isolate.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:isolate'; Future<Uri> resolvePackageUri(Uri packageUri) => Isolate.resolvePackageUri(packageUri);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/package_config_types.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. /// A package configuration is a way to assign file paths to package URIs, /// and vice-versa, library package_config.package_config; export "src/package_config.dart" show PackageConfig, Package, LanguageVersion, InvalidLanguageVersion; export "src/errors.dart" show PackageConfigError;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/packages.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. @Deprecated("Use the package_config.json based API") library package_config.packages; import "src/packages_impl.dart"; /// A package resolution strategy. /// /// Allows converting a `package:` URI to a different kind of URI. /// /// May also allow listing the available packages and converting /// to a `Map<String, Uri>` that gives the base location of each available /// package. In some cases there is no way to find the available packages, /// in which case [packages] and [asMap] will throw if used. /// One such case is if the packages are resolved relative to a /// `packages/` directory available over HTTP. @Deprecated("Use the package_config.json based API") abstract class Packages { /// A [Packages] resolver containing no packages. /// /// This constant object is returned by [find] above if no /// package resolution strategy is found. static const Packages noPackages = NoPackages(); /// Resolve a package URI into a non-package URI. /// /// Translates a `package:` URI, according to the package resolution /// strategy, into a URI that can be loaded. /// By default, only `file`, `http` and `https` URIs are returned. /// Custom `Packages` objects may return other URIs. /// /// If resolution fails because a package with the requested package name /// is not available, the [notFound] function is called. /// If no `notFound` function is provided, it defaults to throwing an error. /// /// The [packageUri] must be a valid package URI. Uri resolve(Uri packageUri, {Uri notFound(Uri packageUri)}); /// Return the names of the available packages. /// /// Returns an iterable that allows iterating the names of available packages. /// /// Some `Packages` objects are unable to find the package names, /// and getting `packages` from such a `Packages` object will throw. Iterable<String> get packages; /// Retrieve metadata associated with a package. /// /// Metadata have string keys and values, and are looked up by key. /// /// Returns `null` if the argument is not a valid package name, /// or if the package is not one of the packages configured by /// this packages object, or if the package does not have associated /// metadata with the provided [key]. /// /// Not all `Packages` objects can support metadata. /// Those will always return `null`. String packageMetadata(String packageName, String key); /// Retrieve metadata associated with a library. /// /// If [libraryUri] is a `package:` URI, the returned value /// is the same that would be returned by [packageMetadata] with /// the package's name and the same key. /// /// If [libraryUri] is not a `package:` URI, and this [Packages] /// object has a [defaultPackageName], then the [key] is looked /// up on the default package instead. /// /// Otherwise the result is `null`. String libraryMetadata(Uri libraryUri, String key); /// Return the names-to-base-URI mapping of the available packages. /// /// Returns a map from package name to a base URI. /// The [resolve] method will resolve a package URI with a specific package /// name to a path extending the base URI that this map gives for that /// package name. /// /// Some `Packages` objects are unable to find the package names, /// and calling `asMap` on such a `Packages` object will throw. Map<String, Uri> asMap(); /// The name of the "default package". /// /// A default package is a package that *non-package* libraries /// may be considered part of for some purposes. /// /// The value is `null` if there is no default package. /// Not all implementations of [Packages] supports a default package, /// and will always have a `null` value for those. String get defaultPackageName; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/packages_file.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. @Deprecated("Use the package_config.json based API") library package_config.packages_file; import "package:charcode/ascii.dart"; import "src/util.dart" show isValidPackageName; /// Parses a `.packages` file into a map from package name to base URI. /// /// The [source] is the byte content of a `.packages` file, assumed to be /// UTF-8 encoded. In practice, all significant parts of the file must be ASCII, /// so Latin-1 or Windows-1252 encoding will also work fine. /// /// If the file content is available as a string, its [String.codeUnits] can /// be used as the `source` argument of this function. /// /// The [baseLocation] is used as a base URI to resolve all relative /// URI references against. /// If the content was read from a file, `baseLocation` should be the /// location of that file. /// /// If [allowDefaultPackage] is set to true, an entry with an empty package name /// is accepted. This entry does not correspond to a package, but instead /// represents a *default package* which non-package libraries may be considered /// part of in some cases. The value of that entry must be a valid package name. /// /// Returns a simple mapping from package name to package location. /// If default package is allowed, the map maps the empty string to the default package's name. Map<String, Uri> parse(List<int> source, Uri baseLocation, {bool allowDefaultPackage = false}) { var index = 0; var result = <String, Uri>{}; while (index < source.length) { var isComment = false; var start = index; var separatorIndex = -1; var end = source.length; var char = source[index++]; if (char == $cr || char == $lf) { continue; } if (char == $colon) { if (!allowDefaultPackage) { throw FormatException("Missing package name", source, index - 1); } separatorIndex = index - 1; } isComment = char == $hash; while (index < source.length) { char = source[index++]; if (char == $colon && separatorIndex < 0) { separatorIndex = index - 1; } else if (char == $cr || char == $lf) { end = index - 1; break; } } if (isComment) continue; if (separatorIndex < 0) { throw FormatException("No ':' on line", source, index - 1); } var packageName = String.fromCharCodes(source, start, separatorIndex); if (packageName.isEmpty ? !allowDefaultPackage : !isValidPackageName(packageName)) { throw FormatException("Not a valid package name", packageName, 0); } var packageValue = String.fromCharCodes(source, separatorIndex + 1, end); Uri packageLocation; if (packageName.isEmpty) { if (!isValidPackageName(packageValue)) { throw FormatException( "Default package entry value is not a valid package name"); } packageLocation = Uri(path: packageValue); } else { packageLocation = baseLocation.resolve(packageValue); if (!packageLocation.path.endsWith('/')) { packageLocation = packageLocation.replace(path: packageLocation.path + "/"); } } if (result.containsKey(packageName)) { if (packageName.isEmpty) { throw FormatException( "More than one default package entry", source, start); } throw FormatException("Same package name occured twice", source, start); } result[packageName] = packageLocation; } return result; } /// Writes the mapping to a [StringSink]. /// /// If [comment] is provided, the output will contain this comment /// with `# ` in front of each line. /// Lines are defined as ending in line feed (`'\n'`). If the final /// line of the comment doesn't end in a line feed, one will be added. /// /// If [baseUri] is provided, package locations will be made relative /// to the base URI, if possible, before writing. /// /// If [allowDefaultPackage] is `true`, the [packageMapping] may contain an /// empty string mapping to the _default package name_. /// /// All the keys of [packageMapping] must be valid package names, /// and the values must be URIs that do not have the `package:` scheme. void write(StringSink output, Map<String, Uri> packageMapping, {Uri baseUri, String comment, bool allowDefaultPackage = false}) { ArgumentError.checkNotNull(allowDefaultPackage, 'allowDefaultPackage'); if (baseUri != null && !baseUri.isAbsolute) { throw ArgumentError.value(baseUri, "baseUri", "Must be absolute"); } if (comment != null) { var lines = comment.split('\n'); if (lines.last.isEmpty) lines.removeLast(); for (var commentLine in lines) { output.write('# '); output.writeln(commentLine); } } else { output.write("# generated by package:package_config at "); output.write(DateTime.now()); output.writeln(); } packageMapping.forEach((String packageName, Uri uri) { // If [packageName] is empty then [uri] is the _default package name_. if (allowDefaultPackage && packageName.isEmpty) { final defaultPackageName = uri.toString(); if (!isValidPackageName(defaultPackageName)) { throw ArgumentError.value( defaultPackageName, 'defaultPackageName', '"$defaultPackageName" is not a valid package name', ); } output.write(':'); output.write(defaultPackageName); output.writeln(); return; } // Validate packageName. if (!isValidPackageName(packageName)) { throw ArgumentError('"$packageName" is not a valid package name'); } if (uri.scheme == "package") { throw ArgumentError.value( "Package location must not be a package: URI", uri.toString()); } output.write(packageName); output.write(':'); // If baseUri provided, make uri relative. if (baseUri != null) { uri = _relativize(uri, baseUri); } if (!uri.path.endsWith('/')) { uri = uri.replace(path: uri.path + '/'); } output.write(uri); output.writeln(); }); } /// Attempts to return a relative URI for [uri]. /// /// The result URI satisfies `baseUri.resolveUri(result) == uri`, /// but may be relative. /// The `baseUri` must be absolute. Uri _relativize(Uri uri, Uri baseUri) { assert(baseUri.isAbsolute); if (uri.hasQuery || uri.hasFragment) { uri = Uri( scheme: uri.scheme, userInfo: uri.hasAuthority ? uri.userInfo : null, host: uri.hasAuthority ? uri.host : null, port: uri.hasAuthority ? uri.port : null, path: uri.path); } // Already relative. We assume the caller knows what they are doing. if (!uri.isAbsolute) return uri; if (baseUri.scheme != uri.scheme) { return uri; } // If authority differs, we could remove the scheme, but it's not worth it. if (uri.hasAuthority != baseUri.hasAuthority) return uri; if (uri.hasAuthority) { if (uri.userInfo != baseUri.userInfo || uri.host.toLowerCase() != baseUri.host.toLowerCase() || uri.port != baseUri.port) { return uri; } } baseUri = baseUri.normalizePath(); var base = baseUri.pathSegments.toList(); if (base.isNotEmpty) { base = List<String>.from(base)..removeLast(); } uri = uri.normalizePath(); var target = uri.pathSegments.toList(); if (target.isNotEmpty && target.last.isEmpty) target.removeLast(); var index = 0; while (index < base.length && index < target.length) { if (base[index] != target[index]) { break; } index++; } if (index == base.length) { if (index == target.length) { return Uri(path: "./"); } return Uri(path: target.skip(index).join('/')); } else if (index > 0) { return Uri( path: '../' * (base.length - index) + target.skip(index).join('/')); } else { return uri; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/package_config.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. /// A package configuration is a way to assign file paths to package URIs, /// and vice-versa, library package_config.package_config_discovery; import "dart:io" show File, Directory; import "dart:typed_data" show Uint8List; import "src/discovery.dart" as discover; import "src/errors.dart" show throwError; import "src/package_config.dart"; import "src/package_config_io.dart"; export "package_config_types.dart"; /// Reads a specific package configuration file. /// /// The file must exist and be readable. /// It must be either a valid `package_config.json` file /// or a valid `.packages` file. /// It is considered a `package_config.json` file if its first character /// is a `{`. /// /// If the file is a `.packages` file (the file name is `.packages`) /// and [preferNewest] is true, the default, also checks if there is /// a `.dart_tool/package_config.json` file next /// to the original file, and if so, loads that instead. /// If [preferNewest] is set to false, a directly specified `.packages` file /// is loaded even if there is an available `package_config.json` file. /// The caller can determine this from the [PackageConfig.version] /// being 1 and look for a `package_config.json` file themselves. /// /// If [onError] is provided, the configuration file parsing will report errors /// by calling that function, and then try to recover. /// The returned package configuration is a *best effort* attempt to create /// a valid configuration from the invalid configuration file. /// If no [onError] is provided, errors are thrown immediately. Future<PackageConfig> loadPackageConfig(File file, {bool preferNewest = true, void onError(Object error)}) => readAnyConfigFile(file, preferNewest, onError ?? throwError); /// Reads a specific package configuration URI. /// /// The file of the URI must exist and be readable. /// It must be either a valid `package_config.json` file /// or a valid `.packages` file. /// It is considered a `package_config.json` file if its first /// non-whitespace character is a `{`. /// /// If [preferNewest] is true, the default, and the file is a `.packages` file, /// as determined by its file name being `.packages`, /// first checks if there is a `.dart_tool/package_config.json` file /// next to the original file, and if so, loads that instead. /// The [file] *must not* be a `package:` URI. /// If [preferNewest] is set to false, a directly specified `.packages` file /// is loaded even if there is an available `package_config.json` file. /// The caller can determine this from the [PackageConfig.version] /// being 1 and look for a `package_config.json` file themselves. /// /// If [loader] is provided, URIs are loaded using that function. /// The future returned by the loader must complete with a [Uint8List] /// containing the entire file content encoded as UTF-8, /// or with `null` if the file does not exist. /// The loader may throw at its own discretion, for situations where /// it determines that an error might be need user attention, /// but it is always allowed to return `null`. /// This function makes no attempt to catch such errors. /// As such, it may throw any error that [loader] throws. /// /// If no [loader] is supplied, a default loader is used which /// only accepts `file:`, `http:` and `https:` URIs, /// and which uses the platform file system and HTTP requests to /// fetch file content. The default loader never throws because /// of an I/O issue, as long as the location URIs are valid. /// As such, it does not distinguish between a file not existing, /// and it being temporarily locked or unreachable. /// /// If [onError] is provided, the configuration file parsing will report errors /// by calling that function, and then try to recover. /// The returned package configuration is a *best effort* attempt to create /// a valid configuration from the invalid configuration file. /// If no [onError] is provided, errors are thrown immediately. Future<PackageConfig> loadPackageConfigUri(Uri file, {Future<Uint8List /*?*/ > loader(Uri uri) /*?*/, bool preferNewest = true, void onError(Object error)}) => readAnyConfigFileUri(file, loader, onError ?? throwError, preferNewest); /// Finds a package configuration relative to [directory]. /// /// If [directory] contains a package configuration, /// either a `.dart_tool/package_config.json` file or, /// if not, a `.packages`, then that file is loaded. /// /// If no file is found in the current directory, /// then the parent directories are checked recursively, /// all the way to the root directory, to check if those contains /// a package configuration. /// If [recurse] is set to [false], this parent directory check is not /// performed. /// /// If [onError] is provided, the configuration file parsing will report errors /// by calling that function, and then try to recover. /// The returned package configuration is a *best effort* attempt to create /// a valid configuration from the invalid configuration file. /// If no [onError] is provided, errors are thrown immediately. /// /// Returns `null` if no configuration file is found. Future<PackageConfig> findPackageConfig(Directory directory, {bool recurse = true, void onError(Object error)}) => discover.findPackageConfig(directory, recurse, onError ?? throwError); /// Finds a package configuration relative to [location]. /// /// If [location] contains a package configuration, /// either a `.dart_tool/package_config.json` file or, /// if not, a `.packages`, then that file is loaded. /// The [location] URI *must not* be a `package:` URI. /// It should be a hierarchical URI which is supported /// by [loader]. /// /// If no file is found in the current directory, /// then the parent directories are checked recursively, /// all the way to the root directory, to check if those contains /// a package configuration. /// If [recurse] is set to [false], this parent directory check is not /// performed. /// /// If [loader] is provided, URIs are loaded using that function. /// The future returned by the loader must complete with a [Uint8List] /// containing the entire file content, /// or with `null` if the file does not exist. /// The loader may throw at its own discretion, for situations where /// it determines that an error might be need user attention, /// but it is always allowed to return `null`. /// This function makes no attempt to catch such errors. /// /// If no [loader] is supplied, a default loader is used which /// only accepts `file:`, `http:` and `https:` URIs, /// and which uses the platform file system and HTTP requests to /// fetch file content. The default loader never throws because /// of an I/O issue, as long as the location URIs are valid. /// As such, it does not distinguish between a file not existing, /// and it being temporarily locked or unreachable. /// /// If [onError] is provided, the configuration file parsing will report errors /// by calling that function, and then try to recover. /// The returned package configuration is a *best effort* attempt to create /// a valid configuration from the invalid configuration file. /// If no [onError] is provided, errors are thrown immediately. /// /// Returns `null` if no configuration file is found. Future<PackageConfig> findPackageConfigUri(Uri location, {bool recurse = true, Future<Uint8List /*?*/ > loader(Uri uri), void onError(Object error)}) => discover.findPackageConfigUri( location, loader, onError ?? throwError, recurse); /// Writes a package configuration to the provided directory. /// /// Writes `.dart_tool/package_config.json` relative to [directory]. /// If the `.dart_tool/` directory does not exist, it is created. /// If it cannot be created, this operation fails. /// /// Also writes a `.packages` file in [directory]. /// This will stop happening eventually as the `.packages` file becomes /// discontinued. /// A comment is generated if `[PackageConfig.extraData]` contains a /// `"generator"` entry. Future<void> savePackageConfig( PackageConfig configuration, Directory directory) => writePackageConfigJsonFile(configuration, directory);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/discovery.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. @Deprecated("Use the package_config.json based API") library package_config.discovery; import "dart:async"; import "dart:io"; import "dart:typed_data" show Uint8List; import "package:path/path.dart" as path; import "packages.dart"; import "packages_file.dart" as pkgfile show parse; import "src/packages_impl.dart"; import "src/packages_io_impl.dart"; /// Reads a package resolution file and creates a [Packages] object from it. /// /// The [packagesFile] must exist and be loadable. /// Currently that means the URI must have a `file`, `http` or `https` scheme, /// and that the file can be loaded and its contents parsed correctly. /// /// If the [loader] is provided, it is used to fetch non-`file` URIs, and /// it can support other schemes or set up more complex HTTP requests. /// /// This function can be used to load an explicitly configured package /// resolution file, for example one specified using a `--packages` /// command-line parameter. Future<Packages> loadPackagesFile(Uri packagesFile, {Future<List<int>> loader(Uri uri)}) async { Packages parseBytes(List<int> bytes) { return MapPackages(pkgfile.parse(bytes, packagesFile)); } if (packagesFile.scheme == "file") { return parseBytes(await File.fromUri(packagesFile).readAsBytes()); } if (loader == null) { return parseBytes(await _httpGet(packagesFile)); } return parseBytes(await loader(packagesFile)); } /// Create a [Packages] object for a package directory. /// /// The [packagesDir] URI should refer to a directory. /// Package names are resolved as relative to sub-directories of the /// package directory. /// /// This function can be used for explicitly configured package directories, /// for example one specified using a `--package-root` comand-line parameter. Packages getPackagesDirectory(Uri packagesDir) { if (packagesDir.scheme == "file") { return FilePackagesDirectoryPackages(Directory.fromUri(packagesDir)); } if (!packagesDir.path.endsWith('/')) { packagesDir = packagesDir.replace(path: packagesDir.path + '/'); } return NonFilePackagesDirectoryPackages(packagesDir); } /// Discover the package configuration for a Dart script. /// /// The [baseUri] points to either the Dart script or its directory. /// A package resolution strategy is found by going through the following steps, /// and stopping when something is found. /// /// * Check if a `.packages` file exists in the same directory. /// * If `baseUri`'s scheme is not `file`, then assume a `packages` directory /// in the same directory, and resolve packages relative to that. /// * If `baseUri`'s scheme *is* `file`: /// * Check if a `packages` directory exists. /// * Otherwise check each successive parent directory of `baseUri` for a /// `.packages` file. /// /// If any of these tests succeed, a `Packages` class is returned. /// Returns the constant [noPackages] if no resolution strategy is found. /// /// This function currently only supports `file`, `http` and `https` URIs. /// It needs to be able to load a `.packages` file from the URI, so only /// recognized schemes are accepted. /// /// To support other schemes, or more complex HTTP requests, /// an optional [loader] function can be supplied. /// It's called to load the `.packages` file for a non-`file` scheme. /// The loader function returns the *contents* of the file /// identified by the URI it's given. /// The content should be a UTF-8 encoded `.packages` file, and must return an /// error future if loading fails for any reason. Future<Packages> findPackages(Uri baseUri, {Future<List<int>> loader(Uri unsupportedUri)}) { if (baseUri.scheme == "file") { return Future<Packages>.sync(() => findPackagesFromFile(baseUri)); } else if (loader != null) { return findPackagesFromNonFile(baseUri, loader: loader); } else if (baseUri.scheme == "http" || baseUri.scheme == "https") { return findPackagesFromNonFile(baseUri, loader: _httpGet); } else { return Future<Packages>.value(Packages.noPackages); } } /// Find the location of the package resolution file/directory for a Dart file. /// /// Checks for a `.packages` file in the [workingDirectory]. /// If not found, checks for a `packages` directory in the same directory. /// If still not found, starts checking parent directories for /// `.packages` until reaching the root directory. /// /// Returns a [File] object of a `.packages` file if one is found, or a /// [Directory] object for the `packages/` directory if that is found. FileSystemEntity _findPackagesFile(String workingDirectory) { var dir = Directory(workingDirectory); if (!dir.isAbsolute) dir = dir.absolute; if (!dir.existsSync()) { throw ArgumentError.value( workingDirectory, "workingDirectory", "Directory does not exist."); } File checkForConfigFile(Directory directory) { assert(directory.isAbsolute); var file = File(path.join(directory.path, ".packages")); if (file.existsSync()) return file; return null; } // Check for $cwd/.packages var packagesCfgFile = checkForConfigFile(dir); if (packagesCfgFile != null) return packagesCfgFile; // Check for $cwd/packages/ var packagesDir = Directory(path.join(dir.path, "packages")); if (packagesDir.existsSync()) return packagesDir; // Check for cwd(/..)+/.packages var parentDir = dir.parent; while (parentDir.path != dir.path) { packagesCfgFile = checkForConfigFile(parentDir); if (packagesCfgFile != null) break; dir = parentDir; parentDir = dir.parent; } return packagesCfgFile; } /// Finds a package resolution strategy for a local Dart script. /// /// The [fileBaseUri] points to either a Dart script or the directory of the /// script. The `fileBaseUri` must be a `file:` URI. /// /// This function first tries to locate a `.packages` file in the `fileBaseUri` /// directory. If that is not found, it instead checks for the presence of /// a `packages/` directory in the same place. /// If that also fails, it starts checking parent directories for a `.packages` /// file, and stops if it finds it. /// Otherwise it gives up and returns [Packages.noPackages]. Packages findPackagesFromFile(Uri fileBaseUri) { var baseDirectoryUri = fileBaseUri; if (!fileBaseUri.path.endsWith('/')) { baseDirectoryUri = baseDirectoryUri.resolve("."); } var baseDirectoryPath = baseDirectoryUri.toFilePath(); var location = _findPackagesFile(baseDirectoryPath); if (location == null) return Packages.noPackages; if (location is File) { var fileBytes = location.readAsBytesSync(); var map = pkgfile.parse(fileBytes, Uri.file(location.path)); return MapPackages(map); } assert(location is Directory); return FilePackagesDirectoryPackages(location); } /// Finds a package resolution strategy for a Dart script. /// /// The [nonFileUri] points to either a Dart script or the directory of the /// script. /// The [nonFileUri] should not be a `file:` URI since the algorithm for /// finding a package resolution strategy is more elaborate for `file:` URIs. /// In that case, use [findPackagesFromFile]. /// /// This function first tries to locate a `.packages` file in the [nonFileUri] /// directory. If that is not found, it instead assumes a `packages/` directory /// in the same place. /// /// By default, this function only works for `http:` and `https:` URIs. /// To support other schemes, a loader must be provided, which is used to /// try to load the `.packages` file. The loader should return the contents /// of the requested `.packages` file as bytes, which will be assumed to be /// UTF-8 encoded. Future<Packages> findPackagesFromNonFile(Uri nonFileUri, {Future<List<int>> loader(Uri name)}) async { loader ??= _httpGet; var packagesFileUri = nonFileUri.resolve(".packages"); try { var fileBytes = await loader(packagesFileUri); var map = pkgfile.parse(fileBytes, packagesFileUri); return MapPackages(map); } catch (_) { // Didn't manage to load ".packages". Assume a "packages/" directory. var packagesDirectoryUri = nonFileUri.resolve("packages/"); return NonFilePackagesDirectoryPackages(packagesDirectoryUri); } } /// Fetches a file over http. Future<List<int>> _httpGet(Uri uri) async { var client = HttpClient(); var request = await client.getUrl(uri); var response = await request.close(); if (response.statusCode != HttpStatus.ok) { throw HttpException('${response.statusCode} ${response.reasonPhrase}', uri: uri); } var splitContent = await response.toList(); var totalLength = 0; for (var list in splitContent) { totalLength += list.length; } var result = Uint8List(totalLength); var offset = 0; for (var contentPart in splitContent) { result.setRange(offset, offset + contentPart.length, contentPart); offset += contentPart.length; } return result; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/discovery_analysis.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. /// Analyse a directory structure and find packages resolvers for each /// sub-directory. /// /// The resolvers are generally the same that would be found by using /// the `discovery.dart` library on each sub-directory in turn, /// but more efficiently and with some heuristics for directories that /// wouldn't otherwise have a package resolution strategy, or that are /// determined to be "package directories" themselves. @Deprecated("Use the package_config.json based API") library package_config.discovery_analysis; import "dart:collection" show HashMap; import "dart:io" show File, Directory; import "package:path/path.dart" as path; import "packages.dart"; import "packages_file.dart" as pkgfile; import "src/packages_impl.dart"; import "src/packages_io_impl.dart"; /// Associates a [Packages] package resolution strategy with a directory. /// /// The package resolution applies to the directory and any sub-directory /// that doesn't have its own overriding child [PackageContext]. abstract class PackageContext { /// The directory that introduced the [packages] resolver. Directory get directory; /// A [Packages] resolver that applies to the directory. /// /// Introduced either by a `.packages` file or a `packages/` directory. Packages get packages; /// Child contexts that apply to sub-directories of [directory]. List<PackageContext> get children; /// Look up the [PackageContext] that applies to a specific directory. /// /// The directory must be inside [directory]. PackageContext operator [](Directory directory); /// A map from directory to package resolver. /// /// Has an entry for this package context and for each child context /// contained in this one. Map<Directory, Packages> asMap(); /// Analyze [directory] and sub-directories for package resolution strategies. /// /// Returns a mapping from sub-directories to [Packages] objects. /// /// The analysis assumes that there are no `.packages` files in a parent /// directory of `directory`. If there is, its corresponding `Packages` object /// should be provided as `root`. static PackageContext findAll(Directory directory, {Packages root = Packages.noPackages}) { if (!directory.existsSync()) { throw ArgumentError("Directory not found: $directory"); } var contexts = <PackageContext>[]; void findRoots(Directory directory) { Packages packages; List<PackageContext> oldContexts; var packagesFile = File(path.join(directory.path, ".packages")); if (packagesFile.existsSync()) { packages = _loadPackagesFile(packagesFile); oldContexts = contexts; contexts = []; } else { var packagesDir = Directory(path.join(directory.path, "packages")); if (packagesDir.existsSync()) { packages = FilePackagesDirectoryPackages(packagesDir); oldContexts = contexts; contexts = []; } } for (var entry in directory.listSync()) { if (entry is Directory) { if (packages == null || !entry.path.endsWith("/packages")) { findRoots(entry); } } } if (packages != null) { oldContexts.add(_PackageContext(directory, packages, contexts)); contexts = oldContexts; } } findRoots(directory); // If the root is not itself context root, add a the wrapper context. if (contexts.length == 1 && contexts[0].directory == directory) { return contexts[0]; } return _PackageContext(directory, root, contexts); } } class _PackageContext implements PackageContext { final Directory directory; final Packages packages; final List<PackageContext> children; _PackageContext(this.directory, this.packages, List<PackageContext> children) : children = List<PackageContext>.unmodifiable(children); Map<Directory, Packages> asMap() { var result = HashMap<Directory, Packages>(); void recurse(_PackageContext current) { result[current.directory] = current.packages; for (var child in current.children) { recurse(child); } } recurse(this); return result; } PackageContext operator [](Directory directory) { var path = directory.path; if (!path.startsWith(this.directory.path)) { throw ArgumentError("Not inside $path: $directory"); } var current = this; // The current path is know to agree with directory until deltaIndex. var deltaIndex = current.directory.path.length; List children = current.children; var i = 0; while (i < children.length) { // TODO(lrn): Sort children and use binary search. _PackageContext child = children[i]; var childPath = child.directory.path; if (_stringsAgree(path, childPath, deltaIndex, childPath.length)) { deltaIndex = childPath.length; if (deltaIndex == path.length) { return child; } current = child; children = current.children; i = 0; continue; } i++; } return current; } static bool _stringsAgree(String a, String b, int start, int end) { if (a.length < end || b.length < end) return false; for (var i = start; i < end; i++) { if (a.codeUnitAt(i) != b.codeUnitAt(i)) return false; } return true; } } Packages _loadPackagesFile(File file) { var uri = Uri.file(file.path); var bytes = file.readAsBytesSync(); var map = pkgfile.parse(bytes, uri); return MapPackages(map); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/util.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. /// Utility methods used by more than one library in the package. library package_config.util; import "errors.dart"; // All ASCII characters that are valid in a package name, with space // for all the invalid ones (including space). const String _validPackageNameCharacters = r" ! $ &'()*+,-. 0123456789 ; = " r"@ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz ~ "; /// Tests whether something is a valid Dart package name. bool isValidPackageName(String string) { return checkPackageName(string) < 0; } /// Check if a string is a valid package name. /// /// Valid package names contain only characters in [_validPackageNameCharacters] /// and must contain at least one non-'.' character. /// /// Returns `-1` if the string is valid. /// Otherwise returns the index of the first invalid character, /// or `string.length` if the string contains no non-'.' character. int checkPackageName(String string) { // Becomes non-zero if any non-'.' character is encountered. var nonDot = 0; for (var i = 0; i < string.length; i++) { var c = string.codeUnitAt(i); if (c > 0x7f || _validPackageNameCharacters.codeUnitAt(c) <= $space) { return i; } nonDot += c ^ $dot; } if (nonDot == 0) return string.length; return -1; } /// Validate that a [Uri] is a valid `package:` URI. /// /// Used to validate user input. /// /// Returns the package name extracted from the package URI, /// which is the path segment between `package:` and the first `/`. String checkValidPackageUri(Uri packageUri, String name) { if (packageUri.scheme != "package") { throw PackageConfigArgumentError(packageUri, name, "Not a package: URI"); } if (packageUri.hasAuthority) { throw PackageConfigArgumentError( packageUri, name, "Package URIs must not have a host part"); } if (packageUri.hasQuery) { // A query makes no sense if resolved to a file: URI. throw PackageConfigArgumentError( packageUri, name, "Package URIs must not have a query part"); } if (packageUri.hasFragment) { // We could leave the fragment after the URL when resolving, // but it would be odd if "package:foo/foo.dart#1" and // "package:foo/foo.dart#2" were considered different libraries. // Keep the syntax open in case we ever get multiple libraries in one file. throw PackageConfigArgumentError( packageUri, name, "Package URIs must not have a fragment part"); } if (packageUri.path.startsWith('/')) { throw PackageConfigArgumentError( packageUri, name, "Package URIs must not start with a '/'"); } var firstSlash = packageUri.path.indexOf('/'); if (firstSlash == -1) { throw PackageConfigArgumentError(packageUri, name, "Package URIs must start with the package name followed by a '/'"); } var packageName = packageUri.path.substring(0, firstSlash); var badIndex = checkPackageName(packageName); if (badIndex >= 0) { if (packageName.isEmpty) { throw PackageConfigArgumentError( packageUri, name, "Package names mus be non-empty"); } if (badIndex == packageName.length) { throw PackageConfigArgumentError(packageUri, name, "Package names must contain at least one non-'.' character"); } assert(badIndex < packageName.length); var badCharCode = packageName.codeUnitAt(badIndex); var badChar = "U+" + badCharCode.toRadixString(16).padLeft(4, '0'); if (badCharCode >= 0x20 && badCharCode <= 0x7e) { // Printable character. badChar = "'${packageName[badIndex]}' ($badChar)"; } throw PackageConfigArgumentError( packageUri, name, "Package names must not contain $badChar"); } return packageName; } /// Checks whether URI is just an absolute directory. /// /// * It must have a scheme. /// * It must not have a query or fragment. /// * The path must end with `/`. bool isAbsoluteDirectoryUri(Uri uri) { if (uri.hasQuery) return false; if (uri.hasFragment) return false; if (!uri.hasScheme) return false; var path = uri.path; if (!path.endsWith("/")) return false; return true; } /// Whether the former URI is a prefix of the latter. bool isUriPrefix(Uri prefix, Uri path) { assert(!prefix.hasFragment); assert(!prefix.hasQuery); assert(!path.hasQuery); assert(!path.hasFragment); assert(prefix.path.endsWith('/')); return path.toString().startsWith(prefix.toString()); } /// Finds the first non-JSON-whitespace character in a file. /// /// Used to heuristically detect whether a file is a JSON file or an .ini file. int firstNonWhitespaceChar(List<int> bytes) { for (var i = 0; i < bytes.length; i++) { var char = bytes[i]; if (char != 0x20 && char != 0x09 && char != 0x0a && char != 0x0d) { return char; } } return -1; } /// Attempts to return a relative path-only URI for [uri]. /// /// First removes any query or fragment part from [uri]. /// /// If [uri] is already relative (has no scheme), it's returned as-is. /// If that is not desired, the caller can pass `baseUri.resolveUri(uri)` /// as the [uri] instead. /// /// If the [uri] has a scheme or authority part which differs from /// the [baseUri], or if there is no overlap in the paths of the /// two URIs at all, the [uri] is returned as-is. /// /// Otherwise the result is a path-only URI which satsifies /// `baseUri.resolveUri(result) == uri`, /// /// The `baseUri` must be absolute. Uri relativizeUri(Uri uri, Uri /*?*/ baseUri) { if (baseUri == null) return uri; assert(baseUri.isAbsolute); if (uri.hasQuery || uri.hasFragment) { uri = Uri( scheme: uri.scheme, userInfo: uri.hasAuthority ? uri.userInfo : null, host: uri.hasAuthority ? uri.host : null, port: uri.hasAuthority ? uri.port : null, path: uri.path); } // Already relative. We assume the caller knows what they are doing. if (!uri.isAbsolute) return uri; if (baseUri.scheme != uri.scheme) { return uri; } // If authority differs, we could remove the scheme, but it's not worth it. if (uri.hasAuthority != baseUri.hasAuthority) return uri; if (uri.hasAuthority) { if (uri.userInfo != baseUri.userInfo || uri.host.toLowerCase() != baseUri.host.toLowerCase() || uri.port != baseUri.port) { return uri; } } baseUri = baseUri.normalizePath(); var base = [...baseUri.pathSegments]; if (base.isNotEmpty) base.removeLast(); uri = uri.normalizePath(); var target = [...uri.pathSegments]; if (target.isNotEmpty && target.last.isEmpty) target.removeLast(); var index = 0; while (index < base.length && index < target.length) { if (base[index] != target[index]) { break; } index++; } if (index == base.length) { if (index == target.length) { return Uri(path: "./"); } return Uri(path: target.skip(index).join('/')); } else if (index > 0) { var buffer = StringBuffer(); for (var n = base.length - index; n > 0; --n) { buffer.write("../"); } buffer.writeAll(target.skip(index), "/"); return Uri(path: buffer.toString()); } else { return uri; } } // Character constants used by this package. /// "Line feed" control character. const int $lf = 0x0a; /// "Carriage return" control character. const int $cr = 0x0d; /// Space character. const int $space = 0x20; /// Character `#`. const int $hash = 0x23; /// Character `.`. const int $dot = 0x2e; /// Character `:`. const int $colon = 0x3a; /// Character `?`. const int $question = 0x3f; /// Character `{`. const int $lbrace = 0x7b;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/packages_impl.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. /// Implementations of [Packages] that may be used in either server or browser /// based applications. For implementations that can only run in the browser, /// see [package_config.packages_io_impl]. @Deprecated("Use the package_config.json based API") library package_config.packages_impl; import "dart:collection" show UnmodifiableMapView; import "../packages.dart"; import "util.dart" show checkValidPackageUri; /// A [Packages] null-object. class NoPackages implements Packages { const NoPackages(); Uri resolve(Uri packageUri, {Uri notFound(Uri packageUri)}) { var packageName = checkValidPackageUri(packageUri, "packageUri"); if (notFound != null) return notFound(packageUri); throw ArgumentError.value( packageUri, "packageUri", 'No package named "$packageName"'); } Iterable<String> get packages => Iterable<String>.empty(); Map<String, Uri> asMap() => const <String, Uri>{}; String get defaultPackageName => null; String packageMetadata(String packageName, String key) => null; String libraryMetadata(Uri libraryUri, String key) => null; } /// Base class for [Packages] implementations. /// /// This class implements the [resolve] method in terms of a private /// member abstract class PackagesBase implements Packages { Uri resolve(Uri packageUri, {Uri notFound(Uri packageUri)}) { packageUri = packageUri.normalizePath(); var packageName = checkValidPackageUri(packageUri, "packageUri"); var packageBase = getBase(packageName); if (packageBase == null) { if (notFound != null) return notFound(packageUri); throw ArgumentError.value( packageUri, "packageUri", 'No package named "$packageName"'); } var packagePath = packageUri.path.substring(packageName.length + 1); return packageBase.resolve(packagePath); } /// Find a base location for a package name. /// /// Returns `null` if no package exists with that name, and that can be /// determined. Uri getBase(String packageName); String get defaultPackageName => null; String packageMetadata(String packageName, String key) => null; String libraryMetadata(Uri libraryUri, String key) => null; } /// A [Packages] implementation based on an existing map. class MapPackages extends PackagesBase { final Map<String, Uri> _mapping; MapPackages(this._mapping); Uri getBase(String packageName) => packageName.isEmpty ? null : _mapping[packageName]; Iterable<String> get packages => _mapping.keys; Map<String, Uri> asMap() => UnmodifiableMapView<String, Uri>(_mapping); String get defaultPackageName => _mapping[""]?.toString(); String packageMetadata(String packageName, String key) { if (packageName.isEmpty) return null; var uri = _mapping[packageName]; if (uri == null || !uri.hasFragment) return null; // This can be optimized, either by caching the map or by // parsing incrementally instead of parsing the entire fragment. return Uri.splitQueryString(uri.fragment)[key]; } String libraryMetadata(Uri libraryUri, String key) { if (libraryUri.isScheme("package")) { return packageMetadata(libraryUri.pathSegments.first, key); } var defaultPackageNameUri = _mapping[""]; if (defaultPackageNameUri != null) { return packageMetadata(defaultPackageNameUri.toString(), key); } return null; } } /// A [Packages] implementation based on a remote (e.g., HTTP) directory. /// /// There is no way to detect which packages exist short of trying to use /// them. You can't necessarily check whether a directory exists, /// except by checking for a know file in the directory. class NonFilePackagesDirectoryPackages extends PackagesBase { final Uri _packageBase; NonFilePackagesDirectoryPackages(this._packageBase); Uri getBase(String packageName) => _packageBase.resolve("$packageName/"); Error _failListingPackages() { return UnsupportedError( "Cannot list packages for a ${_packageBase.scheme}: " "based package root"); } Iterable<String> get packages { throw _failListingPackages(); } Map<String, Uri> asMap() { throw _failListingPackages(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/packages_file.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_config_impl.dart"; import "util.dart"; import "errors.dart"; /// The language version prior to the release of language versioning. /// /// This is the default language version used by all packages from a /// `.packages` file. final LanguageVersion _languageVersion = LanguageVersion(2, 7); /// Parses a `.packages` file into a [PackageConfig]. /// /// The [source] is the byte content of a `.packages` file, assumed to be /// UTF-8 encoded. In practice, all significant parts of the file must be ASCII, /// so Latin-1 or Windows-1252 encoding will also work fine. /// /// If the file content is available as a string, its [String.codeUnits] can /// be used as the `source` argument of this function. /// /// The [baseLocation] is used as a base URI to resolve all relative /// URI references against. /// If the content was read from a file, `baseLocation` should be the /// location of that file. /// /// Returns a simple package configuration where each package's /// [Package.packageUriRoot] is the same as its [Package.root] /// and it has no [Package.languageVersion]. PackageConfig parse( List<int> source, Uri baseLocation, void onError(Object error)) { if (baseLocation.isScheme("package")) { onError(PackageConfigArgumentError( baseLocation, "baseLocation", "Must not be a package: URI")); return PackageConfig.empty; } var index = 0; var packages = <Package>[]; var packageNames = <String>{}; while (index < source.length) { var ignoreLine = false; var start = index; var separatorIndex = -1; var end = source.length; var char = source[index++]; if (char == $cr || char == $lf) { continue; } if (char == $colon) { onError(PackageConfigFormatException( "Missing package name", source, index - 1)); ignoreLine = true; // Ignore if package name is invalid. } else { ignoreLine = char == $hash; // Ignore if comment. } var queryStart = -1; var fragmentStart = -1; while (index < source.length) { char = source[index++]; if (char == $colon && separatorIndex < 0) { separatorIndex = index - 1; } else if (char == $cr || char == $lf) { end = index - 1; break; } else if (char == $question && queryStart < 0 && fragmentStart < 0) { queryStart = index - 1; } else if (char == $hash && fragmentStart < 0) { fragmentStart = index - 1; } } if (ignoreLine) continue; if (separatorIndex < 0) { onError( PackageConfigFormatException("No ':' on line", source, index - 1)); continue; } var packageName = String.fromCharCodes(source, start, separatorIndex); var invalidIndex = checkPackageName(packageName); if (invalidIndex >= 0) { onError(PackageConfigFormatException( "Not a valid package name", source, start + invalidIndex)); continue; } if (queryStart >= 0) { onError(PackageConfigFormatException( "Location URI must not have query", source, queryStart)); end = queryStart; } else if (fragmentStart >= 0) { onError(PackageConfigFormatException( "Location URI must not have fragment", source, fragmentStart)); end = fragmentStart; } var packageValue = String.fromCharCodes(source, separatorIndex + 1, end); Uri packageLocation; try { packageLocation = baseLocation.resolve(packageValue); } on FormatException catch (e) { onError(PackageConfigFormatException.from(e)); continue; } if (packageLocation.isScheme("package")) { onError(PackageConfigFormatException( "Package URI as location for package", source, separatorIndex + 1)); continue; } var path = packageLocation.path; if (!path.endsWith('/')) { path += "/"; packageLocation = packageLocation.replace(path: path); } if (packageNames.contains(packageName)) { onError(PackageConfigFormatException( "Same package name occured more than once", source, start)); continue; } var rootUri = packageLocation; if (path.endsWith("/lib/")) { // Assume default Pub package layout. Include package itself in root. rootUri = packageLocation.replace(path: path.substring(0, path.length - 4)); } var package = SimplePackage.validate( packageName, rootUri, packageLocation, _languageVersion, null, (error) { if (error is ArgumentError) { onError(PackageConfigFormatException(error.message, source)); } else { onError(error); } }); if (package != null) { packages.add(package); packageNames.add(packageName); } } return SimplePackageConfig(1, packages, null, onError); } /// Writes the configuration to a [StringSink]. /// /// If [comment] is provided, the output will contain this comment /// with `# ` in front of each line. /// Lines are defined as ending in line feed (`'\n'`). If the final /// line of the comment doesn't end in a line feed, one will be added. /// /// If [baseUri] is provided, package locations will be made relative /// to the base URI, if possible, before writing. /// /// If [allowDefaultPackage] is `true`, the [packageMapping] may contain an /// empty string mapping to the _default package name_. /// /// All the keys of [packageMapping] must be valid package names, /// and the values must be URIs that do not have the `package:` scheme. void write(StringSink output, PackageConfig config, {Uri baseUri, String comment}) { if (baseUri != null && !baseUri.isAbsolute) { throw PackageConfigArgumentError(baseUri, "baseUri", "Must be absolute"); } if (comment != null) { var lines = comment.split('\n'); if (lines.last.isEmpty) lines.removeLast(); for (var commentLine in lines) { output.write('# '); output.writeln(commentLine); } } else { output.write("# generated by package:package_config at "); output.write(DateTime.now()); output.writeln(); } for (var package in config.packages) { var packageName = package.name; var uri = package.packageUriRoot; // Validate packageName. if (!isValidPackageName(packageName)) { throw PackageConfigArgumentError( config, "config", '"$packageName" is not a valid package name'); } if (uri.scheme == "package") { throw PackageConfigArgumentError( config, "config", "Package location must not be a package URI: $uri"); } output.write(packageName); output.write(':'); // If baseUri is provided, make the URI relative to baseUri. if (baseUri != null) { uri = relativizeUri(uri, baseUri); } if (!uri.path.endsWith('/')) { uri = uri.replace(path: uri.path + '/'); } output.write(uri); output.writeln(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/package_config_impl.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 'errors.dart'; import "package_config.dart"; import "util.dart"; export "package_config.dart"; // Implementations of the main data types exposed by the API of this package. class SimplePackageConfig implements PackageConfig { final int version; final Map<String, Package> _packages; final PackageTree _packageTree; final dynamic extraData; factory SimplePackageConfig(int version, Iterable<Package> packages, [dynamic extraData, void onError(Object error)]) { onError ??= throwError; var validVersion = _validateVersion(version, onError); var sortedPackages = [...packages]..sort(_compareRoot); var packageTree = _validatePackages(packages, sortedPackages, onError); return SimplePackageConfig._(validVersion, packageTree, {for (var p in packageTree.allPackages) p.name: p}, extraData); } SimplePackageConfig._( this.version, this._packageTree, this._packages, this.extraData); /// Creates empty configuration. /// /// The empty configuration can be used in cases where no configuration is /// found, but code expects a non-null configuration. const SimplePackageConfig.empty() : version = 1, _packageTree = const EmptyPackageTree(), _packages = const <String, Package>{}, extraData = null; static int _validateVersion(int version, void onError(Object error)) { if (version < 0 || version > PackageConfig.maxVersion) { onError(PackageConfigArgumentError(version, "version", "Must be in the range 1 to ${PackageConfig.maxVersion}")); return 2; // The minimal version supporting a SimplePackageConfig. } return version; } static PackageTree _validatePackages(Iterable<Package> originalPackages, List<Package> packages, void onError(Object error)) { var packageNames = <String>{}; var tree = MutablePackageTree(); for (var originalPackage in packages) { if (originalPackage == null) { onError(ArgumentError.notNull("element of packages")); continue; } SimplePackage package; if (originalPackage is! SimplePackage) { // SimplePackage validates these properties. package = SimplePackage.validate( originalPackage.name, originalPackage.root, originalPackage.packageUriRoot, originalPackage.languageVersion, originalPackage.extraData, (error) { if (error is PackageConfigArgumentError) { onError(PackageConfigArgumentError(packages, "packages", "Package ${package.name}: ${error.message}")); } else { onError(error); } }); if (package == null) continue; } else { package = originalPackage; } var name = package.name; if (packageNames.contains(name)) { onError(PackageConfigArgumentError( name, "packages", "Duplicate package name")); continue; } packageNames.add(name); tree.add(0, package, (error) { if (error is ConflictException) { // There is a conflict with an existing package. var existingPackage = error.existingPackage; if (error.isRootConflict) { onError(PackageConfigArgumentError( originalPackages, "packages", "Packages ${package.name} and ${existingPackage.name} " "have the same root directory: ${package.root}.\n")); } else { assert(error.isPackageRootConflict); // Package is inside the package URI root of the existing package. onError(PackageConfigArgumentError( originalPackages, "packages", "Package ${package.name} is inside the package URI root of " "package ${existingPackage.name}.\n" "${existingPackage.name} URI root: " "${existingPackage.packageUriRoot}\n" "${package.name} root: ${package.root}\n")); } } else { // Any other error. onError(error); } }); } return tree; } Iterable<Package> get packages => _packages.values; Package /*?*/ operator [](String packageName) => _packages[packageName]; /// Provides the associated package for a specific [file] (or directory). /// /// Returns a [Package] which contains the [file]'s path. /// That is, the [Package.rootUri] directory is a parent directory /// of the [file]'s location. /// Returns `null` if the file does not belong to any package. Package /*?*/ packageOf(Uri file) => _packageTree.packageOf(file); Uri /*?*/ resolve(Uri packageUri) { var packageName = checkValidPackageUri(packageUri, "packageUri"); return _packages[packageName]?.packageUriRoot?.resolveUri( Uri(path: packageUri.path.substring(packageName.length + 1))); } Uri /*?*/ toPackageUri(Uri nonPackageUri) { if (nonPackageUri.isScheme("package")) { throw PackageConfigArgumentError( nonPackageUri, "nonPackageUri", "Must not be a package URI"); } if (nonPackageUri.hasQuery || nonPackageUri.hasFragment) { throw PackageConfigArgumentError(nonPackageUri, "nonPackageUri", "Must not have query or fragment part"); } // Find package that file belongs to. var package = _packageTree.packageOf(nonPackageUri); if (package == null) return null; // Check if it is inside the package URI root. var path = nonPackageUri.toString(); var root = package.packageUriRoot.toString(); if (_beginsWith(package.root.toString().length, root, path)) { var rest = path.substring(root.length); return Uri(scheme: "package", path: "${package.name}/$rest"); } return null; } } /// Configuration data for a single package. class SimplePackage implements Package { final String name; final Uri root; final Uri packageUriRoot; final LanguageVersion /*?*/ languageVersion; final dynamic extraData; SimplePackage._(this.name, this.root, this.packageUriRoot, this.languageVersion, this.extraData); /// Creates a [SimplePackage] with the provided content. /// /// The provided arguments must be valid. /// /// If the arguments are invalid then the error is reported by /// calling [onError], then the erroneous entry is ignored. /// /// If [onError] is provided, the user is expected to be able to handle /// errors themselves. An invalid [languageVersion] string /// will be replaced with the string `"invalid"`. This allows /// users to detect the difference between an absent version and /// an invalid one. /// /// Returns `null` if the input is invalid and an approximately valid package /// cannot be salvaged from the input. static SimplePackage /*?*/ validate( String name, Uri root, Uri packageUriRoot, LanguageVersion /*?*/ languageVersion, dynamic extraData, void onError(Object error)) { var fatalError = false; var invalidIndex = checkPackageName(name); if (invalidIndex >= 0) { onError(PackageConfigFormatException( "Not a valid package name", name, invalidIndex)); fatalError = true; } if (root.isScheme("package")) { onError(PackageConfigArgumentError( "$root", "root", "Must not be a package URI")); fatalError = true; } else if (!isAbsoluteDirectoryUri(root)) { onError(PackageConfigArgumentError( "$root", "root", "In package $name: Not an absolute URI with no query or fragment " "with a path ending in /")); // Try to recover. If the URI has a scheme, // then ensure that the path ends with `/`. if (!root.hasScheme) { fatalError = true; } else if (!root.path.endsWith("/")) { root = root.replace(path: root.path + "/"); } } if (packageUriRoot == null) { packageUriRoot = root; } else if (!fatalError) { packageUriRoot = root.resolveUri(packageUriRoot); if (!isAbsoluteDirectoryUri(packageUriRoot)) { onError(PackageConfigArgumentError( packageUriRoot, "packageUriRoot", "In package $name: Not an absolute URI with no query or fragment " "with a path ending in /")); packageUriRoot = root; } else if (!isUriPrefix(root, packageUriRoot)) { onError(PackageConfigArgumentError(packageUriRoot, "packageUriRoot", "The package URI root is not below the package root")); packageUriRoot = root; } } if (fatalError) return null; return SimplePackage._( name, root, packageUriRoot, languageVersion, extraData); } } /// Checks whether [version] is a valid Dart language version string. /// /// The format is (as RegExp) `^(0|[1-9]\d+)\.(0|[1-9]\d+)$`. /// /// Reports a format exception on [onError] if not, or if the numbers /// are too large (at most 32-bit signed integers). LanguageVersion parseLanguageVersion( String source, void onError(Object error)) { var index = 0; // Reads a positive decimal numeral. Returns the value of the numeral, // or a negative number in case of an error. // Starts at [index] and increments the index to the position after // the numeral. // It is an error if the numeral value is greater than 0x7FFFFFFFF. // It is a recoverable error if the numeral starts with leading zeros. int readNumeral() { const maxValue = 0x7FFFFFFF; if (index == source.length) { onError(PackageConfigFormatException("Missing number", source, index)); return -1; } var start = index; var char = source.codeUnitAt(index); var digit = char ^ 0x30; if (digit > 9) { onError(PackageConfigFormatException("Missing number", source, index)); return -1; } var firstDigit = digit; var value = 0; do { value = value * 10 + digit; if (value > maxValue) { onError( PackageConfigFormatException("Number too large", source, start)); return -1; } index++; if (index == source.length) break; char = source.codeUnitAt(index); digit = char ^ 0x30; } while (digit <= 9); if (firstDigit == 0 && index > start + 1) { onError(PackageConfigFormatException( "Leading zero not allowed", source, start)); } return value; } var major = readNumeral(); if (major < 0) { return SimpleInvalidLanguageVersion(source); } if (index == source.length || source.codeUnitAt(index) != $dot) { onError(PackageConfigFormatException("Missing '.'", source, index)); return SimpleInvalidLanguageVersion(source); } index++; var minor = readNumeral(); if (minor < 0) { return SimpleInvalidLanguageVersion(source); } if (index != source.length) { onError(PackageConfigFormatException( "Unexpected trailing character", source, index)); return SimpleInvalidLanguageVersion(source); } return SimpleLanguageVersion(major, minor, source); } abstract class _SimpleLanguageVersionBase implements LanguageVersion { int compareTo(LanguageVersion other) { var result = major.compareTo(other.major); if (result != 0) return result; return minor.compareTo(other.minor); } } class SimpleLanguageVersion extends _SimpleLanguageVersionBase { final int major; final int minor; String /*?*/ _source; SimpleLanguageVersion(this.major, this.minor, this._source); bool operator ==(Object other) => other is LanguageVersion && major == other.major && minor == other.minor; int get hashCode => (major * 17 ^ minor * 37) & 0x3FFFFFFF; String toString() => _source ??= "$major.$minor"; } class SimpleInvalidLanguageVersion extends _SimpleLanguageVersionBase implements InvalidLanguageVersion { final String _source; SimpleInvalidLanguageVersion(this._source); int get major => -1; int get minor => -1; String toString() => _source; } abstract class PackageTree { Iterable<Package> get allPackages; SimplePackage /*?*/ packageOf(Uri file); } /// Packages of a package configuration ordered by root path. /// /// A package has a root path and a package root path, where the latter /// contains the files exposed by `package:` URIs. /// /// A package is said to be inside another package if the root path URI of /// the latter is a prefix of the root path URI of the former. /// /// No two packages of a package may have the same root path, so this /// path prefix ordering defines a tree-like partial ordering on packages /// of a configuration. /// /// The package root path of a package must not be inside another package's /// root path. /// Entire other packages are allowed inside a package's root or /// package root path. /// /// The package tree contains an ordered mapping of unrelated packages /// (represented by their name) to their immediately nested packages' names. class MutablePackageTree implements PackageTree { /// A list of packages that are not nested inside each other. final List<SimplePackage> packages = []; /// The tree of the immediately nested packages inside each package. /// /// Indexed by [Package.name]. /// If a package has no nested packages (which is most often the case), /// there is no tree object associated with it. Map<String, MutablePackageTree /*?*/ > /*?*/ _packageChildren; Iterable<Package> get allPackages sync* { for (var package in packages) yield package; if (_packageChildren != null) { for (var tree in _packageChildren.values) yield* tree.allPackages; } } /// Tries to (add) `package` to the tree. /// /// Reports a [ConflictException] if the added package conflicts with an /// existing package. /// It conflicts if its root or package root is the same as another /// package's root or package root, or is between the two. /// /// If a conflict is detected between [package] and a previous package, /// then [onError] is called with a [ConflictException] object /// and the [package] is not added to the tree. /// /// The packages are added in order of their root path. /// It is never necessary to insert a node between two existing levels. void add(int start, SimplePackage package, void onError(Object error)) { var path = package.root.toString(); for (var treePackage in packages) { // Check is package is inside treePackage. var treePackagePath = treePackage.root.toString(); assert(treePackagePath.length > start); assert(path.startsWith(treePackagePath.substring(0, start))); if (_beginsWith(start, treePackagePath, path)) { // Package *is* inside treePackage. var treePackagePathLength = treePackagePath.length; if (path.length == treePackagePathLength) { // Has same root. Do not add package. onError(ConflictException.root(package, treePackage)); return; } var treePackageUriRoot = treePackage.packageUriRoot.toString(); if (_beginsWith(treePackagePathLength, path, treePackageUriRoot)) { // The treePackage's package root is inside package, which is inside // the treePackage. This is not allowed. onError(ConflictException.packageRoot(package, treePackage)); return; } _treeOf(treePackage).add(treePackagePathLength, package, onError); return; } } packages.add(package); } SimplePackage /*?*/ packageOf(Uri file) { return findPackageOf(0, file.toString()); } /// Finds package containing [path] in this tree. /// /// Returns `null` if no such package is found. /// /// Assumes the first [start] characters of path agrees with all /// the packages at this level of the tree. SimplePackage /*?*/ findPackageOf(int start, String path) { for (var childPackage in packages) { var childPath = childPackage.root.toString(); if (_beginsWith(start, childPath, path)) { // The [package] is inside [childPackage]. var childPathLength = childPath.length; if (path.length == childPathLength) return childPackage; var uriRoot = childPackage.packageUriRoot.toString(); // Is [package] is inside the URI root of [childPackage]. if (uriRoot.length == childPathLength || _beginsWith(childPathLength, uriRoot, path)) { return childPackage; } // Otherwise add [package] as child of [childPackage]. // TODO(lrn): When NNBD comes, convert to: // return _packageChildren?[childPackage.name] // ?.packageOf(childPathLength, path) ?? childPackage; if (_packageChildren == null) return childPackage; var childTree = _packageChildren[childPackage.name]; if (childTree == null) return childPackage; return childTree.findPackageOf(childPathLength, path) ?? childPackage; } } return null; } /// Returns the [PackageTree] of the children of [package]. /// /// Ensures that the object is allocated if necessary. MutablePackageTree _treeOf(SimplePackage package) { var children = _packageChildren ??= {}; return children[package.name] ??= MutablePackageTree(); } } class EmptyPackageTree implements PackageTree { const EmptyPackageTree(); Iterable<Package> get allPackages => const Iterable<Package>.empty(); SimplePackage packageOf(Uri file) => null; } /// Checks whether [longerPath] begins with [parentPath]. /// /// Skips checking the [start] first characters which are assumed to /// already have been matched. bool _beginsWith(int start, String parentPath, String longerPath) { if (longerPath.length < parentPath.length) return false; for (var i = start; i < parentPath.length; i++) { if (longerPath.codeUnitAt(i) != parentPath.codeUnitAt(i)) return false; } return true; } /// Conflict between packages added to the same configuration. /// /// The [package] conflicts with [existingPackage] if it has /// the same root path ([isRootConflict]) or the package URI root path /// of [existingPackage] is inside the root path of [package] /// ([isPackageRootConflict]). class ConflictException { /// The existing package that [package] conflicts with. final SimplePackage existingPackage; /// The package that could not be added without a conflict. final SimplePackage package; /// Whether the conflict is with the package URI root of [existingPackage]. final bool isPackageRootConflict; /// Creates a root conflict between [package] and [existingPackage]. ConflictException.root(this.package, this.existingPackage) : isPackageRootConflict = false; /// Creates a package root conflict between [package] and [existingPackage]. ConflictException.packageRoot(this.package, this.existingPackage) : isPackageRootConflict = true; /// WHether the conflict is with the root URI of [existingPackage]. bool get isRootConflict => !isPackageRootConflict; } /// Used for sorting packages by root path. int _compareRoot(Package p1, Package p2) => p1.root.toString().compareTo(p2.root.toString());
0