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/build_resolvers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers/src/analysis_driver.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:analyzer/src/dart/analysis/byte_store.dart' show MemoryByteStore; import 'package:analyzer/src/dart/analysis/driver.dart'; import 'package:analyzer/src/dart/analysis/file_state.dart'; import 'package:analyzer/src/dart/analysis/performance_logger.dart' show PerformanceLog; import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl, AnalysisOptions; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; import 'package:analyzer/src/summary/summary_sdk.dart' show SummaryBasedDartSdk; import 'build_asset_uri_resolver.dart'; /// Builds an [AnalysisDriver] backed by a summary SDK and package summary /// files. /// /// Any code which is not covered by the summaries must be resolvable through /// [buildAssetUriResolver]. AnalysisDriver analysisDriver(BuildAssetUriResolver buildAssetUriResolver, AnalysisOptions analysisOptions, String sdkSummaryPath) { var sdk = SummaryBasedDartSdk(sdkSummaryPath, true); var sdkResolver = DartUriResolver(sdk); var resolvers = [sdkResolver, buildAssetUriResolver]; var sourceFactory = SourceFactory(resolvers); var dataStore = SummaryDataStore([sdkSummaryPath]); var logger = PerformanceLog(null); var scheduler = AnalysisDriverScheduler(logger); var driver = AnalysisDriver( scheduler, logger, buildAssetUriResolver.resourceProvider, MemoryByteStore(), FileContentOverlay(), null, sourceFactory, (analysisOptions as AnalysisOptionsImpl) ?? AnalysisOptionsImpl(), externalSummaries: dataStore, ); scheduler.start(); return driver; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_resolvers/src/build_asset_uri_resolver.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; // ignore: deprecated_member_use import 'package:analyzer/analyzer.dart' show parseDirectives; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/file_system/memory_file_system.dart'; import 'package:analyzer/src/dart/analysis/driver.dart' show AnalysisDriver; import 'package:analyzer/src/generated/source.dart'; import 'package:build/build.dart' show AssetId, BuildStep; import 'package:crypto/crypto.dart'; import 'package:graphs/graphs.dart'; import 'package:path/path.dart' as p; const _ignoredSchemes = ['dart', 'dart-ext']; class BuildAssetUriResolver extends UriResolver { /// A cache of the directives for each Dart library. /// /// This is stored across builds and is only invalidated if we read a file and /// see that it's content is different from what it was last time it was read. final _cachedAssetDependencies = <AssetId, Set<AssetId>>{}; /// A cache of the digest for each Dart asset. /// /// This is stored across builds and used to invalidate the values in /// [_cachedAssetDependencies] only when the actual content of the library /// changed. final _cachedAssetDigests = <AssetId, Digest>{}; final resourceProvider = MemoryResourceProvider(context: p.posix); /// The assets which are known to be readable at some point during the current /// build. /// /// When actions can run out of order an asset can move from being readable /// (in the later phase) to being unreadable (in the earlier phase which ran /// later). If this happens we don't want to hide the asset from the analyzer. final seenAssets = HashSet<AssetId>(); /// Crawl the transitive imports from [entryPoints] and ensure that the /// content of each asset is updated in [resourceProvider] and [driver]. Future<void> performResolve(BuildStep buildStep, List<AssetId> entryPoints, AnalysisDriver driver) async { final changedPaths = await crawlAsync<AssetId, _AssetState>(entryPoints, (id) async { final path = assetPath(id); if (!await buildStep.canRead(id)) { if (seenAssets.contains(id)) { // ignore from this graph, some later build step may still be using it // so it shouldn't be removed from [resourceProvider], but we also // don't care about it's transitive imports. return null; } _cachedAssetDependencies.remove(id); _cachedAssetDigests.remove(id); if (resourceProvider.getFile(path).exists) { resourceProvider.deleteFile(path); } return _AssetState.removed(path); } seenAssets.add(id); final digest = await buildStep.digest(id); if (_cachedAssetDigests[id] == digest) { return _AssetState.unchanged(path, _cachedAssetDependencies[id]); } else { final isChange = _cachedAssetDigests.containsKey(id); final content = await buildStep.readAsString(id); _cachedAssetDigests[id] = digest; final dependencies = _cachedAssetDependencies[id] = _parseDirectives(content, id); if (isChange) { resourceProvider.updateFile(path, content); return _AssetState.changed(path, dependencies); } else { resourceProvider.newFile(path, content); return _AssetState.newAsset(path, dependencies); } } }, (id, state) => state.directives) .where((state) => state.isAssetUpdate) .map((state) => state.path) .toList(); changedPaths.forEach(driver.changeFile); } /// Attempts to parse [uri] into an [AssetId] and returns it if it is cached. /// /// Handles 'package:' or 'asset:' URIs, as well as 'file:' URIs that have the /// same pattern used by [assetPath]. /// /// Returns null if the Uri cannot be parsed or is not cached. AssetId lookupAsset(Uri uri) { if (_ignoredSchemes.any(uri.isScheme)) return null; if (uri.isScheme('package') || uri.isScheme('asset')) { final assetId = AssetId.resolve('$uri'); return _cachedAssetDigests.containsKey(assetId) ? assetId : null; } if (uri.isScheme('file')) { final parts = p.split(uri.path); final assetId = AssetId(parts[1], p.posix.joinAll(parts.skip(2))); return _cachedAssetDigests.containsKey(assetId) ? assetId : null; } return null; } @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { final cachedId = lookupAsset(uri); if (cachedId == null) return null; return resourceProvider .getFile(assetPath(cachedId)) .createSource(cachedId.uri); } @override Uri restoreAbsolute(Source source) => lookupAsset(source.uri)?.uri ?? source.uri; } String assetPath(AssetId assetId) => p.posix.join('/${assetId.package}', assetId.path); /// Returns all the directives from a Dart library that can be resolved to an /// [AssetId]. Set<AssetId> _parseDirectives(String content, AssetId from) => // ignore: deprecated_member_use HashSet.of(parseDirectives(content, suppressErrors: true) .directives .whereType<UriBasedDirective>() .where((directive) { var uri = Uri.parse(directive.uri.stringValue); return !_ignoredSchemes.any(uri.isScheme); }) .map((d) => AssetId.resolve(d.uri.stringValue, from: from)) .where((id) => id != null)); class _AssetState { final String path; final bool isAssetUpdate; final Iterable<AssetId> directives; _AssetState.removed(this.path) : isAssetUpdate = false, directives = const []; _AssetState.changed(this.path, this.directives) : isAssetUpdate = true; _AssetState.unchanged(this.path, this.directives) : isAssetUpdate = false; _AssetState.newAsset(this.path, this.directives) : isAssetUpdate = false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/ansi.dart
// Copyright 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/ansi_code.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/io.dart
// Copyright 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/copy_path.dart' show copyPath, copyPathSync; export 'src/exit_code.dart' show ExitCode; export 'src/permissions.dart' show isExecutable; export 'src/process_manager.dart' show ProcessManager, Spawn, StartProcess; export 'src/shared_stdin.dart' show SharedStdIn, sharedStdIn; export 'src/shell_words.dart' show shellSplit;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/shared_stdin.dart
// Copyright 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:convert'; import 'dart:io'; import 'package:meta/meta.dart'; /// A shared singleton instance of `dart:io`'s [stdin] stream. /// /// _Unlike_ the normal [stdin] stream, [sharedStdIn] may switch subscribers /// as long as the previous subscriber cancels before the new subscriber starts /// listening. /// /// [SharedStdIn.terminate] *must* be invoked in order to close the underlying /// connection to [stdin], allowing your program to close automatically without /// hanging. final SharedStdIn sharedStdIn = SharedStdIn(stdin); /// A singleton wrapper around `stdin` that allows new subscribers. /// /// This class is visible in order to be used as a test harness for mock /// implementations of `stdin`. In normal programs, [sharedStdIn] should be /// used directly. @visibleForTesting class SharedStdIn extends Stream<List<int>> { StreamController<List<int>> _current; StreamSubscription<List<int>> _sub; SharedStdIn([Stream<List<int>> stream]) { _sub = (stream ??= stdin).listen(_onInput); } /// Returns a future that completes with the next line. /// /// This is similar to the standard [Stdin.readLineSync], but asynchronous. Future<String> nextLine({Encoding encoding = systemEncoding}) { return lines(encoding: encoding).first; } /// Returns the stream transformed as UTF8 strings separated by line breaks. /// /// This is similar to synchronous code using [Stdin.readLineSync]: /// ```dart /// while (true) { /// var line = stdin.readLineSync(); /// // ... /// } /// ``` /// /// ... but asynchronous. Stream<String> lines({Encoding encoding = systemEncoding}) { return transform(utf8.decoder).transform(const LineSplitter()); } void _onInput(List<int> event) => _getCurrent().add(event); StreamController<List<int>> _getCurrent() => _current ??= StreamController<List<int>>( onCancel: () { _current = null; }, sync: true); @override StreamSubscription<List<int>> listen( void Function(List<int> event) onData, { Function onError, void Function() onDone, bool cancelOnError, }) { if (_sub == null) { throw StateError('Stdin has already been terminated.'); } final controller = _getCurrent(); if (controller.hasListener) { throw StateError('' 'Subscriber already listening. The existing subscriber must cancel ' 'before another may be added.'); } return controller.stream.listen( onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError, ); } /// Terminates the connection to `stdin`, closing all subscription. Future<Null> terminate() async { if (_sub == null) { throw StateError('Stdin has already been terminated.'); } await _sub.cancel(); await _current?.close(); _sub = null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/exit_code.dart
// Copyright 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. /// Exit code constants. /// /// [Source](https://www.freebsd.org/cgi/man.cgi?query=sysexits). class ExitCode { /// Command completed successfully. static const success = ExitCode._(0, 'success'); /// Command was used incorrectly. /// /// This may occur if the wrong number of arguments was used, a bad flag, or /// bad syntax in a parameter. static const usage = ExitCode._(64, 'usage'); /// Input data was used incorrectly. /// /// This should occur only for user data (not system files). static const data = ExitCode._(65, 'data'); /// An input file (not a system file) did not exist or was not readable. static const noInput = ExitCode._(66, 'noInput'); /// User specified did not exist. static const noUser = ExitCode._(67, 'noUser'); /// Host specified did not exist. static const noHost = ExitCode._(68, 'noHost'); /// A service is unavailable. /// /// This may occur if a support program or file does not exist. This may also /// be used as a catch-all error when something you wanted to do does not /// work, but you do not know why. static const unavailable = ExitCode._(69, 'unavailable'); /// An internal software error has been detected. /// /// This should be limited to non-operating system related errors as possible. static const software = ExitCode._(70, 'software'); /// An operating system error has been detected. /// /// This intended to be used for such thing as `cannot fork` or `cannot pipe`. static const osError = ExitCode._(71, 'osError'); /// Some system file (e.g. `/etc/passwd`) does not exist or could not be read. static const osFile = ExitCode._(72, 'osFile'); /// A (user specified) output file cannot be created. static const cantCreate = ExitCode._(73, 'cantCreate'); /// An error occurred doing I/O on some file. static const ioError = ExitCode._(74, 'ioError'); /// Temporary failure, indicating something is not really an error. /// /// In some cases, this can be re-attempted and will succeed later. static const tempFail = ExitCode._(75, 'tempFail'); /// You did not have sufficient permissions to perform the operation. /// /// This is not intended for file system problems, which should use [noInput] /// or [cantCreate], but rather for higher-level permissions. static const noPerm = ExitCode._(77, 'noPerm'); /// Something was found in an unconfigured or misconfigured state. static const config = ExitCode._(78, 'config'); /// Exit code value. final int code; /// Name of the exit code. final String _name; const ExitCode._(this.code, this._name); @override String toString() => '$_name: $code'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/copy_path.dart
// Copyright 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:path/path.dart' as p; bool _doNothing(String from, String to) { if (p.canonicalize(from) == p.canonicalize(to)) { return true; } if (p.isWithin(from, to)) { throw ArgumentError('Cannot copy from $from to $to'); } return false; } /// Copies all of the files in the [from] directory to [to]. /// /// This is similar to `cp -R <from> <to>`: /// * Symlinks are supported. /// * Existing files are over-written, if any. /// * If [to] is within [from], throws [ArgumentError] (an infinite operation). /// * If [from] and [to] are canonically the same, no operation occurs. /// /// Returns a future that completes when complete. Future<Null> copyPath(String from, String to) async { if (_doNothing(from, to)) { return; } await Directory(to).create(recursive: true); await for (final file in Directory(from).list(recursive: true)) { final copyTo = p.join(to, p.relative(file.path, from: from)); if (file is Directory) { await Directory(copyTo).create(recursive: true); } else if (file is File) { await File(file.path).copy(copyTo); } else if (file is Link) { await Link(copyTo).create(await file.target(), recursive: true); } } } /// Copies all of the files in the [from] directory to [to]. /// /// This is similar to `cp -R <from> <to>`: /// * Symlinks are supported. /// * Existing files are over-written, if any. /// * If [to] is within [from], throws [ArgumentError] (an infinite operation). /// * If [from] and [to] are canonically the same, no operation occurs. /// /// This action is performed synchronously (blocking I/O). void copyPathSync(String from, String to) { if (_doNothing(from, to)) { return; } Directory(to).createSync(recursive: true); for (final file in Directory(from).listSync(recursive: true)) { final copyTo = p.join(to, p.relative(file.path, from: from)); if (file is Directory) { Directory(copyTo).createSync(recursive: true); } else if (file is File) { File(file.path).copySync(copyTo); } else if (file is Link) { Link(copyTo).createSync(file.targetSync(), recursive: true); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/shell_words.dart
// Copyright 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. // ignore_for_file: comment_references import 'package:charcode/charcode.dart'; import 'package:string_scanner/string_scanner.dart'; /// Splits [command] into tokens according to [the POSIX shell /// specification][spec]. /// /// [spec]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html /// /// This returns the unquoted values of quoted tokens. For example, /// `shellSplit('foo "bar baz"')` returns `["foo", "bar baz"]`. It does not /// currently support here-documents. It does *not* treat dynamic features such /// as parameter expansion specially. For example, `shellSplit("foo $(bar /// baz)")` returns `["foo", "$(bar", "baz)"]`. /// /// This will discard any comments at the end of [command]. /// /// Throws a [FormatException] if [command] isn't a valid shell command. List<String> shellSplit(String command) { final scanner = StringScanner(command); final results = <String>[]; final token = StringBuffer(); // Whether a token is being parsed, as opposed to a separator character. This // is different than just [token.isEmpty], because empty quoted tokens can // exist. var hasToken = false; while (!scanner.isDone) { final next = scanner.readChar(); switch (next) { case $backslash: // Section 2.2.1: A <backslash> that is not quoted shall preserve the // literal value of the following character, with the exception of a // <newline>. If a <newline> follows the <backslash>, the shell shall // interpret this as line continuation. The <backslash> and <newline> // shall be removed before splitting the input into tokens. Since the // escaped <newline> is removed entirely from the input and is not // replaced by any white space, it cannot serve as a token separator. if (scanner.scanChar($lf)) break; hasToken = true; token.writeCharCode(scanner.readChar()); break; case $single_quote: hasToken = true; // Section 2.2.2: Enclosing characters in single-quotes ( '' ) shall // preserve the literal value of each character within the // single-quotes. A single-quote cannot occur within single-quotes. final firstQuote = scanner.position - 1; while (!scanner.scanChar($single_quote)) { _checkUnmatchedQuote(scanner, firstQuote); token.writeCharCode(scanner.readChar()); } break; case $double_quote: hasToken = true; // Section 2.2.3: Enclosing characters in double-quotes ( "" ) shall // preserve the literal value of all characters within the // double-quotes, with the exception of the characters backquote, // <dollar-sign>, and <backslash>. // // (Note that this code doesn't preserve special behavior of backquote // or dollar sign within double quotes, since those are dynamic // features.) final firstQuote = scanner.position - 1; while (!scanner.scanChar($double_quote)) { _checkUnmatchedQuote(scanner, firstQuote); if (scanner.scanChar($backslash)) { _checkUnmatchedQuote(scanner, firstQuote); // The <backslash> shall retain its special meaning as an escape // character (see Escape Character (Backslash)) only when followed // by one of the following characters when considered special: // // $ ` " \ <newline> final next = scanner.readChar(); if (next == $lf) continue; if (next == $dollar || next == $backquote || next == $double_quote || next == $backslash) { token.writeCharCode(next); } else { token..writeCharCode($backslash)..writeCharCode(next); } } else { token.writeCharCode(scanner.readChar()); } } break; case $hash: // Section 2.3: If the current character is a '#' [and the previous // characters was not part of a word], it and all subsequent characters // up to, but excluding, the next <newline> shall be discarded as a // comment. The <newline> that ends the line is not considered part of // the comment. if (hasToken) { token.writeCharCode($hash); break; } while (!scanner.isDone && scanner.peekChar() != $lf) { scanner.readChar(); } break; case $space: case $tab: case $lf: // ignore: invariant_booleans if (hasToken) results.add(token.toString()); hasToken = false; token.clear(); break; default: hasToken = true; token.writeCharCode(next); break; } } if (hasToken) results.add(token.toString()); return results; } /// Throws a [FormatException] if [scanner] is done indicating that a closing /// quote matching the one at position [openingQuote] is missing. void _checkUnmatchedQuote(StringScanner scanner, int openingQuote) { if (!scanner.isDone) return; final type = scanner.substring(openingQuote, openingQuote + 1) == '"' ? 'double' : 'single'; scanner.error('Unmatched $type quote.', position: openingQuote, length: 1); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/process_manager.dart
// Copyright 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' as io; import 'package:meta/meta.dart'; import 'shared_stdin.dart'; /// Type definition for both [io.Process.start] and [ProcessManager.spawn]. /// /// Useful for taking different implementations of this base functionality. typedef StartProcess = Future<io.Process> Function( String executable, List<String> arguments, { String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell, io.ProcessStartMode mode, }); /// A high-level abstraction around using and managing processes on the system. abstract class ProcessManager { /// Terminates the global `stdin` listener, making future listens impossible. /// /// This method should be invoked only at the _end_ of a program's execution. static Future<Null> terminateStdIn() async { await sharedStdIn.terminate(); } /// Create a new instance of [ProcessManager] for the current platform. /// /// May manually specify whether the current platform [isWindows], otherwise /// this is derived from the Dart runtime (i.e. [io.Platform.isWindows]). factory ProcessManager({ Stream<List<int>> stdin, io.IOSink stdout, io.IOSink stderr, bool isWindows, }) { stdin ??= sharedStdIn; stdout ??= io.stdout; stderr ??= io.stderr; isWindows ??= io.Platform.isWindows; if (isWindows) { return _WindowsProcessManager(stdin, stdout, stderr); } return _UnixProcessManager(stdin, stdout, stderr); } final Stream<List<int>> _stdin; final io.IOSink _stdout; final io.IOSink _stderr; const ProcessManager._(this._stdin, this._stdout, this._stderr); /// Spawns a process by invoking [executable] with [arguments]. /// /// This is _similar_ to [io.Process.start], but all standard input and output /// is forwarded/routed between the process and the host, similar to how a /// shell script works. /// /// Returns a future that completes with a handle to the spawned process. Future<io.Process> spawn( String executable, Iterable<String> arguments, { String workingDirectory, Map<String, String> environment, bool includeParentEnvironment = true, bool runInShell = false, io.ProcessStartMode mode = io.ProcessStartMode.normal, }) async { final process = io.Process.start( executable, arguments.toList(), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, mode: mode, ); return _ForwardingSpawn(await process, _stdin, _stdout, _stderr); } /// Spawns a process by invoking [executable] with [arguments]. /// /// This is _similar_ to [io.Process.start], but `stdout` and `stderr` is /// forwarded/routed between the process and host, similar to how a shell /// script works. /// /// Returns a future that completes with a handle to the spawned process. Future<io.Process> spawnBackground( String executable, Iterable<String> arguments, { String workingDirectory, Map<String, String> environment, bool includeParentEnvironment = true, bool runInShell = false, io.ProcessStartMode mode = io.ProcessStartMode.normal, }) async { final process = io.Process.start( executable, arguments.toList(), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, mode: mode, ); return _ForwardingSpawn( await process, const Stream.empty(), _stdout, _stderr, ); } /// Spawns a process by invoking [executable] with [arguments]. /// /// This is _identical to [io.Process.start] (no forwarding of I/O). /// /// Returns a future that completes with a handle to the spawned process. Future<io.Process> spawnDetached( String executable, Iterable<String> arguments, { String workingDirectory, Map<String, String> environment, bool includeParentEnvironment = true, bool runInShell = false, io.ProcessStartMode mode = io.ProcessStartMode.normal, }) async { return io.Process.start( executable, arguments.toList(), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, mode: mode, ); } } /// A process instance created and managed through [ProcessManager]. /// /// Unlike one created directly by [io.Process.start] or [io.Process.run], a /// spawned process works more like executing a command in a shell script. class Spawn implements io.Process { final io.Process _delegate; Spawn._(this._delegate) { _delegate.exitCode.then((_) => _onClosed()); } @mustCallSuper void _onClosed() {} @override bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) => _delegate.kill(signal); @override Future<int> get exitCode => _delegate.exitCode; @override int get pid => _delegate.pid; @override Stream<List<int>> get stderr => _delegate.stderr; @override io.IOSink get stdin => _delegate.stdin; @override Stream<List<int>> get stdout => _delegate.stdout; } /// Forwards `stdin`/`stdout`/`stderr` to/from the host. class _ForwardingSpawn extends Spawn { final StreamSubscription _stdInSub; final StreamSubscription _stdOutSub; final StreamSubscription _stdErrSub; final StreamController<List<int>> _stdOut; final StreamController<List<int>> _stdErr; factory _ForwardingSpawn( io.Process delegate, Stream<List<int>> stdin, io.IOSink stdout, io.IOSink stderr, ) { final stdoutSelf = StreamController<List<int>>(); final stderrSelf = StreamController<List<int>>(); final stdInSub = stdin.listen(delegate.stdin.add); final stdOutSub = delegate.stdout.listen((event) { stdout.add(event); stdoutSelf.add(event); }); final stdErrSub = delegate.stderr.listen((event) { stderr.add(event); stderrSelf.add(event); }); return _ForwardingSpawn._delegate( delegate, stdInSub, stdOutSub, stdErrSub, stdoutSelf, stderrSelf, ); } _ForwardingSpawn._delegate( io.Process delegate, this._stdInSub, this._stdOutSub, this._stdErrSub, this._stdOut, this._stdErr, ) : super._(delegate); @override void _onClosed() { _stdInSub.cancel(); _stdOutSub.cancel(); _stdErrSub.cancel(); super._onClosed(); } @override Stream<List<int>> get stdout => _stdOut.stream; @override Stream<List<int>> get stderr => _stdErr.stream; } class _UnixProcessManager extends ProcessManager { const _UnixProcessManager( Stream<List<int>> stdin, io.IOSink stdout, io.IOSink stderr, ) : super._( stdin, stdout, stderr, ); } class _WindowsProcessManager extends ProcessManager { const _WindowsProcessManager( Stream<List<int>> stdin, io.IOSink stdout, io.IOSink stderr, ) : super._( stdin, stdout, stderr, ); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/ansi_code.dart
// Copyright 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' as io; const _ansiEscapeLiteral = '\x1B'; const _ansiEscapeForScript = '\\033'; /// Whether formatted ANSI output is enabled for [wrapWith] and [AnsiCode.wrap]. /// /// By default, returns `true` if both `stdout.supportsAnsiEscapes` and /// `stderr.supportsAnsiEscapes` from `dart:io` are `true`. /// /// The default can be overridden by setting the [Zone] variable [AnsiCode] to /// either `true` or `false`. /// /// [overrideAnsiOutput] is provided to make this easy. bool get ansiOutputEnabled => Zone.current[AnsiCode] as bool ?? (io.stdout.supportsAnsiEscapes && io.stderr.supportsAnsiEscapes); /// Returns `true` no formatting is required for [input]. bool _isNoop(bool skip, String input, bool forScript) => skip || input == null || input.isEmpty || !((forScript ?? false) || ansiOutputEnabled); /// Allows overriding [ansiOutputEnabled] to [enableAnsiOutput] for the code run /// within [body]. T overrideAnsiOutput<T>(bool enableAnsiOutput, T Function() body) => runZoned(body, zoneValues: <Object, Object>{AnsiCode: enableAnsiOutput}); /// The type of code represented by [AnsiCode]. class AnsiCodeType { final String _name; /// A foreground color. static const AnsiCodeType foreground = AnsiCodeType._('foreground'); /// A style. static const AnsiCodeType style = AnsiCodeType._('style'); /// A background color. static const AnsiCodeType background = AnsiCodeType._('background'); /// A reset value. static const AnsiCodeType reset = AnsiCodeType._('reset'); const AnsiCodeType._(this._name); @override String toString() => 'AnsiType.$_name'; } /// Standard ANSI escape code for customizing terminal text output. /// /// [Source](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) class AnsiCode { /// The numeric value associated with this code. final int code; /// The [AnsiCode] that resets this value, if one exists. /// /// Otherwise, `null`. final AnsiCode reset; /// A description of this code. final String name; /// The type of code that is represented. final AnsiCodeType type; const AnsiCode._(this.name, this.type, this.code, this.reset); /// Represents the value escaped for use in terminal output. String get escape => '$_ansiEscapeLiteral[${code}m'; /// Represents the value as an unescaped literal suitable for scripts. String get escapeForScript => '$_ansiEscapeForScript[${code}m'; String _escapeValue({bool forScript = false}) { forScript ??= false; return forScript ? escapeForScript : escape; } /// Wraps [value] with the [escape] value for this code, followed by /// [resetAll]. /// /// If [forScript] is `true`, the return value is an unescaped literal. The /// value of [ansiOutputEnabled] is also ignored. /// /// Returns `value` unchanged if /// * [value] is `null` or empty /// * both [ansiOutputEnabled] and [forScript] are `false`. /// * [type] is [AnsiCodeType.reset] String wrap(String value, {bool forScript = false}) => _isNoop(type == AnsiCodeType.reset, value, forScript) ? value : '${_escapeValue(forScript: forScript)}$value' '${reset._escapeValue(forScript: forScript)}'; @override String toString() => '$name ${type._name} ($code)'; } /// Returns a [String] formatted with [codes]. /// /// If [forScript] is `true`, the return value is an unescaped literal. The /// value of [ansiOutputEnabled] is also ignored. /// /// Returns `value` unchanged if /// * [value] is `null` or empty. /// * both [ansiOutputEnabled] and [forScript] are `false`. /// * [codes] is empty. /// /// Throws an [ArgumentError] if /// * [codes] contains more than one value of type [AnsiCodeType.foreground]. /// * [codes] contains more than one value of type [AnsiCodeType.background]. /// * [codes] contains any value of type [AnsiCodeType.reset]. String wrapWith(String value, Iterable<AnsiCode> codes, {bool forScript = false}) { forScript ??= false; // Eliminate duplicates final myCodes = codes.toSet(); if (_isNoop(myCodes.isEmpty, value, forScript)) { return value; } var foreground = 0, background = 0; for (var code in myCodes) { switch (code.type) { case AnsiCodeType.foreground: foreground++; if (foreground > 1) { throw ArgumentError.value(codes, 'codes', 'Cannot contain more than one foreground color code.'); } break; case AnsiCodeType.background: background++; if (background > 1) { throw ArgumentError.value(codes, 'codes', 'Cannot contain more than one foreground color code.'); } break; case AnsiCodeType.reset: throw ArgumentError.value( codes, 'codes', 'Cannot contain reset codes.'); break; } } final sortedCodes = myCodes.map((ac) => ac.code).toList()..sort(); final escapeValue = forScript ? _ansiEscapeForScript : _ansiEscapeLiteral; return "$escapeValue[${sortedCodes.join(';')}m$value" '${resetAll._escapeValue(forScript: forScript)}'; } // // Style values // const styleBold = AnsiCode._('bold', AnsiCodeType.style, 1, resetBold); const styleDim = AnsiCode._('dim', AnsiCodeType.style, 2, resetDim); const styleItalic = AnsiCode._('italic', AnsiCodeType.style, 3, resetItalic); const styleUnderlined = AnsiCode._('underlined', AnsiCodeType.style, 4, resetUnderlined); const styleBlink = AnsiCode._('blink', AnsiCodeType.style, 5, resetBlink); const styleReverse = AnsiCode._('reverse', AnsiCodeType.style, 7, resetReverse); /// Not widely supported. const styleHidden = AnsiCode._('hidden', AnsiCodeType.style, 8, resetHidden); /// Not widely supported. const styleCrossedOut = AnsiCode._('crossed out', AnsiCodeType.style, 9, resetCrossedOut); // // Reset values // const resetAll = AnsiCode._('all', AnsiCodeType.reset, 0, null); // NOTE: bold is weird. The reset code seems to be 22 sometimes – not 21 // See https://gitlab.com/gnachman/iterm2/issues/3208 const resetBold = AnsiCode._('bold', AnsiCodeType.reset, 22, null); const resetDim = AnsiCode._('dim', AnsiCodeType.reset, 22, null); const resetItalic = AnsiCode._('italic', AnsiCodeType.reset, 23, null); const resetUnderlined = AnsiCode._('underlined', AnsiCodeType.reset, 24, null); const resetBlink = AnsiCode._('blink', AnsiCodeType.reset, 25, null); const resetReverse = AnsiCode._('reverse', AnsiCodeType.reset, 27, null); const resetHidden = AnsiCode._('hidden', AnsiCodeType.reset, 28, null); const resetCrossedOut = AnsiCode._('crossed out', AnsiCodeType.reset, 29, null); // // Foreground values // const black = AnsiCode._('black', AnsiCodeType.foreground, 30, resetAll); const red = AnsiCode._('red', AnsiCodeType.foreground, 31, resetAll); const green = AnsiCode._('green', AnsiCodeType.foreground, 32, resetAll); const yellow = AnsiCode._('yellow', AnsiCodeType.foreground, 33, resetAll); const blue = AnsiCode._('blue', AnsiCodeType.foreground, 34, resetAll); const magenta = AnsiCode._('magenta', AnsiCodeType.foreground, 35, resetAll); const cyan = AnsiCode._('cyan', AnsiCodeType.foreground, 36, resetAll); const lightGray = AnsiCode._('light gray', AnsiCodeType.foreground, 37, resetAll); const defaultForeground = AnsiCode._('default', AnsiCodeType.foreground, 39, resetAll); const darkGray = AnsiCode._('dark gray', AnsiCodeType.foreground, 90, resetAll); const lightRed = AnsiCode._('light red', AnsiCodeType.foreground, 91, resetAll); const lightGreen = AnsiCode._('light green', AnsiCodeType.foreground, 92, resetAll); const lightYellow = AnsiCode._('light yellow', AnsiCodeType.foreground, 93, resetAll); const lightBlue = AnsiCode._('light blue', AnsiCodeType.foreground, 94, resetAll); const lightMagenta = AnsiCode._('light magenta', AnsiCodeType.foreground, 95, resetAll); const lightCyan = AnsiCode._('light cyan', AnsiCodeType.foreground, 96, resetAll); const white = AnsiCode._('white', AnsiCodeType.foreground, 97, resetAll); // // Background values // const backgroundBlack = AnsiCode._('black', AnsiCodeType.background, 40, resetAll); const backgroundRed = AnsiCode._('red', AnsiCodeType.background, 41, resetAll); const backgroundGreen = AnsiCode._('green', AnsiCodeType.background, 42, resetAll); const backgroundYellow = AnsiCode._('yellow', AnsiCodeType.background, 43, resetAll); const backgroundBlue = AnsiCode._('blue', AnsiCodeType.background, 44, resetAll); const backgroundMagenta = AnsiCode._('magenta', AnsiCodeType.background, 45, resetAll); const backgroundCyan = AnsiCode._('cyan', AnsiCodeType.background, 46, resetAll); const backgroundLightGray = AnsiCode._('light gray', AnsiCodeType.background, 47, resetAll); const backgroundDefault = AnsiCode._('default', AnsiCodeType.background, 49, resetAll); const backgroundDarkGray = AnsiCode._('dark gray', AnsiCodeType.background, 100, resetAll); const backgroundLightRed = AnsiCode._('light red', AnsiCodeType.background, 101, resetAll); const backgroundLightGreen = AnsiCode._('light green', AnsiCodeType.background, 102, resetAll); const backgroundLightYellow = AnsiCode._('light yellow', AnsiCodeType.background, 103, resetAll); const backgroundLightBlue = AnsiCode._('light blue', AnsiCodeType.background, 104, resetAll); const backgroundLightMagenta = AnsiCode._('light magenta', AnsiCodeType.background, 105, resetAll); const backgroundLightCyan = AnsiCode._('light cyan', AnsiCodeType.background, 106, resetAll); const backgroundWhite = AnsiCode._('white', AnsiCodeType.background, 107, resetAll); /// All of the [AnsiCode] values that represent [AnsiCodeType.style]. const List<AnsiCode> styles = [ styleBold, styleDim, styleItalic, styleUnderlined, styleBlink, styleReverse, styleHidden, styleCrossedOut ]; /// All of the [AnsiCode] values that represent [AnsiCodeType.foreground]. const List<AnsiCode> foregroundColors = [ black, red, green, yellow, blue, magenta, cyan, lightGray, defaultForeground, darkGray, lightRed, lightGreen, lightYellow, lightBlue, lightMagenta, lightCyan, white ]; /// All of the [AnsiCode] values that represent [AnsiCodeType.background]. const List<AnsiCode> backgroundColors = [ backgroundBlack, backgroundRed, backgroundGreen, backgroundYellow, backgroundBlue, backgroundMagenta, backgroundCyan, backgroundLightGray, backgroundDefault, backgroundDarkGray, backgroundLightRed, backgroundLightGreen, backgroundLightYellow, backgroundLightBlue, backgroundLightMagenta, backgroundLightCyan, backgroundWhite ];
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/io/src/permissions.dart
// Copyright 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'; /// What type of permission is granted to a file based on file permission roles. enum _FilePermission { execute, write, read, setGid, setUid, sticky, } /// What type of role is assigned to a file. enum _FilePermissionRole { world, group, user, } /// Returns whether file [stat] has [permission] for a [role] type. bool _hasPermission( FileStat stat, _FilePermission permission, { _FilePermissionRole role = _FilePermissionRole.world, }) { final index = _permissionBitIndex(permission, role); return (stat.mode & (1 << index)) != 0; } int _permissionBitIndex(_FilePermission permission, _FilePermissionRole role) { switch (permission) { case _FilePermission.setUid: return 11; case _FilePermission.setGid: return 10; case _FilePermission.sticky: return 9; default: return (role.index * 3) + permission.index; } } /// Returns whether [path] is considered an executable file on this OS. /// /// May optionally define how to implement [getStat] or whether to execute based /// on whether this is the windows platform ([isWindows]) - if not set it is /// automatically extracted from `dart:io#Platform`. /// /// **NOTE**: On windows this always returns `true`. FutureOr<bool> isExecutable( String path, { bool isWindows, FutureOr<FileStat> Function(String path) getStat = FileStat.stat, }) { // Windows has no concept of executable. if (isWindows ?? Platform.isWindows) return true; final stat = getStat(path); if (stat is FileStat) { return _isExecutable(stat); } return (stat as Future<FileStat>).then(_isExecutable); } bool _isExecutable(FileStat stat) => stat.type == FileSystemEntityType.file && _FilePermissionRole.values.any( (role) => _hasPermission(stat, _FilePermission.execute, role: role));
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/string_scanner.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. /// A library for parsing strings using a sequence of patterns. export 'src/exception.dart'; export 'src/line_scanner.dart'; export 'src/span_scanner.dart'; export 'src/string_scanner.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/span_scanner.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:source_span/source_span.dart'; import 'eager_span_scanner.dart'; import 'exception.dart'; import 'line_scanner.dart'; import 'relative_span_scanner.dart'; import 'string_scanner.dart'; import 'utils.dart'; /// A subclass of [LineScanner] that exposes matched ranges as source map /// [FileSpan]s. class SpanScanner extends StringScanner implements LineScanner { /// The source of the scanner. /// /// This caches line break information and is used to generate [FileSpan]s. final SourceFile _sourceFile; int get line => _sourceFile.getLine(position); int get column => _sourceFile.getColumn(position); LineScannerState get state => _SpanScannerState(this, position); set state(LineScannerState state) { if (state is! _SpanScannerState || !identical((state as _SpanScannerState)._scanner, this)) { throw ArgumentError("The given LineScannerState was not returned by " "this LineScanner."); } position = state.position; } /// The [FileSpan] for [lastMatch]. /// /// This is the span for the entire match. There's no way to get spans for /// subgroups since [Match] exposes no information about their positions. FileSpan get lastSpan { if (lastMatch == null) _lastSpan = null; return _lastSpan; } FileSpan _lastSpan; /// The current location of the scanner. FileLocation get location => _sourceFile.location(position); /// Returns an empty span at the current location. FileSpan get emptySpan => location.pointSpan(); /// Creates a new [SpanScanner] that starts scanning from [position]. /// /// [sourceUrl] is used as [SourceLocation.sourceUrl] for the returned /// [FileSpan]s as well as for error reporting. It can be a [String], a /// [Uri], or `null`. SpanScanner(String string, {sourceUrl, int position}) : _sourceFile = SourceFile.fromString(string, url: sourceUrl), super(string, sourceUrl: sourceUrl, position: position); /// Creates a new [SpanScanner] that eagerly computes line and column numbers. /// /// In general [new SpanScanner] will be more efficient, since it avoids extra /// computation on every scan. However, eager scanning can be useful for /// situations where the normal course of parsing frequently involves /// accessing the current line and column numbers. /// /// Note that *only* the `line` and `column` fields on the `SpanScanner` /// itself and its `LineScannerState` are eagerly computed. To limit their /// memory footprint, returned spans and locations will still lazily compute /// their line and column numbers. factory SpanScanner.eager(String string, {sourceUrl, int position}) = EagerSpanScanner; /// Creates a new [SpanScanner] that scans within [span]. /// /// This scans through [span]`.text, but emits new spans from [span]`.file` in /// their appropriate relative positions. The [string] field contains only /// [span]`.text`, and [position], [line], and [column] are all relative to the /// span. factory SpanScanner.within(FileSpan span) = RelativeSpanScanner; /// Creates a [FileSpan] representing the source range between [startState] /// and the current position. FileSpan spanFrom(LineScannerState startState, [LineScannerState endState]) { var endPosition = endState == null ? position : endState.position; return _sourceFile.span(startState.position, endPosition); } bool matches(Pattern pattern) { if (!super.matches(pattern)) { _lastSpan = null; return false; } _lastSpan = _sourceFile.span(position, lastMatch.end); return true; } void error(String message, {Match match, int position, int length}) { validateErrorArgs(string, match, position, length); if (match == null && position == null && length == null) match = lastMatch; position ??= match == null ? this.position : match.start; length ??= match == null ? 0 : match.end - match.start; var span = _sourceFile.span(position, position + length); throw StringScannerException(message, span, string); } } /// A class representing the state of a [SpanScanner]. class _SpanScannerState implements LineScannerState { /// The [SpanScanner] that created this. final SpanScanner _scanner; final int position; int get line => _scanner._sourceFile.getLine(position); int get column => _scanner._sourceFile.getColumn(position); _SpanScannerState(this._scanner, this.position); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/line_scanner.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/ascii.dart'; import 'string_scanner.dart'; // Note that much of this code is duplicated in eager_span_scanner.dart. /// A regular expression matching newlines across platforms. final _newlineRegExp = RegExp(r"\r\n?|\n"); /// A subclass of [StringScanner] that tracks line and column information. class LineScanner extends StringScanner { /// The scanner's current (zero-based) line number. int get line => _line; int _line = 0; /// The scanner's current (zero-based) column number. int get column => _column; int _column = 0; /// The scanner's state, including line and column information. /// /// This can be used to efficiently save and restore the state of the scanner /// when backtracking. A given [LineScannerState] is only valid for the /// [LineScanner] that created it. /// /// This does not include the scanner's match information. LineScannerState get state => LineScannerState._(this, position, line, column); /// Whether the current position is between a CR character and an LF /// charactet. bool get _betweenCRLF => peekChar(-1) == $cr && peekChar() == $lf; set state(LineScannerState state) { if (!identical(state._scanner, this)) { throw ArgumentError("The given LineScannerState was not returned by " "this LineScanner."); } super.position = state.position; _line = state.line; _column = state.column; } set position(int newPosition) { var oldPosition = position; super.position = newPosition; if (newPosition > oldPosition) { var newlines = _newlinesIn(string.substring(oldPosition, newPosition)); _line += newlines.length; if (newlines.isEmpty) { _column += newPosition - oldPosition; } else { _column = newPosition - newlines.last.end; } } else { var newlines = _newlinesIn(string.substring(newPosition, oldPosition)); if (_betweenCRLF) newlines.removeLast(); _line -= newlines.length; if (newlines.isEmpty) { _column -= oldPosition - newPosition; } else { _column = newPosition - string.lastIndexOf(_newlineRegExp, newPosition) - 1; } } } LineScanner(String string, {sourceUrl, int position}) : super(string, sourceUrl: sourceUrl, position: position); bool scanChar(int character) { if (!super.scanChar(character)) return false; _adjustLineAndColumn(character); return true; } int readChar() { var character = super.readChar(); _adjustLineAndColumn(character); return character; } /// Adjusts [_line] and [_column] after having consumed [character]. void _adjustLineAndColumn(int character) { if (character == $lf || (character == $cr && peekChar() != $lf)) { _line += 1; _column = 0; } else { _column += 1; } } bool scan(Pattern pattern) { if (!super.scan(pattern)) return false; var newlines = _newlinesIn(lastMatch[0]); _line += newlines.length; if (newlines.isEmpty) { _column += lastMatch[0].length; } else { _column = lastMatch[0].length - newlines.last.end; } return true; } /// Returns a list of [Match]es describing all the newlines in [text], which /// is assumed to end at [position]. List<Match> _newlinesIn(String text) { var newlines = _newlineRegExp.allMatches(text).toList(); if (_betweenCRLF) newlines.removeLast(); return newlines; } } /// A class representing the state of a [LineScanner]. class LineScannerState { /// The [LineScanner] that created this. final LineScanner _scanner; /// The position of the scanner in this state. final int position; /// The zero-based line number of the scanner in this state. final int line; /// The zero-based column number of the scanner in this state. final int column; LineScannerState._(this._scanner, this.position, this.line, this.column); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/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 'package:source_span/source_span.dart'; import 'string_scanner.dart'; /// An exception thrown by a [StringScanner] that failed to parse a string. class StringScannerException extends SourceSpanFormatException { String get source => super.source as String; /// The URL of the source file being parsed. /// /// This may be `null`, indicating that the source URL is unknown. Uri get sourceUrl => span.sourceUrl; StringScannerException(String message, SourceSpan span, String source) : super(message, span, source); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/string_scanner.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:meta/meta.dart'; import 'package:source_span/source_span.dart'; import 'exception.dart'; import 'utils.dart'; /// A class that scans through a string using [Pattern]s. class StringScanner { /// The URL of the source of the string being scanned. /// /// This is used for error reporting. It may be `null`, indicating that the /// source URL is unknown or unavailable. final Uri sourceUrl; /// The string being scanned through. final String string; /// The current position of the scanner in the string, in characters. int get position => _position; set position(int position) { if (position < 0 || position > string.length) { throw ArgumentError("Invalid position $position"); } _position = position; _lastMatch = null; } int _position = 0; /// The data about the previous match made by the scanner. /// /// If the last match failed, this will be `null`. Match get lastMatch { // Lazily unset [_lastMatch] so that we avoid extra assignments in // character-by-character methods that are used in core loops. if (_position != _lastMatchPosition) _lastMatch = null; return _lastMatch; } Match _lastMatch; int _lastMatchPosition; /// The portion of the string that hasn't yet been scanned. String get rest => string.substring(position); /// Whether the scanner has completely consumed [string]. bool get isDone => position == string.length; /// Creates a new [StringScanner] that starts scanning from [position]. /// /// [position] defaults to 0, the beginning of the string. [sourceUrl] is the /// URL of the source of the string being scanned, if available. It can be /// a [String], a [Uri], or `null`. StringScanner(this.string, {sourceUrl, int position}) : sourceUrl = sourceUrl is String ? Uri.parse(sourceUrl) : sourceUrl as Uri { if (position != null) this.position = position; } /// Consumes a single character and returns its character code. /// /// This throws a [FormatException] if the string has been fully consumed. It /// doesn't affect [lastMatch]. int readChar() { if (isDone) _fail("more input"); return string.codeUnitAt(_position++); } /// Returns the character code of the character [offset] away from [position]. /// /// [offset] defaults to zero, and may be negative to inspect already-consumed /// characters. /// /// This returns `null` if [offset] points outside the string. It doesn't /// affect [lastMatch]. int peekChar([int offset]) { offset ??= 0; var index = position + offset; if (index < 0 || index >= string.length) return null; return string.codeUnitAt(index); } /// If the next character in the string is [character], consumes it. /// /// Returns whether or not [character] was consumed. bool scanChar(int character) { if (isDone) return false; if (string.codeUnitAt(_position) != character) return false; _position++; return true; } /// If the next character in the string is [character], consumes it. /// /// If [character] could not be consumed, throws a [FormatException] /// describing the position of the failure. [name] is used in this error as /// the expected name of the character being matched; if it's `null`, the /// character itself is used instead. void expectChar(int character, {String name}) { if (scanChar(character)) return; if (name == null) { if (character == $backslash) { name = r'"\"'; } else if (character == $double_quote) { name = r'"\""'; } else { name = '"${String.fromCharCode(character)}"'; } } _fail(name); } /// If [pattern] matches at the current position of the string, scans forward /// until the end of the match. /// /// Returns whether or not [pattern] matched. bool scan(Pattern pattern) { var success = matches(pattern); if (success) { _position = _lastMatch.end; _lastMatchPosition = _position; } return success; } /// If [pattern] matches at the current position of the string, scans forward /// until the end of the match. /// /// If [pattern] did not match, throws a [FormatException] describing the /// position of the failure. [name] is used in this error as the expected name /// of the pattern being matched; if it's `null`, the pattern itself is used /// instead. void expect(Pattern pattern, {String name}) { if (scan(pattern)) return; if (name == null) { if (pattern is RegExp) { var source = pattern.pattern; name = "/$source/"; } else { name = pattern.toString().replaceAll("\\", "\\\\").replaceAll('"', '\\"'); name = '"$name"'; } } _fail(name); } /// If the string has not been fully consumed, this throws a /// [FormatException]. void expectDone() { if (isDone) return; _fail("no more input"); } /// Returns whether or not [pattern] matches at the current position of the /// string. /// /// This doesn't move the scan pointer forward. bool matches(Pattern pattern) { _lastMatch = pattern.matchAsPrefix(string, position); _lastMatchPosition = _position; return _lastMatch != null; } /// Returns the substring of [string] between [start] and [end]. /// /// Unlike [String.substring], [end] defaults to [position] rather than the /// end of the string. String substring(int start, [int end]) { end ??= position; return string.substring(start, end); } /// Throws a [FormatException] with [message] as well as a detailed /// description of the location of the error in the string. /// /// [match] is the match information for the span of the string with which the /// error is associated. This should be a match returned by this scanner's /// [lastMatch] property. By default, the error is associated with the last /// match. /// /// If [position] and/or [length] are passed, they are used as the error span /// instead. If only [length] is passed, [position] defaults to the current /// position; if only [position] is passed, [length] defaults to 0. /// /// It's an error to pass [match] at the same time as [position] or [length]. @alwaysThrows void error(String message, {Match match, int position, int length}) { validateErrorArgs(string, match, position, length); if (match == null && position == null && length == null) match = lastMatch; position ??= match == null ? this.position : match.start; length ??= match == null ? 0 : match.end - match.start; var sourceFile = SourceFile.fromString(string, url: sourceUrl); var span = sourceFile.span(position, position + length); throw StringScannerException(message, span, string); } // TODO(nweiz): Make this handle long lines more gracefully. /// Throws a [FormatException] describing that [name] is expected at the /// current position in the string. void _fail(String name) { error("expected $name.", position: position, length: 0); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/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 'string_scanner.dart'; /// Validates the arguments passed to [StringScanner.error]. void validateErrorArgs(String string, Match match, int position, int length) { if (match != null && (position != null || length != null)) { throw ArgumentError("Can't pass both match and position/length."); } if (position != null) { if (position < 0) { throw RangeError("position must be greater than or equal to 0."); } else if (position > string.length) { throw RangeError("position must be less than or equal to the " "string length."); } } if (length != null && length < 0) { throw RangeError("length must be greater than or equal to 0."); } if (position != null && length != null && position + length > string.length) { throw RangeError("position plus length must not go beyond the end of " "the string."); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/relative_span_scanner.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:source_span/source_span.dart'; import 'exception.dart'; import 'line_scanner.dart'; import 'span_scanner.dart'; import 'string_scanner.dart'; import 'utils.dart'; /// A [SpanScanner] that scans within an existing [FileSpan]. /// /// This re-implements chunks of [SpanScanner] rather than using a dummy span or /// inheritance because scanning is often a performance-critical operation, so /// it's important to avoid adding extra overhead when relative scanning isn't /// needed. class RelativeSpanScanner extends StringScanner implements SpanScanner { /// The source of the scanner. /// /// This caches line break information and is used to generate [SourceSpan]s. final SourceFile _sourceFile; /// The start location of the span within which this scanner is scanning. /// /// This is used to convert between span-relative and file-relative fields. final FileLocation _startLocation; int get line => _sourceFile.getLine(_startLocation.offset + position) - _startLocation.line; int get column { var line = _sourceFile.getLine(_startLocation.offset + position); var column = _sourceFile.getColumn(_startLocation.offset + position, line: line); return line == _startLocation.line ? column - _startLocation.column : column; } LineScannerState get state => _SpanScannerState(this, position); set state(LineScannerState state) { if (state is! _SpanScannerState || !identical((state as _SpanScannerState)._scanner, this)) { throw ArgumentError("The given LineScannerState was not returned by " "this LineScanner."); } position = state.position; } FileSpan get lastSpan => _lastSpan; FileSpan _lastSpan; FileLocation get location => _sourceFile.location(_startLocation.offset + position); FileSpan get emptySpan => location.pointSpan(); RelativeSpanScanner(FileSpan span) : _sourceFile = span.file, _startLocation = span.start, super(span.text, sourceUrl: span.sourceUrl); FileSpan spanFrom(LineScannerState startState, [LineScannerState endState]) { var endPosition = endState == null ? position : endState.position; return _sourceFile.span(_startLocation.offset + startState.position, _startLocation.offset + endPosition); } bool matches(Pattern pattern) { if (!super.matches(pattern)) { _lastSpan = null; return false; } _lastSpan = _sourceFile.span(_startLocation.offset + position, _startLocation.offset + lastMatch.end); return true; } void error(String message, {Match match, int position, int length}) { validateErrorArgs(string, match, position, length); if (match == null && position == null && length == null) match = lastMatch; position ??= match == null ? this.position : match.start; length ??= match == null ? 1 : match.end - match.start; var span = _sourceFile.span(_startLocation.offset + position, _startLocation.offset + position + length); throw StringScannerException(message, span, string); } } /// A class representing the state of a [SpanScanner]. class _SpanScannerState implements LineScannerState { /// The [SpanScanner] that created this. final RelativeSpanScanner _scanner; final int position; int get line => _scanner._sourceFile.getLine(position); int get column => _scanner._sourceFile.getColumn(position); _SpanScannerState(this._scanner, this.position); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/string_scanner/src/eager_span_scanner.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 'package:charcode/ascii.dart'; import 'line_scanner.dart'; import 'span_scanner.dart'; // TODO(nweiz): Currently this duplicates code in line_scanner.dart. Once // sdk#23770 is fully complete, we should move the shared code into a mixin. /// A regular expression matching newlines across platforms. final _newlineRegExp = RegExp(r"\r\n?|\n"); /// A [SpanScanner] that tracks the line and column eagerly, like [LineScanner]. class EagerSpanScanner extends SpanScanner { int get line => _line; int _line = 0; int get column => _column; int _column = 0; LineScannerState get state => _EagerSpanScannerState(this, position, line, column); bool get _betweenCRLF => peekChar(-1) == $cr && peekChar() == $lf; set state(LineScannerState state) { if (state is! _EagerSpanScannerState || !identical((state as _EagerSpanScannerState)._scanner, this)) { throw ArgumentError("The given LineScannerState was not returned by " "this LineScanner."); } super.position = state.position; _line = state.line; _column = state.column; } set position(int newPosition) { var oldPosition = position; super.position = newPosition; if (newPosition > oldPosition) { var newlines = _newlinesIn(string.substring(oldPosition, newPosition)); _line += newlines.length; if (newlines.isEmpty) { _column += newPosition - oldPosition; } else { _column = newPosition - newlines.last.end; } } else { var newlines = _newlinesIn(string.substring(newPosition, oldPosition)); if (_betweenCRLF) newlines.removeLast(); _line -= newlines.length; if (newlines.isEmpty) { _column -= oldPosition - newPosition; } else { _column = newPosition - string.lastIndexOf(_newlineRegExp, newPosition) - 1; } } } EagerSpanScanner(String string, {sourceUrl, int position}) : super(string, sourceUrl: sourceUrl, position: position); bool scanChar(int character) { if (!super.scanChar(character)) return false; _adjustLineAndColumn(character); return true; } int readChar() { var character = super.readChar(); _adjustLineAndColumn(character); return character; } /// Adjusts [_line] and [_column] after having consumed [character]. void _adjustLineAndColumn(int character) { if (character == $lf || (character == $cr && peekChar() != $lf)) { _line += 1; _column = 0; } else { _column += 1; } } bool scan(Pattern pattern) { if (!super.scan(pattern)) return false; var newlines = _newlinesIn(lastMatch[0]); _line += newlines.length; if (newlines.isEmpty) { _column += lastMatch[0].length; } else { _column = lastMatch[0].length - newlines.last.end; } return true; } /// Returns a list of [Match]es describing all the newlines in [text], which /// is assumed to end at [position]. List<Match> _newlinesIn(String text) { var newlines = _newlineRegExp.allMatches(text).toList(); if (_betweenCRLF) newlines.removeLast(); return newlines; } } /// A class representing the state of an [EagerSpanScanner]. class _EagerSpanScannerState implements LineScannerState { final EagerSpanScanner _scanner; final int position; final int line; final int column; _EagerSpanScannerState(this._scanner, this.position, this.line, this.column); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/build.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/analyzer/resolver.dart'; export 'src/asset/exceptions.dart'; export 'src/asset/id.dart'; export 'src/asset/reader.dart'; export 'src/asset/writer.dart'; export 'src/builder/build_step.dart' hide NoOpStageTracker; export 'src/builder/builder.dart'; export 'src/builder/exceptions.dart'; export 'src/builder/file_deleting_builder.dart' show FileDeletingBuilder; export 'src/builder/logging.dart' show log; export 'src/builder/multiplexing_builder.dart'; export 'src/builder/post_process_build_step.dart' show PostProcessBuildStep; export 'src/builder/post_process_builder.dart' show PostProcessBuilder, PostProcessBuilderFactory; export 'src/generate/expected_outputs.dart'; export 'src/generate/run_builder.dart'; export 'src/generate/run_post_process_builder.dart' show runPostProcessBuilder; export 'src/resource/resource.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/resource/resource.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'; typedef CreateInstance<T> = FutureOr<T> Function(); typedef DisposeInstance<T> = FutureOr<void> Function(T instance); typedef BeforeExit = FutureOr<void> Function(); /// A [Resource] encapsulates the logic for creating and disposing of some /// expensive object which has a lifecycle. /// /// Actual [Resource]s should be retrieved using `BuildStep#fetchResource`. /// /// Build system implementations should be the only users that directly /// instantiate a [ResourceManager] since they can handle the lifecycle /// guarantees in a sane way. class Resource<T> { /// Factory method which creates an instance of this resource. final CreateInstance<T> _create; /// Optional method which is given an existing instance that is ready to be /// disposed. final DisposeInstance<T> _userDispose; /// Optional method which is called before the process is going to exit. /// /// This allows resources to do any final cleanup, and is not given an /// instance. final BeforeExit _userBeforeExit; /// A Future instance of this resource if one has ever been requested. final _instanceByManager = <ResourceManager, Future<T>>{}; Resource(this._create, {DisposeInstance<T> dispose, BeforeExit beforeExit}) : _userDispose = dispose, _userBeforeExit = beforeExit; /// Fetches an actual instance of this resource for [manager]. Future<T> _fetch(ResourceManager manager) => _instanceByManager.putIfAbsent(manager, () async => await _create()); /// Disposes the actual instance of this resource for [manager] if present. Future<void> _dispose(ResourceManager manager) { if (!_instanceByManager.containsKey(manager)) return Future.value(null); var oldInstance = _fetch(manager); _instanceByManager.remove(manager); if (_userDispose != null) { return oldInstance.then(_userDispose); } else { return Future.value(null); } } } /// Manages fetching and disposing of a group of [Resource]s. /// /// This is an internal only API which should only be used by build system /// implementations and not general end users. Instead end users should use /// the `buildStep#fetchResource` method to get [Resource]s. class ResourceManager { final _resources = Set<Resource<void>>(); /// The [Resource]s that we need to call `beforeExit` on. /// /// We have to hang on to these forever, but they should be small in number, /// and we don't hold on to the actual created instances, just the [Resource] /// instances. final _resourcesWithBeforeExit = Set<Resource<void>>(); /// Fetches an instance of [resource]. Future<T> fetch<T>(Resource<T> resource) async { if (resource._userBeforeExit != null) { _resourcesWithBeforeExit.add(resource); } _resources.add(resource); return resource._fetch(this); } /// Disposes of all [Resource]s fetched since the last call to [disposeAll]. Future<Null> disposeAll() { var done = Future.wait(_resources.map((r) => r._dispose(this))); _resources.clear(); return done.then((_) => null); } /// Invokes the `beforeExit` callbacks of all [Resource]s that had one. Future<Null> beforeExit() async { await Future.wait(_resourcesWithBeforeExit.map((r) async { if (r._userBeforeExit != null) return r._userBeforeExit(); })); _resourcesWithBeforeExit.clear(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/generate/run_post_process_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:logging/logging.dart'; import 'package:meta/meta.dart'; import '../asset/id.dart'; import '../asset/reader.dart'; import '../asset/writer.dart'; import '../builder/logging.dart'; import '../builder/post_process_build_step.dart'; import '../builder/post_process_builder.dart'; /// Run [builder] with [inputId] as the primary input. /// /// [addAsset] should update the build systems knowledge of what assets exist. /// If an asset should not be written this function should throw. /// [deleteAsset] should remove the asset from the build system, it will not be /// deleted on disk since the `writer` has no mechanism for delete. Future<void> runPostProcessBuilder(PostProcessBuilder builder, AssetId inputId, AssetReader reader, AssetWriter writer, Logger logger, {@required void Function(AssetId) addAsset, @required void Function(AssetId) deleteAsset}) async { await scopeLogAsync(() async { var buildStep = postProcessBuildStep(inputId, reader, writer, addAsset, deleteAsset); try { await builder.build(buildStep); } finally { await buildStep.complete(); } }, logger); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/generate/run_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:logging/logging.dart'; import '../analyzer/resolver.dart'; import '../asset/id.dart'; import '../asset/reader.dart'; import '../asset/writer.dart'; import '../builder/build_step.dart'; import '../builder/build_step_impl.dart'; import '../builder/builder.dart'; import '../builder/logging.dart'; import '../resource/resource.dart'; import 'expected_outputs.dart'; /// Run [builder] with each asset in [inputs] as the primary input. /// /// Builds for all inputs are run asynchronously and ordering is not guaranteed. /// The [log] instance inside the builds will be scoped to [logger] which is /// defaulted to a [Logger] name 'runBuilder'. /// /// If a [resourceManager] is provided it will be used and it will not be /// automatically disposed of (its up to the caller to dispose of it later). If /// one is not provided then one will be created and disposed at the end of /// this function call. /// /// If [reportUnusedAssetsForInput] is provided then all calls to /// `BuildStep.reportUnusedAssets` in [builder] will be forwarded to this /// function with the associated primary input. Future<void> runBuilder(Builder builder, Iterable<AssetId> inputs, AssetReader reader, AssetWriter writer, Resolvers resolvers, {Logger logger, ResourceManager resourceManager, String rootPackage, StageTracker stageTracker = NoOpStageTracker.instance, void Function(AssetId input, Iterable<AssetId> assets) reportUnusedAssetsForInput}) async { var shouldDisposeResourceManager = resourceManager == null; resourceManager ??= ResourceManager(); logger ??= Logger('runBuilder'); //TODO(nbosch) check overlapping outputs? Future<void> buildForInput(AssetId input) async { var outputs = expectedOutputs(builder, input); if (outputs.isEmpty) return; var buildStep = BuildStepImpl(input, outputs, reader, writer, rootPackage ?? input.package, resolvers, resourceManager, stageTracker: stageTracker, reportUnusedAssets: reportUnusedAssetsForInput == null ? null : (assets) => reportUnusedAssetsForInput(input, assets)); try { await builder.build(buildStep); } finally { await buildStep.complete(); } } await scopeLogAsync(() => Future.wait(inputs.map(buildForInput)), logger); if (shouldDisposeResourceManager) { await resourceManager.disposeAll(); await resourceManager.beforeExit(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/generate/expected_outputs.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 '../asset/id.dart'; import '../builder/builder.dart'; /// Collects the expected AssetIds created by [builder] when given [input] based /// on the extension configuration. Iterable<AssetId> expectedOutputs(Builder builder, AssetId input) { var matchingExtensions = builder.buildExtensions.keys.where((e) => input.path.endsWith(e)); return matchingExtensions .expand((e) => _replaceExtensions(input, e, builder.buildExtensions[e])); } Iterable<AssetId> _replaceExtensions( AssetId assetId, String oldExtension, List<String> newExtensions) => newExtensions.map((n) => _replaceExtension(assetId, oldExtension, n)); AssetId _replaceExtension( AssetId assetId, String oldExtension, String newExtension) { var path = assetId.path; assert(path.endsWith(oldExtension)); return AssetId( assetId.package, path.replaceRange( path.length - oldExtension.length, path.length, newExtension)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/analyzer/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:async'; import 'package:analyzer/dart/element/element.dart'; import '../asset/id.dart'; import '../builder/build_step.dart'; /// Standard interface for resolving Dart source code as part of a build. abstract class Resolver { /// Returns whether [assetId] represents an Dart library file. /// /// This will be `false` in the case where the file is not Dart source code, /// or is a `part of` file (not a standalone Dart library). Future<bool> isLibrary(AssetId assetId); /// All libraries recursively accessible from the entry point or subsequent /// calls to [libraryFor] and [isLibrary]. /// /// **NOTE**: This includes all Dart SDK libraries as well. Stream<LibraryElement> get libraries; /// Returns a resolved library representing the file defined in [assetId]. /// /// * Throws [NonLibraryAssetException] if [assetId] is not a Dart library. Future<LibraryElement> libraryFor(AssetId assetId); /// Returns the first resolved library identified by [libraryName]. /// /// A library is resolved if it's recursively accessible from the entry point /// or subsequent calls to [libraryFor] and [isLibrary]. If no library can be /// found, returns `null`. /// /// **NOTE**: In general, its recommended to use [libraryFor] with an absolute /// asset id instead of a named identifier that has the possibility of not /// being unique. Future<LibraryElement> findLibraryByName(String libraryName); /// Returns the [AssetId] of the Dart library or part declaring [element]. /// /// If [element] is defined in the SDK or in a summary throws /// `UnresolvableAssetException`, although a non-throwing return here does not /// guarantee that the asset is readable. /// /// The returned asset is not necessarily the asset that should be imported to /// use the element, it may be a part file instead of the library. Future<AssetId> assetIdForElement(Element element); } /// A resolver that should be manually released at the end of a build step. abstract class ReleasableResolver implements Resolver { /// Release this resolver so it can be updated by following build steps. void release(); } /// A factory that returns a resolver for a given [BuildStep]. abstract class Resolvers { const Resolvers(); Future<ReleasableResolver> get(BuildStep buildStep); /// Reset the state of any caches within [Resolver] instances produced by /// this [Resolvers]. /// /// In between calls to [reset] no Assets should change, so every call to /// `BuildStep.readAsString` for a given AssetId should return identical /// contents. Any time an Asset's contents may change [reset] must be called. void reset() {} } /// Thrown when attempting to read a non-Dart library in a [Resolver]. class NonLibraryAssetException implements Exception { final AssetId assetId; const NonLibraryAssetException(this.assetId); @override String toString() => 'Asset [$assetId] is not a Dart library. ' 'It may be a part file or a file without Dart source code.'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/asset/exceptions.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 'id.dart'; class AssetNotFoundException implements Exception { final AssetId assetId; AssetNotFoundException(this.assetId); @override String toString() => 'AssetNotFoundException: $assetId'; } class PackageNotFoundException implements Exception { final String name; PackageNotFoundException(this.name); @override String toString() => 'PackageNotFoundException: $name'; } class InvalidOutputException implements Exception { final AssetId assetId; final String message; InvalidOutputException(this.assetId, this.message); @override String toString() => 'InvalidOutputException: $assetId\n$message'; } class InvalidInputException implements Exception { final AssetId assetId; InvalidInputException(this.assetId); @override String toString() => 'InvalidInputException: $assetId\n' 'For package dependencies, only files under `lib` may be used as inputs.'; } class BuildStepCompletedException implements Exception { @override String toString() => 'BuildStepCompletedException: ' 'Attempt to use a BuildStep after is has completed'; } class UnresolvableAssetException implements Exception { final String description; const UnresolvableAssetException(this.description); @override String toString() => 'Unresolvable Asset from $description.'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/asset/writer.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'id.dart'; /// Standard interface for writing an asset into a package's outputs. abstract class AssetWriter { /// Writes [bytes] to a binary file located at [id]. /// /// Returns a [Future] that completes after writing the asset out. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws an `InvalidOutputException` if the output was not valid. Future<void> writeAsBytes(AssetId id, List<int> bytes); /// Writes [contents] to a text file located at [id] with [encoding]. /// /// Returns a [Future] that completes after writing the asset out. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws an `InvalidOutputException` if the output was not valid. Future<void> writeAsString(AssetId id, String contents, {Encoding encoding = utf8}); } /// An [AssetWriter] which tracks all [assetsWritten] during its lifetime. class AssetWriterSpy implements AssetWriter { final AssetWriter _delegate; final _assetsWritten = Set<AssetId>(); AssetWriterSpy(this._delegate); Iterable<AssetId> get assetsWritten => _assetsWritten; @override Future<void> writeAsBytes(AssetId id, List<int> bytes) { _assetsWritten.add(id); return _delegate.writeAsBytes(id, bytes); } @override Future<void> writeAsString(AssetId id, String contents, {Encoding encoding = utf8}) { _assetsWritten.add(id); return _delegate.writeAsString(id, contents, encoding: encoding); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/asset/id.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; /// Identifies an asset within a package. class AssetId implements Comparable<AssetId> { /// The name of the package containing this asset. final String package; /// The path to the asset relative to the root directory of [package]. /// /// Source (i.e. read from disk) and generated (i.e. the output of a /// `Builder`) assets all have paths. Even intermediate assets that are /// generated and then consumed by later transformations will still have a /// path used to identify it. /// /// Asset paths always use forward slashes as path separators, regardless of /// the host platform. Asset paths will always be within their package, that /// is they will never contain "../". final String path; /// Splits [path] into its components. List<String> get pathSegments => p.url.split(path); /// The file extension of the asset, if it has one, including the ".". String get extension => p.extension(path); /// Creates a new [AssetId] at [path] within [package]. /// /// The [path] will be normalized: any backslashes will be replaced with /// forward slashes (regardless of host OS) and "." and ".." will be removed /// where possible. AssetId(this.package, String path) : path = _normalizePath(path); /// Creates a new [AssetId] from an [uri] String. /// /// This gracefully handles `package:` or `asset:` URIs. /// /// Resolve a `package:` URI when creating an [AssetId] from an `import` or /// `export` directive pointing to a package's _lib_ directory: /// ```dart /// AssetId assetOfDirective(UriReferencedElement element) { /// return new AssetId.resolve(element.uri); /// } /// ``` /// /// When resolving a relative URI with no scheme, specifyg the origin asset /// ([from]) - otherwise an [ArgumentError] will be thrown. /// ```dart /// AssetId assetOfDirective(AssetId origin, UriReferencedElement element) { /// return new AssetId.resolve(element.uri, from: origin); /// } /// ``` /// /// `asset:` uris have the format '$package/$path', including the top level /// directory. factory AssetId.resolve(String uri, {AssetId from}) { final parsedUri = Uri.parse(uri); if (parsedUri.hasScheme) { if (parsedUri.scheme == 'package') { return AssetId(parsedUri.pathSegments.first, p.url.join('lib', p.url.joinAll(parsedUri.pathSegments.skip(1)))); } else if (parsedUri.scheme == 'asset') { return AssetId(parsedUri.pathSegments.first, p.url.joinAll(parsedUri.pathSegments.skip(1))); } throw UnsupportedError( 'Cannot resolve $uri; only "package" and "asset" schemes supported'); } if (from == null) { throw ArgumentError.value(from, 'from', 'An AssetId "from" must be specified to resolve a relative URI'); } return AssetId(p.url.normalize(from.package), p.url.join(p.url.dirname(from.path), uri)); } /// Parses an [AssetId] string of the form "package|path/to/asset.txt". /// /// The [path] will be normalized: any backslashes will be replaced with /// forward slashes (regardless of host OS) and "." and ".." will be removed /// where possible. factory AssetId.parse(String description) { var parts = description.split('|'); if (parts.length != 2) { throw FormatException('Could not parse "$description".'); } if (parts[0].isEmpty) { throw FormatException( 'Cannot have empty package name in "$description".'); } if (parts[1].isEmpty) { throw FormatException('Cannot have empty path in "$description".'); } return AssetId(parts[0], parts[1]); } /// A `package:` URI suitable for use directly with other systems if this /// asset is under it's package's `lib/` directory, else an `asset:` URI /// suitable for use within build tools. Uri get uri => _uri ??= _constructUri(this); Uri _uri; /// Deserializes an [AssetId] from [data], which must be the result of /// calling [serialize] on an existing [AssetId]. AssetId.deserialize(List<dynamic> data) : package = data[0] as String, path = data[1] as String; /// Returns `true` if [other] is an [AssetId] with the same package and path. @override bool operator ==(Object other) => other is AssetId && package == other.package && path == other.path; @override int get hashCode => package.hashCode ^ path.hashCode; @override int compareTo(AssetId other) { var packageComp = package.compareTo(other.package); if (packageComp != 0) return packageComp; return path.compareTo(other.path); } /// Returns a new [AssetId] with the same [package] as this one and with the /// [path] extended to include [extension]. AssetId addExtension(String extension) => AssetId(package, '$path$extension'); /// Returns a new [AssetId] with the same [package] and [path] as this one /// but with file extension [newExtension]. AssetId changeExtension(String newExtension) => AssetId(package, p.withoutExtension(path) + newExtension); @override String toString() => '$package|$path'; /// Serializes this [AssetId] to an object that can be sent across isolates /// and passed to [AssetId.deserialize]. Object serialize() => [package, path]; } String _normalizePath(String path) { if (p.isAbsolute(path)) { throw ArgumentError.value(path, 'Asset paths must be relative.'); } // Normalize path separators so that they are always "/" in the AssetID. path = path.replaceAll(r'\', '/'); // Collapse "." and "..". final collapsed = p.posix.normalize(path); if (collapsed.startsWith('../')) { throw ArgumentError.value( path, 'Asset paths may not reach outside the package.'); } return collapsed; } Uri _constructUri(AssetId id) { final originalSegments = id.pathSegments; final isLib = originalSegments.first == 'lib'; final scheme = isLib ? 'package' : 'asset'; final pathSegments = isLib ? originalSegments.skip(1) : originalSegments; return Uri(scheme: scheme, pathSegments: [id.package]..addAll(pathSegments)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/asset/reader.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:crypto/crypto.dart'; import 'package:convert/convert.dart'; import 'package:glob/glob.dart'; import 'id.dart'; /// Standard interface for reading an asset within in a package. /// /// An [AssetReader] is required when calling the `runBuilder` method. abstract class AssetReader { /// Returns a [Future] that completes with the bytes of a binary asset. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws a `AssetNotFoundException` if `id.path` is not found. Future<List<int>> readAsBytes(AssetId id); /// Returns a [Future] that completes with the contents of a text asset. /// /// When decoding as text uses [encoding], or [utf8] is not specified. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws a `AssetNotFoundException` if `id.path` is not found. Future<String> readAsString(AssetId id, {Encoding encoding}); /// Indicates whether asset at [id] is readable. Future<bool> canRead(AssetId id); /// Returns all readable assets matching [glob] under the current package. Stream<AssetId> findAssets(Glob glob); /// Returns a [Digest] representing a hash of the contents of [id]. /// /// The digests should include the asset ID as well as the content of the /// file, as some build systems may rely on the digests for two files being /// different, even if their content is the same. /// /// This should be treated as a transparent [Digest] and the implementation /// may differ based on the current build system being used. Future<Digest> digest(AssetId id) async { var digestSink = AccumulatorSink<Digest>(); md5.startChunkedConversion(digestSink) ..add(await readAsBytes(id)) ..add(id.toString().codeUnits) ..close(); return digestSink.events.first; } } /// The same as an `AssetReader`, except that `findAssets` takes an optional /// argument `package` which allows you to glob any package. /// /// This should not be exposed to end users generally, but can be used by /// different build system implementations. abstract class MultiPackageAssetReader extends AssetReader { /// Returns all readable assets matching [glob] under [package]. /// /// Some implementations may require the [package] argument, while others /// may have a sane default. @override Stream<AssetId> findAssets(Glob glob, {String package}); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/logging.dart
import 'dart:async'; import 'package:logging/logging.dart'; const Symbol logKey = #buildLog; final _default = Logger('build.fallback'); /// The log instance for the currently running BuildStep. /// /// Will be `null` when not running within a build. Logger get log => Zone.current[logKey] as Logger ?? _default; /// Runs [fn] in an error handling [Zone]. /// /// Any calls to [print] will be logged with `log.warning`, and any errors will /// be logged with `log.severe`. /// /// Completes with the first error or result of `fn`, whichever comes first. Future<T> scopeLogAsync<T>(Future<T> fn(), Logger log) { var done = Completer<T>(); runZoned(fn, zoneSpecification: ZoneSpecification(print: (self, parent, zone, message) { log.warning(message); }), zoneValues: {logKey: log}, onError: (Object e, StackTrace s) { log.severe('', e, s); if (done.isCompleted) return; done.completeError(e, s); }).then((result) { if (done.isCompleted) return; done.complete(result); }); return done.future; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/exceptions.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 '../asset/id.dart'; class UnexpectedOutputException implements Exception { final AssetId assetId; final Iterable<AssetId> expected; UnexpectedOutputException(this.assetId, {this.expected}); @override String toString() => 'UnexpectedOutputException: $assetId' '${expected == null ? '' : '\nExpected only: $expected'}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/file_deleting_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:glob/glob.dart'; import 'post_process_build_step.dart'; import 'post_process_builder.dart'; /// A [PostProcessBuilder] which can be configured to consume any input /// extensions and always deletes it primary input. class FileDeletingBuilder implements PostProcessBuilder { @override final List<String> inputExtensions; final bool isEnabled; final List<Glob> exclude; const FileDeletingBuilder(this.inputExtensions, {this.isEnabled = true}) : exclude = const []; FileDeletingBuilder.withExcludes( this.inputExtensions, Iterable<String> exclude, {this.isEnabled = true}) : exclude = exclude?.map((s) => Glob(s))?.toList() ?? const []; @override FutureOr<Null> build(PostProcessBuildStep buildStep) { if (!isEnabled) return null; if (exclude.any((g) => g.matches(buildStep.inputId.path))) return null; buildStep.deletePrimaryInput(); return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/post_process_build_step.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:async/async.dart'; import 'package:build/build.dart'; import 'package:crypto/src/digest.dart'; // This is not exported to hack around a package-private constructor. PostProcessBuildStep postProcessBuildStep( AssetId inputId, AssetReader reader, AssetWriter writer, void Function(AssetId) addAsset, void Function(AssetId) deleteAsset) => PostProcessBuildStep._(inputId, reader, writer, addAsset, deleteAsset); /// A simplified [BuildStep] which can only read its primary input, and can't /// get a [Resolver] or any [Resource]s, at least for now. class PostProcessBuildStep { final AssetId inputId; final AssetReader _reader; final AssetWriter _writer; final void Function(AssetId) _addAsset; final void Function(AssetId) _deleteAsset; /// The result of any writes which are starting during this step. final _writeResults = <Future<Result<void>>>[]; PostProcessBuildStep._(this.inputId, this._reader, this._writer, this._addAsset, this._deleteAsset); Future<Digest> digest(AssetId id) => inputId == id ? _reader.digest(id) : Future.error(InvalidInputException(id)); Future<List<int>> readInputAsBytes() => _reader.readAsBytes(inputId); Future<String> readInputAsString({Encoding encoding = utf8}) => _reader.readAsString(inputId, encoding: encoding); Future<void> writeAsBytes(AssetId id, FutureOr<List<int>> bytes) { _addAsset(id); var done = _futureOrWrite(bytes, (List<int> b) => _writer.writeAsBytes(id, b)); _writeResults.add(Result.capture(done)); return done; } Future<void> writeAsString(AssetId id, FutureOr<String> content, {Encoding encoding = utf8}) { _addAsset(id); var done = _futureOrWrite(content, (String c) => _writer.writeAsString(id, c, encoding: encoding)); _writeResults.add(Result.capture(done)); return done; } /// Marks an asset for deletion in the post process step. void deletePrimaryInput() { _deleteAsset(inputId); } /// Waits for work to finish and cleans up resources. /// /// This method should be called after a build has completed. After the /// returned [Future] completes then all outputs have been written. Future<void> complete() async { await Future.wait(_writeResults.map(Result.release)); } } Future<void> _futureOrWrite<T>( FutureOr<T> content, Future<void> write(T content)) => (content is Future<T>) ? content.then(write) : write(content as T);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/build_step.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:convert'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer/resolver.dart'; import '../asset/id.dart'; import '../asset/reader.dart'; import '../asset/writer.dart'; import '../resource/resource.dart'; /// A single step in a build process. /// /// This represents a single [inputId], logic around resolving as a library, /// and the ability to read and write assets as allowed by the underlying build /// system. abstract class BuildStep implements AssetReader, AssetWriter { /// The primary for this build step. AssetId get inputId; /// Resolved library defined by [inputId]. /// /// Throws [NonLibraryAssetException] if [inputId] is not a Dart library file. Future<LibraryElement> get inputLibrary; /// Gets an instance provided by [resource] which is guaranteed to be unique /// within a single build, and may be reused across build steps within a /// build if the implementation allows. /// /// It is also guaranteed that [resource] will be disposed before the next /// build starts (and the dispose callback will be invoked if provided). Future<T> fetchResource<T>(Resource<T> resource); /// Writes [bytes] to a binary file located at [id]. /// /// Returns a [Future] that completes after writing the asset out. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws an `InvalidOutputException` if the output was not valid. /// /// **NOTE**: Most `Builder` implementations should not need to `await` this /// Future since the runner will be responsible for waiting until all outputs /// are written. @override Future<void> writeAsBytes(AssetId id, FutureOr<List<int>> bytes); /// Writes [contents] to a text file located at [id] with [encoding]. /// /// Returns a [Future] that completes after writing the asset out. /// /// * Throws a `PackageNotFoundException` if `id.package` is not found. /// * Throws an `InvalidOutputException` if the output was not valid. /// /// **NOTE**: Most `Builder` implementations should not need to `await` this /// Future since the runner will be responsible for waiting until all outputs /// are written. @override Future<void> writeAsString(AssetId id, FutureOr<String> contents, {Encoding encoding = utf8}); /// A [Resolver] for [inputId]. Resolver get resolver; /// Tracks performance of [action] separately. /// /// If performance tracking is enabled, tracks [action] as separate stage /// identified by [label]. Otherwise just runs [action]. /// /// You can specify [action] as [isExternal] (waiting for some external /// resource like network, process or file IO). In that case [action] will /// be tracked as single time slice from the beginning of the stage till /// completion of Future returned by [action]. /// /// Otherwise all separate time slices of asynchronous execution will be /// tracked, but waiting for external resources will be a gap. /// /// Returns value returned by [action]. /// [action] can be async function returning [Future]. T trackStage<T>(String label, T Function() action, {bool isExternal = false}); /// Indicates that [ids] were read but their content has no impact on the /// outputs of this step. /// /// **WARNING**: Using this introduces serious risk of non-hermetic builds. /// /// If these files change or become unreadable on the next build this build /// step may not run. /// /// **Note**: This is not guaranteed to have any effect and it should be /// assumed to be a no-op by default. Implementations must explicitly /// choose to support this feature. void reportUnusedAssets(Iterable<AssetId> ids); } abstract class StageTracker { T trackStage<T>(String label, T Function() action, {bool isExternal = false}); } class NoOpStageTracker implements StageTracker { static const StageTracker instance = NoOpStageTracker._(); @override T trackStage<T>(String label, T Function() action, {bool isExternal = false}) => action(); const NoOpStageTracker._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/post_process_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 'builder.dart'; import 'post_process_build_step.dart'; /// A builder which runes in a special phase at the end of the build. /// /// They are different from a normal [Builder] in several ways: /// /// - They don't have to declare output extensions, and can output any file as /// long as it doesn't conflict with an existing one. /// - They can only read their primary input. /// - They will not cause optional actions to run - they will only run on assets /// that were built as a part of the normal build. /// - They all run in a single phase, and thus can not see the outputs of any /// other [PostProcessBuilder]s. /// - Because they run in a separate phase, after other builders, none of thier /// outputs can be consumed by [Builder]s. /// /// Because of these restrictions, these builders should never be used to output /// Dart files, or any other file which would should be processed by normal /// [Builder]s. abstract class PostProcessBuilder { /// The extensions this builder expects for its inputs. Iterable<String> get inputExtensions; /// Generates the outputs and deletes for [buildStep]. FutureOr<void> build(PostProcessBuildStep buildStep); } typedef PostProcessBuilderFactory = PostProcessBuilder Function(BuilderOptions);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/build_step_impl.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:convert'; import 'package:analyzer/dart/element/element.dart'; import 'package:async/async.dart'; import 'package:build/src/builder/build_step.dart'; import 'package:crypto/crypto.dart'; import 'package:glob/glob.dart'; import '../analyzer/resolver.dart'; import '../asset/exceptions.dart'; import '../asset/id.dart'; import '../asset/reader.dart'; import '../asset/writer.dart'; import '../resource/resource.dart'; import 'build_step.dart'; import 'exceptions.dart'; /// A single step in the build processes. /// /// This represents a single input and its expected and real outputs. It also /// handles tracking of dependencies. class BuildStepImpl implements BuildStep { final Resolvers _resolvers; final StageTracker _stageTracker; /// The primary input id for this build step. @override final AssetId inputId; @override Future<LibraryElement> get inputLibrary async { if (_isComplete) throw BuildStepCompletedException(); return resolver.libraryFor(inputId); } /// The list of all outputs which are expected/allowed to be output from this /// step. final Set<AssetId> _expectedOutputs; /// The result of any writes which are starting during this step. final _writeResults = <Future<Result<void>>>[]; /// Used internally for reading files. final AssetReader _reader; /// Used internally for writing files. final AssetWriter _writer; /// The current root package, used for input/output validation. final String _rootPackage; final ResourceManager _resourceManager; bool _isComplete = false; final void Function(Iterable<AssetId>) _reportUnusedAssets; BuildStepImpl(this.inputId, Iterable<AssetId> expectedOutputs, this._reader, this._writer, this._rootPackage, this._resolvers, this._resourceManager, {StageTracker stageTracker, void Function(Iterable<AssetId>) reportUnusedAssets}) : _expectedOutputs = expectedOutputs.toSet(), _stageTracker = stageTracker ?? NoOpStageTracker.instance, _reportUnusedAssets = reportUnusedAssets; @override Resolver get resolver { if (_isComplete) throw BuildStepCompletedException(); return _DelayedResolver(_resolver ??= _resolvers.get(this)); } Future<ReleasableResolver> _resolver; @override Future<bool> canRead(AssetId id) { if (_isComplete) throw BuildStepCompletedException(); _checkInput(id); return _reader.canRead(id); } @override Future<T> fetchResource<T>(Resource<T> resource) { if (_isComplete) throw BuildStepCompletedException(); return _resourceManager.fetch(resource); } @override Future<List<int>> readAsBytes(AssetId id) { if (_isComplete) throw BuildStepCompletedException(); _checkInput(id); return _reader.readAsBytes(id); } @override Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) { if (_isComplete) throw BuildStepCompletedException(); _checkInput(id); return _reader.readAsString(id, encoding: encoding); } @override Stream<AssetId> findAssets(Glob glob) { if (_isComplete) throw BuildStepCompletedException(); if (_reader is MultiPackageAssetReader) { return (_reader as MultiPackageAssetReader) .findAssets(glob, package: inputId?.package ?? _rootPackage); } else { return _reader.findAssets(glob); } } @override Future<void> writeAsBytes(AssetId id, FutureOr<List<int>> bytes) { if (_isComplete) throw BuildStepCompletedException(); _checkOutput(id); var done = _futureOrWrite(bytes, (List<int> b) => _writer.writeAsBytes(id, b)); _writeResults.add(Result.capture(done)); return done; } @override Future<void> writeAsString(AssetId id, FutureOr<String> content, {Encoding encoding = utf8}) { if (_isComplete) throw BuildStepCompletedException(); _checkOutput(id); var done = _futureOrWrite(content, (String c) => _writer.writeAsString(id, c, encoding: encoding)); _writeResults.add(Result.capture(done)); return done; } @override Future<Digest> digest(AssetId id) { if (_isComplete) throw BuildStepCompletedException(); _checkInput(id); return _reader.digest(id); } @override T trackStage<T>(String label, T Function() action, {bool isExternal = false}) => _stageTracker.trackStage(label, action, isExternal: isExternal); Future<void> _futureOrWrite<T>( FutureOr<T> content, Future<void> write(T content)) => (content is Future<T>) ? content.then(write) : write(content as T); /// Waits for work to finish and cleans up resources. /// /// This method should be called after a build has completed. After the /// returned [Future] completes then all outputs have been written and the /// [Resolver] for this build step - if any - has been released. Future<void> complete() async { _isComplete = true; await Future.wait(_writeResults.map(Result.release)); (await _resolver)?.release(); } /// Checks that [id] is a valid input, and throws an [InvalidInputException] /// if its not. void _checkInput(AssetId id) { if (id.package != _rootPackage && !id.path.startsWith('lib/')) { throw InvalidInputException(id); } } /// Checks that [id] is an expected output, and throws an /// [InvalidOutputException] or [UnexpectedOutputException] if it's not. void _checkOutput(AssetId id) { if (!_expectedOutputs.contains(id)) { throw UnexpectedOutputException(id, expected: _expectedOutputs); } } @override void reportUnusedAssets(Iterable<AssetId> assets) { if (_reportUnusedAssets != null) _reportUnusedAssets(assets); } } class _DelayedResolver implements Resolver { final Future<Resolver> _delegate; _DelayedResolver(this._delegate); @override Future<bool> isLibrary(AssetId assetId) async => (await _delegate).isLibrary(assetId); @override Stream<LibraryElement> get libraries { var completer = StreamCompleter<LibraryElement>(); _delegate.then((r) => completer.setSourceStream(r.libraries)); return completer.stream; } @override Future<LibraryElement> libraryFor(AssetId assetId) async => (await _delegate).libraryFor(assetId); @override Future<LibraryElement> findLibraryByName(String libraryName) async => (await _delegate).findLibraryByName(libraryName); @override Future<AssetId> assetIdForElement(Element element) async => (await _delegate).assetIdForElement(element); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/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 'build_step.dart'; /// The basic builder class, used to build new files from existing ones. abstract class Builder { /// Generates the outputs for a given [BuildStep]. FutureOr<void> build(BuildStep buildStep); /// Mapping from input file extension to output file extensions. /// /// All input sources matching any key in this map will be passed as build /// step to this builder. Only files with the same basename and an extension /// from the values in this map are expected as outputs. /// /// - If an empty key exists, all inputs are considered matching. /// - A builder must always return the same configuration. Typically this will /// be `const` but may vary based on build arguments. /// - Most builders will use a single input extension and one or more output /// extensions. Map<String, List<String>> get buildExtensions; } class BuilderOptions { /// A configuration with no options set. static const empty = BuilderOptions({}); /// A configuration with [isRoot] set to `true`, and no options set. static const forRoot = BuilderOptions({}, isRoot: true); /// The configuration to apply to a given usage of a [Builder]. /// /// A `Map` parsed from json or yaml. The value types will be `String`, `num`, /// `bool` or `List` or `Map` of these types. final Map<String, dynamic> config; /// Whether or not this builder is running on the root package. final bool isRoot; const BuilderOptions(this.config, {bool isRoot}) : isRoot = isRoot ?? false; /// Returns a new set of options with keys from [other] overriding options in /// this instance. /// /// Config values are overridden at a per-key granularity. There is no value /// level merging. [other] may be null, in which case this instance is /// returned directly. /// /// The `isRoot` value will also be overridden to value from [other]. BuilderOptions overrideWith(BuilderOptions other) { if (other == null) return this; return BuilderOptions({}..addAll(config)..addAll(other.config), isRoot: other.isRoot); } } /// Creates a [Builder] honoring the configuation in [options]. typedef BuilderFactory = Builder Function(BuilderOptions options);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build/src/builder/multiplexing_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 'build_step.dart'; import 'builder.dart'; /// A [Builder] that runs multiple delegate builders asynchronously. /// /// **Note**: All builders are ran without ordering guarantees. Thus, none of /// the builders can use the outputs of other builders in this group. All /// builders must also have distinct outputs. class MultiplexingBuilder implements Builder { final Iterable<Builder> _builders; MultiplexingBuilder(this._builders); @override FutureOr<void> build(BuildStep buildStep) { return Future.wait(_builders .where((builder) => builder.buildExtensions.keys.any(buildStep.inputId.path.endsWith)) .map((builder) => builder.build(buildStep)) .whereType<Future<void>>()); } /// Merges output extensions from all builders. /// /// If multiple builders declare the same output it will appear in this List /// more than once. This should be considered an error. @override Map<String, List<String>> get buildExtensions => _mergeMaps(_builders.map((b) => b.buildExtensions)); @override String toString() => '$_builders'; } Map<String, List<String>> _mergeMaps(Iterable<Map<String, List<String>>> maps) { var result = <String, List<String>>{}; for (var map in maps) { for (var key in map.keys) { result.putIfAbsent(key, () => []); result[key].addAll(map[key]); } } 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/bazel_worker/driver.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/driver/driver.dart'; export 'src/driver/driver_connection.dart'; export 'src/constants.dart'; export 'src/message_grouper.dart'; export 'src/worker_protocol.pb.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/bazel_worker.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/worker/async_worker_loop.dart'; export 'src/constants.dart'; export 'src/message_grouper.dart'; export 'src/worker/sync_worker_loop.dart'; export 'src/worker/worker_connection.dart'; export 'src/worker/worker_loop.dart'; export 'src/worker_protocol.pb.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/testing.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'dart:io'; import 'dart:typed_data'; import 'package:bazel_worker/bazel_worker.dart'; export 'src/async_message_grouper.dart'; export 'src/sync_message_grouper.dart'; export 'src/utils.dart' show protoToDelimitedBuffer; /// Interface for a mock [Stdin] object that allows you to add bytes manually. abstract class TestStdin implements Stdin { void addInputBytes(List<int> bytes); void close(); } /// A [Stdin] mock object which only implements `readByteSync`. class TestStdinSync implements TestStdin { /// Pending bytes to be delivered synchronously. final Queue<int> pendingBytes = Queue<int>(); /// Adds all the [bytes] to this stream. @override void addInputBytes(List<int> bytes) { pendingBytes.addAll(bytes); } /// Add a -1 to signal EOF. @override void close() { pendingBytes.add(-1); } @override int readByteSync() { return pendingBytes.removeFirst(); } @override bool get isBroadcast => false; @override void noSuchMethod(Invocation invocation) { throw StateError('Unexpected invocation ${invocation.memberName}.'); } } /// A mock [Stdin] object which only implements `listen`. /// /// Note: You must call [close] in order for the loop to exit properly. class TestStdinAsync implements TestStdin { /// Controls the stream for async delivery of bytes. final StreamController<Uint8List> _controller = StreamController(); StreamController<Uint8List> get controller => _controller; /// Adds all the [bytes] to this stream. @override void addInputBytes(List<int> bytes) { _controller.add(Uint8List.fromList(bytes)); } /// Closes this stream. This is necessary for the [AsyncWorkerLoop] to exit. @override void close() { _controller.close(); } @override StreamSubscription<Uint8List> listen(void Function(Uint8List bytes) onData, {Function onError, void Function() onDone, bool cancelOnError}) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override bool get isBroadcast => false; @override void noSuchMethod(Invocation invocation) { throw StateError('Unexpected invocation ${invocation.memberName}.'); } } /// A [Stdout] mock object. class TestStdoutStream implements Stdout { final List<List<int>> writes = <List<int>>[]; @override void add(List<int> bytes) { writes.add(bytes); } @override void noSuchMethod(Invocation invocation) { throw StateError('Unexpected invocation ${invocation.memberName}.'); } } /// Interface for a [TestWorkerConnection] which records its responses abstract class TestWorkerConnection implements WorkerConnection { List<WorkResponse> get responses; } /// Interface for a [TestWorkerLoop] which allows you to enqueue responses. abstract class TestWorkerLoop implements WorkerLoop { void enqueueResponse(WorkResponse response); /// If set, this message will be printed during the call to `performRequest`. String get printMessage; } /// A [StdSyncWorkerConnection] which records its responses. class TestSyncWorkerConnection extends StdSyncWorkerConnection implements TestWorkerConnection { @override final List<WorkResponse> responses = <WorkResponse>[]; TestSyncWorkerConnection(Stdin stdinStream, Stdout stdoutStream) : super(stdinStream: stdinStream, stdoutStream: stdoutStream); @override void writeResponse(WorkResponse response) { super.writeResponse(response); responses.add(response); } } /// A [SyncWorkerLoop] for testing. class TestSyncWorkerLoop extends SyncWorkerLoop implements TestWorkerLoop { final List<WorkRequest> requests = <WorkRequest>[]; final Queue<WorkResponse> _responses = Queue<WorkResponse>(); @override final String printMessage; TestSyncWorkerLoop(SyncWorkerConnection connection, {this.printMessage}) : super(connection: connection); @override WorkResponse performRequest(WorkRequest request) { requests.add(request); if (printMessage != null) print(printMessage); return _responses.removeFirst(); } /// Adds [response] to the queue. These will be returned from /// [performResponse] in the order they are added, otherwise it will throw /// if the queue is empty. @override void enqueueResponse(WorkResponse response) { _responses.addLast(response); } } /// A [StdAsyncWorkerConnection] which records its responses. class TestAsyncWorkerConnection extends StdAsyncWorkerConnection implements TestWorkerConnection { @override final List<WorkResponse> responses = <WorkResponse>[]; TestAsyncWorkerConnection( Stream<List<int>> inputStream, StreamSink<List<int>> outputStream) : super(inputStream: inputStream, outputStream: outputStream); @override void writeResponse(WorkResponse response) { super.writeResponse(response); responses.add(response); } } /// A [AsyncWorkerLoop] for testing. class TestAsyncWorkerLoop extends AsyncWorkerLoop implements TestWorkerLoop { final List<WorkRequest> requests = <WorkRequest>[]; final Queue<WorkResponse> _responses = Queue<WorkResponse>(); @override final String printMessage; TestAsyncWorkerLoop(AsyncWorkerConnection connection, {this.printMessage}) : super(connection: connection); @override Future<WorkResponse> performRequest(WorkRequest request) async { requests.add(request); if (printMessage != null) print(printMessage); return _responses.removeFirst(); } /// Adds [response] to the queue. These will be returned from /// [performResponse] in the order they are added, otherwise it will throw /// if the queue is empty. @override void enqueueResponse(WorkResponse response) { _responses.addLast(response); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/worker_protocol.pb.dart
/// // Generated code. Do not modify. // source: worker_protocol.proto // // @dart = 2.3 // ignore_for_file: camel_case_types,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type // ignore_for_file: annotate_overrides import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; class Input extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo('Input', package: const $pb.PackageName('blaze.worker'), createEmptyInstance: create) ..aOS(1, 'path') ..a<$core.List<$core.int>>(2, 'digest', $pb.PbFieldType.OY) ..hasRequiredFields = false; Input._() : super(); factory Input() => create(); factory Input.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory Input.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); Input clone() => Input()..mergeFromMessage(this); Input copyWith(void Function(Input) updates) => super.copyWith((message) => updates(message as Input)); $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Input create() => Input._(); Input createEmptyInstance() => create(); static $pb.PbList<Input> createRepeated() => $pb.PbList<Input>(); @$core.pragma('dart2js:noInline') static Input getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Input>(create); static Input _defaultInstance; @$pb.TagNumber(1) $core.String get path => $_getSZ(0); @$pb.TagNumber(1) set path($core.String v) { $_setString(0, v); } @$pb.TagNumber(1) $core.bool hasPath() => $_has(0); @$pb.TagNumber(1) void clearPath() => clearField(1); @$pb.TagNumber(2) $core.List<$core.int> get digest => $_getN(1); @$pb.TagNumber(2) set digest($core.List<$core.int> v) { $_setBytes(1, v); } @$pb.TagNumber(2) $core.bool hasDigest() => $_has(1); @$pb.TagNumber(2) void clearDigest() => clearField(2); } class WorkRequest extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo('WorkRequest', package: const $pb.PackageName('blaze.worker'), createEmptyInstance: create) ..pPS(1, 'arguments') ..pc<Input>(2, 'inputs', $pb.PbFieldType.PM, subBuilder: Input.create) ..a<$core.int>(3, 'requestId', $pb.PbFieldType.O3) ..hasRequiredFields = false; WorkRequest._() : super(); factory WorkRequest() => create(); factory WorkRequest.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory WorkRequest.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); WorkRequest clone() => WorkRequest()..mergeFromMessage(this); WorkRequest copyWith(void Function(WorkRequest) updates) => super.copyWith((message) => updates(message as WorkRequest)); $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static WorkRequest create() => WorkRequest._(); WorkRequest createEmptyInstance() => create(); static $pb.PbList<WorkRequest> createRepeated() => $pb.PbList<WorkRequest>(); @$core.pragma('dart2js:noInline') static WorkRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WorkRequest>(create); static WorkRequest _defaultInstance; @$pb.TagNumber(1) $core.List<$core.String> get arguments => $_getList(0); @$pb.TagNumber(2) $core.List<Input> get inputs => $_getList(1); @$pb.TagNumber(3) $core.int get requestId => $_getIZ(2); @$pb.TagNumber(3) set requestId($core.int v) { $_setSignedInt32(2, v); } @$pb.TagNumber(3) $core.bool hasRequestId() => $_has(2); @$pb.TagNumber(3) void clearRequestId() => clearField(3); } class WorkResponse extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo('WorkResponse', package: const $pb.PackageName('blaze.worker'), createEmptyInstance: create) ..a<$core.int>(1, 'exitCode', $pb.PbFieldType.O3) ..aOS(2, 'output') ..a<$core.int>(3, 'requestId', $pb.PbFieldType.O3) ..hasRequiredFields = false; WorkResponse._() : super(); factory WorkResponse() => create(); factory WorkResponse.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory WorkResponse.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); WorkResponse clone() => WorkResponse()..mergeFromMessage(this); WorkResponse copyWith(void Function(WorkResponse) updates) => super.copyWith((message) => updates(message as WorkResponse)); $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static WorkResponse create() => WorkResponse._(); WorkResponse createEmptyInstance() => create(); static $pb.PbList<WorkResponse> createRepeated() => $pb.PbList<WorkResponse>(); @$core.pragma('dart2js:noInline') static WorkResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WorkResponse>(create); static WorkResponse _defaultInstance; @$pb.TagNumber(1) $core.int get exitCode => $_getIZ(0); @$pb.TagNumber(1) set exitCode($core.int v) { $_setSignedInt32(0, v); } @$pb.TagNumber(1) $core.bool hasExitCode() => $_has(0); @$pb.TagNumber(1) void clearExitCode() => clearField(1); @$pb.TagNumber(2) $core.String get output => $_getSZ(1); @$pb.TagNumber(2) set output($core.String v) { $_setString(1, v); } @$pb.TagNumber(2) $core.bool hasOutput() => $_has(1); @$pb.TagNumber(2) void clearOutput() => clearField(2); @$pb.TagNumber(3) $core.int get requestId => $_getIZ(2); @$pb.TagNumber(3) set requestId($core.int v) { $_setSignedInt32(2, v); } @$pb.TagNumber(3) $core.bool hasRequestId() => $_has(2); @$pb.TagNumber(3) void clearRequestId() => clearField(3); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/message_grouper.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. /// Interface for a [MessageGrouper], which groups bytes in delimited proto /// format into the bytes for each message. /// /// This interface should not generally be implemented directly, instead use /// the [SyncMessageGrouper] or [AsyncMessageGrouper] implementations. abstract class MessageGrouper { /// Returns either a [List<int>] or a [Future<List<int>>]. dynamic get next; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/constants.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. const int EXIT_CODE_OK = 0; const int EXIT_CODE_ERROR = 15;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/message_grouper_state.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:typed_data'; import 'package:protobuf/protobuf.dart'; /// State held by the [MessageGrouper] while waiting for additional data to /// arrive. class MessageGrouperState { /// Reads the initial length. _LengthReader _lengthReader; /// Reads messages from a stream of bytes. _MessageReader _messageReader; MessageGrouperState() { reset(); } /// Handle one byte at a time. /// /// Returns a [List<int>] of message bytes if [byte] was the last byte in a /// message, otherwise returns [null]. List<int> handleInput(int byte) { if (!_lengthReader.done) { _lengthReader.readByte(byte); if (_lengthReader.done) { _messageReader = _MessageReader(_lengthReader.length); } } else { assert(_messageReader != null); _messageReader.readByte(byte); } if (_lengthReader.done && _messageReader.done) { var message = _messageReader.message; reset(); return message; } return null; } /// Reset the state so that we are ready to receive the next message. void reset() { _lengthReader = _LengthReader(); _messageReader = null; } } /// Reads a length one byte at a time. /// /// The base-128 encoding is in little-endian order, with the high bit set on /// all bytes but the last. This was chosen since it's the same as the /// base-128 encoding used by protobufs, so it allows a modest amount of code /// reuse at the other end of the protocol. class _LengthReader { /// Whether or not we are done reading the length. bool get done => _done; bool _done = false; /// If [_done] is `true`, the decoded value of the length bytes received so /// far (if any). If [_done] is `false`, the decoded length that was most /// recently received. int _length; /// The length read in. You are only allowed to read this if [_done] is /// `true`. int get length { assert(_done); return _length; } final List<int> _buffer = <int>[]; /// Read a single byte into [_length]. void readByte(int byte) { assert(!_done); _buffer.add(byte); // Check for the last byte in the length, and then read it. if ((byte & 0x80) == 0) { _done = true; var reader = CodedBufferReader(_buffer); _length = reader.readInt32(); } } } /// Reads some number of bytes from a stream, one byte at a time. class _MessageReader { /// Whether or not we are done reading bytes from the stream. bool get done => _done; bool _done; /// The total length of the message to be read. final int _length; /// A [Uint8List] which holds the message data. You are only allowed to read /// this if [_done] is `true`. Uint8List get message { assert(_done); return _message; } final Uint8List _message; /// If [_done] is `false`, the number of message bytes that have been received /// so far. Otherwise zero. int _numMessageBytesReceived = 0; _MessageReader(int length) : _message = Uint8List(length), _length = length, _done = length == 0; /// Reads [byte] into [_message]. void readByte(int byte) { assert(!done); _message[_numMessageBytesReceived++] = byte; if (_numMessageBytesReceived == _length) _done = true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/async_message_grouper.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'package:async/async.dart'; import 'package:pedantic/pedantic.dart'; import 'message_grouper.dart'; import 'message_grouper_state.dart'; /// Collects stream data into messages by interpreting it as /// base-128 encoded lengths interleaved with raw data. class AsyncMessageGrouper implements MessageGrouper { /// Current state for reading in messages; final _state = MessageGrouperState(); /// The input stream. final StreamQueue<List<int>> _inputQueue; /// The current buffer. final Queue<int> _buffer = Queue<int>(); /// Completes after [cancel] is called or [inputStream] is closed. Future<void> get done => _done.future; final _done = Completer<void>(); AsyncMessageGrouper(Stream<List<int>> inputStream) : _inputQueue = StreamQueue(inputStream); /// Returns the next full message that is received, or null if none are left. @override Future<List<int>> get next async { try { List<int> message; while (message == null && (_buffer.isNotEmpty || await _inputQueue.hasNext)) { if (_buffer.isEmpty) _buffer.addAll(await _inputQueue.next); var nextByte = _buffer.removeFirst(); if (nextByte == -1) return null; message = _state.handleInput(nextByte); } // If there is nothing left in the queue then cancel the subscription. if (message == null) unawaited(cancel()); return message; } catch (e) { // It appears we sometimes get an exception instead of -1 as expected when // stdin closes, this handles that in the same way (returning a null // message) return null; } } /// Stop listening to the stream for further updates. Future cancel() { if (!_done.isCompleted) { _done.complete(null); return _inputQueue.cancel(); } return done; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/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:typed_data'; import 'package:protobuf/protobuf.dart'; List<int> protoToDelimitedBuffer(GeneratedMessage message) { var messageBuffer = CodedBufferWriter(); message.writeToCodedBufferWriter(messageBuffer); var delimiterBuffer = CodedBufferWriter(); delimiterBuffer.writeInt32NoTag(messageBuffer.lengthInBytes); var result = Uint8List(messageBuffer.lengthInBytes + delimiterBuffer.lengthInBytes); delimiterBuffer.writeTo(result); messageBuffer.writeTo(result, delimiterBuffer.lengthInBytes); return result; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/sync_message_grouper.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:io'; import 'message_grouper.dart'; import 'message_grouper_state.dart'; /// Groups bytes in delimited proto format into the bytes for each message. class SyncMessageGrouper implements MessageGrouper { final _state = MessageGrouperState(); final Stdin _stdin; SyncMessageGrouper(this._stdin); /// Blocks until the next full message is received, and then returns it. /// /// Returns null at end of file. @override List<int> get next { try { List<int> message; while (message == null) { var nextByte = _stdin.readByteSync(); if (nextByte == -1) return null; message = _state.handleInput(nextByte); } return message; } catch (e) { // It appears we sometimes get an exception instead of -1 as expected when // stdin closes, this handles that in the same way (returning a null // message) return null; } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/driver/driver.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:io'; import '../constants.dart'; import '../worker_protocol.pb.dart'; import 'driver_connection.dart'; typedef SpawnWorker = Future<Process> Function(); /// A driver for talking to a bazel worker. /// /// This allows you to use any binary that supports the bazel worker protocol in /// the same way that bazel would, but from another dart process instead. class BazelWorkerDriver { /// Idle worker processes. final _idleWorkers = <Process>[]; /// The maximum number of idle workers at any given time. final int _maxIdleWorkers; /// The maximum number of times to retry a [WorkAttempt] if there is an error. final int _maxRetries; /// The maximum number of concurrent workers to run at any given time. final int _maxWorkers; /// The number of currently active workers. int get _numWorkers => _readyWorkers.length + _spawningWorkers.length; /// All workers that are fully spawned and ready to handle work. final _readyWorkers = <Process>[]; /// All workers that are in the process of being spawned. final _spawningWorkers = <Future<Process>>[]; /// Work requests that haven't been started yet. final _workQueue = Queue<_WorkAttempt>(); /// Factory method that spawns a worker process. final SpawnWorker _spawnWorker; BazelWorkerDriver(this._spawnWorker, {int maxIdleWorkers, int maxWorkers, int maxRetries}) : _maxIdleWorkers = maxIdleWorkers ?? 4, _maxWorkers = maxWorkers ?? 4, _maxRetries = maxRetries ?? 4; /// Waits for an available worker, and then sends [WorkRequest] to it. /// /// If [trackWork] is provided it will be invoked with a [Future] once the /// [request] has been actually sent to the worker. This allows the caller /// to determine when actual work is being done versus just waiting for an /// available worker. Future<WorkResponse> doWork(WorkRequest request, {Function(Future<WorkResponse>) trackWork}) { var attempt = _WorkAttempt(request, trackWork: trackWork); _workQueue.add(attempt); _runWorkQueue(); return attempt.response; } /// Calls `kill` on all worker processes. Future terminateWorkers() async { for (var worker in _readyWorkers.toList()) { _killWorker(worker); } await Future.wait(_spawningWorkers.map((worker) async { _killWorker(await worker); })); } /// Runs as many items in [_workQueue] as possible given the number of /// available workers. /// /// Will spawn additional workers until [_maxWorkers] has been reached. /// /// This method synchronously drains the [_workQueue] and [_idleWorkers], but /// some tasks may not actually start right away if they need to wait for a /// worker to spin up. void _runWorkQueue() { // Bail out conditions, we will continue to call ourselves indefinitely // until one of these is met. if (_workQueue.isEmpty) return; if (_numWorkers == _maxWorkers && _idleWorkers.isEmpty) return; if (_numWorkers > _maxWorkers) { throw StateError('Internal error, created to many workers. Please ' 'file a bug at https://github.com/dart-lang/bazel_worker/issues/new'); } // At this point we definitely want to run a task, we just need to decide // whether or not we need to start up a new worker. var attempt = _workQueue.removeFirst(); if (_idleWorkers.isNotEmpty) { _runWorker(_idleWorkers.removeLast(), attempt); } else { // No need to block here, we want to continue to synchronously drain the // work queue. var futureWorker = _spawnWorker(); _spawningWorkers.add(futureWorker); futureWorker.then((worker) { _spawningWorkers.remove(futureWorker); _readyWorkers.add(worker); var connection = StdDriverConnection.forWorker(worker); _workerConnections[worker] = connection; _runWorker(worker, attempt); // When the worker exits we should retry running the work queue in case // there is more work to be done. This is primarily just a defensive // thing but is cheap to do. // // We don't use `exitCode` because it is null for detached processes ( // which is common for workers). connection.done.then((_) { _idleWorkers.remove(worker); _readyWorkers.remove(worker); _runWorkQueue(); }); }); } // Recursively calls itself until one of the bail out conditions are met. _runWorkQueue(); } /// Sends [request] to [worker]. /// /// Once the worker responds then it will be added back to the pool of idle /// workers. void _runWorker(Process worker, _WorkAttempt attempt) { var rescheduled = false; runZoned(() async { var connection = _workerConnections[worker]; connection.writeRequest(attempt.request); var responseFuture = connection.readResponse(); if (attempt.trackWork != null) { attempt.trackWork(responseFuture); } var response = await responseFuture; // It is possible for us to complete with an error response due to an // unhandled async error before we get here. if (!attempt.responseCompleter.isCompleted) { if (response == null) { rescheduled = _tryReschedule(attempt); if (rescheduled) return; stderr.writeln('Failed to run request ${attempt.request}'); response = WorkResponse() ..exitCode = EXIT_CODE_ERROR ..output = 'Invalid response from worker, this probably means it wrote ' 'invalid output or died.'; } attempt.responseCompleter.complete(response); _cleanUp(worker); } }, onError: (e, s) { // Note that we don't need to do additional cleanup here on failures. If // the worker dies that is already handled in a generic fashion, we just // need to make sure we complete with a valid response. if (!attempt.responseCompleter.isCompleted) { rescheduled = _tryReschedule(attempt); if (rescheduled) return; var response = WorkResponse() ..exitCode = EXIT_CODE_ERROR ..output = 'Error running worker:\n$e\n$s'; attempt.responseCompleter.complete(response); _cleanUp(worker); } }); } /// Performs post-work cleanup for [worker]. void _cleanUp(Process worker) { // If the worker crashes, it won't be in `_readyWorkers` any more, and // we don't want to add it to _idleWorkers. if (_readyWorkers.contains(worker)) { _idleWorkers.add(worker); } // Do additional work if available. _runWorkQueue(); // If the worker wasn't immediately used we might have to many idle // workers now, kill one if necessary. if (_idleWorkers.length > _maxIdleWorkers) { // Note that whenever we spawn a worker we listen for its exit code // and clean it up so we don't need to do that here. var worker = _idleWorkers.removeLast(); _killWorker(worker); } } /// Attempts to reschedule a failed [attempt]. /// /// Returns whether or not the job was successfully rescheduled. bool _tryReschedule(_WorkAttempt attempt) { if (attempt.timesRetried >= _maxRetries) return false; stderr.writeln('Rescheduling failed request...'); attempt.timesRetried++; _workQueue.add(attempt); _runWorkQueue(); return true; } void _killWorker(Process worker) { _workerConnections[worker].cancel(); _readyWorkers.remove(worker); _idleWorkers.remove(worker); worker.kill(); } } /// Encapsulates an attempt to fulfill a [WorkRequest], a completer for the /// [WorkResponse], and the number of times it has been retried. class _WorkAttempt { final WorkRequest request; final responseCompleter = Completer<WorkResponse>(); final Function(Future<WorkResponse>) trackWork; Future<WorkResponse> get response => responseCompleter.future; int timesRetried = 0; _WorkAttempt(this.request, {this.trackWork}); } final _workerConnections = Expando<DriverConnection>('connection');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/driver/driver_connection.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:convert'; import 'dart:io'; import 'dart:isolate'; import '../async_message_grouper.dart'; import '../worker_protocol.pb.dart'; import '../constants.dart'; import '../utils.dart'; /// A connection from a `BazelWorkerDriver` to a worker. /// /// Unlike `WorkerConnection` there is no synchronous version of this class. /// This is because drivers talk to multiple workers, so they should never block /// when waiting for the response of any individual worker. abstract class DriverConnection { Future<WorkResponse> readResponse(); void writeRequest(WorkRequest request); Future cancel(); } /// Default implementation of [DriverConnection] that works with [Stdin] /// and [Stdout]. class StdDriverConnection implements DriverConnection { final AsyncMessageGrouper _messageGrouper; final StreamSink<List<int>> _outputStream; Future<void> get done => _messageGrouper.done; StdDriverConnection( {Stream<List<int>> inputStream, StreamSink<List<int>> outputStream}) : _messageGrouper = AsyncMessageGrouper(inputStream ?? stdin), _outputStream = outputStream ?? stdout; factory StdDriverConnection.forWorker(Process worker) => StdDriverConnection( inputStream: worker.stdout, outputStream: worker.stdin); /// Note: This will attempts to recover from invalid proto messages by parsing /// them as strings. This is a common error case for workers (they print a /// message to stdout on accident). This isn't perfect however as it only /// happens if the parsing throws, you can still hang indefinitely if the /// [MessageGrouper] doesn't find what it thinks is the end of a proto /// message. @override Future<WorkResponse> readResponse() async { var buffer = await _messageGrouper.next; if (buffer == null) return null; WorkResponse response; try { response = WorkResponse.fromBuffer(buffer); } catch (_) { try { // Try parsing the message as a string and set that as the output. var output = utf8.decode(buffer); var response = WorkResponse() ..exitCode = EXIT_CODE_ERROR ..output = 'Worker sent an invalid response:\n$output'; return response; } catch (_) { // Fall back to original exception and rethrow if we fail to parse as // a string. } rethrow; } return response; } @override void writeRequest(WorkRequest request) { _outputStream.add(protoToDelimitedBuffer(request)); } @override Future cancel() async { await _outputStream.close(); await _messageGrouper.cancel(); } } /// [DriverConnection] that works with an isolate via a [SendPort]. class IsolateDriverConnection implements DriverConnection { final StreamIterator _receivePortIterator; final SendPort _sendPort; IsolateDriverConnection._(this._receivePortIterator, this._sendPort); /// Creates a driver connection for a worker in an isolate. Provide the /// [receivePort] attached to the [SendPort] that the isolate was created /// with. static Future<IsolateDriverConnection> create(ReceivePort receivePort) async { var receivePortIterator = StreamIterator(receivePort); await receivePortIterator.moveNext(); var sendPort = receivePortIterator.current as SendPort; return IsolateDriverConnection._(receivePortIterator, sendPort); } @override Future<WorkResponse> readResponse() async { if (!await _receivePortIterator.moveNext()) { return null; } return WorkResponse.fromBuffer(_receivePortIterator.current as List<int>); } @override void writeRequest(WorkRequest request) { _sendPort.send(request.writeToBuffer()); } @override Future cancel() async {} }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/worker/async_worker_loop.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import '../constants.dart'; import '../worker_protocol.pb.dart'; import 'worker_connection.dart'; import 'worker_loop.dart'; /// Persistent Bazel worker loop. /// /// Extend this class and implement the `performRequest` method. abstract class AsyncWorkerLoop implements WorkerLoop { final AsyncWorkerConnection connection; AsyncWorkerLoop({AsyncWorkerConnection connection}) : connection = connection ?? StdAsyncWorkerConnection(); /// Perform a single [WorkRequest], and return a [WorkResponse]. @override Future<WorkResponse> performRequest(WorkRequest request); /// Run the worker loop. The returned [Future] doesn't complete until /// [connection#readRequest] returns `null`. @override Future run() async { while (true) { WorkResponse response; try { var request = await connection.readRequest(); if (request == null) break; var printMessages = StringBuffer(); response = await runZoned(() => performRequest(request), zoneSpecification: ZoneSpecification(print: (self, parent, zone, message) { printMessages.writeln(); printMessages.write(message); })); if (printMessages.isNotEmpty) { response.output = '${response.output}$printMessages'; } // In case they forget to set this. response.exitCode ??= EXIT_CODE_OK; } catch (e, s) { response = WorkResponse() ..exitCode = EXIT_CODE_ERROR ..output = '$e\n$s'; } connection.writeResponse(response); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/worker/worker_connection.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; import '../async_message_grouper.dart'; import '../sync_message_grouper.dart'; import '../utils.dart'; import '../worker_protocol.pb.dart'; /// A connection from a worker to a driver (driver could be bazel, a dart /// program using `BazelWorkerDriver`, or any other process that speaks the /// protocol). abstract class WorkerConnection { /// Reads a [WorkRequest] or returns [null] if there are none left. /// /// See [AsyncWorkerConnection] and [SyncWorkerConnection] for more narrow /// interfaces. FutureOr<WorkRequest> readRequest(); void writeResponse(WorkResponse response); } abstract class AsyncWorkerConnection implements WorkerConnection { /// Creates a [StdAsyncWorkerConnection] with the specified [inputStream] /// and [outputStream], unless [sendPort] is specified, in which case /// creates a [SendPortAsyncWorkerConnection]. factory AsyncWorkerConnection( {Stream<List<int>> inputStream, StreamSink<List<int>> outputStream, SendPort sendPort}) => sendPort == null ? StdAsyncWorkerConnection( inputStream: inputStream, outputStream: outputStream) : SendPortAsyncWorkerConnection(sendPort); @override Future<WorkRequest> readRequest(); } abstract class SyncWorkerConnection implements WorkerConnection { @override WorkRequest readRequest(); } /// Default implementation of [AsyncWorkerConnection] that works with [Stdin] /// and [Stdout]. class StdAsyncWorkerConnection implements AsyncWorkerConnection { final AsyncMessageGrouper _messageGrouper; final StreamSink<List<int>> _outputStream; StdAsyncWorkerConnection( {Stream<List<int>> inputStream, StreamSink<List<int>> outputStream}) : _messageGrouper = AsyncMessageGrouper(inputStream ?? stdin), _outputStream = outputStream ?? stdout; @override Future<WorkRequest> readRequest() async { var buffer = await _messageGrouper.next; if (buffer == null) return null; return WorkRequest.fromBuffer(buffer); } @override void writeResponse(WorkResponse response) { _outputStream.add(protoToDelimitedBuffer(response)); } } /// Implementation of [AsyncWorkerConnection] for running in an isolate. class SendPortAsyncWorkerConnection implements AsyncWorkerConnection { final ReceivePort receivePort; final StreamIterator<Uint8List> receivePortIterator; final SendPort sendPort; factory SendPortAsyncWorkerConnection(SendPort sendPort) { var receivePort = ReceivePort(); sendPort.send(receivePort.sendPort); return SendPortAsyncWorkerConnection._(receivePort, sendPort); } SendPortAsyncWorkerConnection._(this.receivePort, this.sendPort) : receivePortIterator = StreamIterator(receivePort.cast()); @override Future<WorkRequest> readRequest() async { if (!await receivePortIterator.moveNext()) return null; return WorkRequest.fromBuffer(receivePortIterator.current); } @override void writeResponse(WorkResponse response) { sendPort.send(response.writeToBuffer()); } } /// Default implementation of [SyncWorkerConnection] that works with [Stdin] and /// [Stdout]. class StdSyncWorkerConnection implements SyncWorkerConnection { final SyncMessageGrouper _messageGrouper; final Stdout _stdoutStream; StdSyncWorkerConnection({Stdin stdinStream, Stdout stdoutStream}) : _messageGrouper = SyncMessageGrouper(stdinStream ?? stdin), _stdoutStream = stdoutStream ?? stdout; @override WorkRequest readRequest() { var buffer = _messageGrouper.next; if (buffer == null) return null; return WorkRequest.fromBuffer(buffer); } @override void writeResponse(WorkResponse response) { _stdoutStream.add(protoToDelimitedBuffer(response)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/worker/worker_loop.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 '../worker_protocol.pb.dart'; /// Interface for a [WorkerLoop]. /// /// This interface should not generally be implemented directly, instead use /// the [SyncWorkerLoop] or [AsyncWorkerLoop] implementations. abstract class WorkerLoop { /// Perform a single [WorkRequest], and return either a [WorkResponse] or /// a [Future<WorkResponse>]. dynamic performRequest(WorkRequest request); /// Run the worker loop. Should return either a [Future] or [null]. dynamic run(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/bazel_worker/src/worker/sync_worker_loop.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import '../constants.dart'; import '../worker_protocol.pb.dart'; import 'worker_connection.dart'; import 'worker_loop.dart'; /// Persistent Bazel worker loop. /// /// Extend this class and implement the `performRequest` method. abstract class SyncWorkerLoop implements WorkerLoop { final SyncWorkerConnection connection; SyncWorkerLoop({SyncWorkerConnection connection}) : connection = connection ?? StdSyncWorkerConnection(); /// Perform a single [WorkRequest], and return a [WorkResponse]. @override WorkResponse performRequest(WorkRequest request); /// Run the worker loop. Blocks until [connection#readRequest] returns `null`. @override void run() { while (true) { WorkResponse response; try { var request = connection.readRequest(); if (request == null) break; var printMessages = StringBuffer(); response = runZoned(() => performRequest(request), zoneSpecification: ZoneSpecification(print: (self, parent, zone, message) { printMessages.writeln(); printMessages.write(message); })); if (printMessages.isNotEmpty) { response.output = '${response.output}$printMessages'; } // In case they forget to set this. response.exitCode ??= EXIT_CODE_OK; } catch (e, s) { response = WorkResponse() ..exitCode = EXIT_CODE_ERROR ..output = '$e\n$s'; } connection.writeResponse(response); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/crypto.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. export 'src/digest.dart'; export 'src/hash.dart'; export 'src/hmac.dart'; export 'src/md5.dart'; export 'src/sha1.dart'; export 'src/sha256.dart'; export 'src/sha512.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/sha512.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 'digest.dart'; import 'hash.dart'; // ignore: uri_does_not_exist import 'sha512_fastsinks.dart' if (dart.library.js) 'sha512_slowsinks.dart'; import 'utils.dart'; /// An instance of [Sha2Sha384]. /// /// This instance provides convenient access to the [Sha384][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 final sha384 = Sha384._(); /// An instance of [Sha2Sha512]. /// /// This instance provides convenient access to the [Sha512][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 final sha512 = Sha512._(); /// An implementation of the [SHA-384][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 /// /// Note that it's almost always easier to use [sha384] rather than creating a /// new instance. class Sha384 extends Hash { @override final int blockSize = 32 * bytesPerWord; Sha384._(); Sha384 newInstance() => Sha384._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(Sha384Sink(sink)); } /// An implementation of the [SHA-512][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 /// /// Note that it's almost always easier to use [sha512] rather than creating a /// new instance. class Sha512 extends Sha384 { Sha512._() : super._(); @override Sha512 newInstance() => Sha512._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(Sha512Sink(sink)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/sha512_fastsinks.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:typed_data'; import 'digest.dart'; import 'hash_sink.dart'; abstract class _Sha64BitSink extends HashSink { int get digestBytes; @override Uint32List get digest { var unordered = _digest.buffer.asUint32List(); var ordered = Uint32List(digestBytes); for (var i = 0; i < digestBytes; i++) { ordered[i] = unordered[i + (i.isEven ? 1 : -1)]; } return ordered; } // Initial value of the hash parts. First 64 bits of the fractional parts // of the square roots of the ninth through sixteenth prime numbers. final Uint64List _digest; /// The sixteen words from the original chunk, extended to 64 words. /// /// This is an instance variable to avoid re-allocating, but its data isn't /// used across invocations of [updateHash]. final _extended = Uint64List(80); _Sha64BitSink(Sink<Digest> sink, this._digest) : super(sink, 32, signatureBytes: 16); // The following helper functions are taken directly from // http://tools.ietf.org/html/rfc6234. static int _rotr64(int n, int x) => _shr64(n, x) | (x << (64 - n)); static int _shr64(int n, int x) => (x >> n) & ~(-1 << (64 - n)); static int _ch(int x, int y, int z) => (x & y) ^ (~x & z); static int _maj(int x, int y, int z) => (x & y) ^ (x & z) ^ (y & z); static int _bsig0(int x) => _rotr64(28, x) ^ _rotr64(34, x) ^ _rotr64(39, x); static int _bsig1(int x) => _rotr64(14, x) ^ _rotr64(18, x) ^ _rotr64(41, x); static int _ssig0(int x) => _rotr64(1, x) ^ _rotr64(8, x) ^ _shr64(7, x); static int _ssig1(int x) => _rotr64(19, x) ^ _rotr64(61, x) ^ _shr64(6, x); @override void updateHash(Uint32List chunk) { assert(chunk.length == 32); // Prepare message schedule. for (var i = 0, x = 0; i < 32; i += 2, x++) { _extended[x] = (chunk[i] << 32) | chunk[i + 1]; } for (var t = 16; t < 80; t++) { _extended[t] = _ssig1(_extended[t - 2]) + _extended[t - 7] + _ssig0(_extended[t - 15]) + _extended[t - 16]; } // Shuffle around the bits. var a = _digest[0]; var b = _digest[1]; var c = _digest[2]; var d = _digest[3]; var e = _digest[4]; var f = _digest[5]; var g = _digest[6]; var h = _digest[7]; for (var i = 0; i < 80; i++) { var temp1 = h + _bsig1(e) + _ch(e, f, g) + _noise64[i] + _extended[i]; var temp2 = _bsig0(a) + _maj(a, b, c); h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } // Update hash values after iteration. _digest[0] += a; _digest[1] += b; _digest[2] += c; _digest[3] += d; _digest[4] += e; _digest[5] += f; _digest[6] += g; _digest[7] += h; } } /// The concrete implementation of [Sha384]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class Sha384Sink extends _Sha64BitSink { @override final digestBytes = 12; Sha384Sink(Sink<Digest> sink) : super( sink, Uint64List.fromList([ 0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4, ])); } /// The concrete implementation of [Sha512]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class Sha512Sink extends _Sha64BitSink { @override final digestBytes = 16; Sha512Sink(Sink<Digest> sink) : super( sink, Uint64List.fromList([ // Initial value of the hash parts. First 64 bits of the fractional // parts of the square roots of the first eight prime numbers. 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, ])); } final _noise64 = Uint64List.fromList([ 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817, ]);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/hash_sink.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:typed_data'; import 'package:typed_data/typed_data.dart'; import 'digest.dart'; import 'utils.dart'; /// A base class for [Sink] implementations for hash algorithms. /// /// Subclasses should override [updateHash] and [digest]. abstract class HashSink implements Sink<List<int>> { /// The inner sink that this should forward to. final Sink<Digest> _sink; /// Whether the hash function operates on big-endian words. final Endian _endian; /// The words in the current chunk. /// /// This is an instance variable to avoid re-allocating, but its data isn't /// used across invocations of [_iterate]. final Uint32List _currentChunk; /// Messages with more than 2^53-1 bits are not supported. (This is the /// largest value that is representable on both JS and the Dart VM.) /// So the maximum length in bytes is (2^53-1)/8. static const _maxMessageLengthInBytes = 0x0003ffffffffffff; /// The length of the input data so far, in bytes. int _lengthInBytes = 0; /// Data that has yet to be processed by the hash function. final _pendingData = Uint8Buffer(); /// Whether [close] has been called. bool _isClosed = false; /// The words in the current digest. /// /// This should be updated each time [updateHash] is called. Uint32List get digest; /// The number of signature bytes emitted at the end of the message. /// /// An encrypted message is followed by a signature which depends /// on the encryption algorithm used. This value specifies the /// number of bytes used by this signature. It must always be /// a power of 2 and no less than 8. final int _signatureBytes; /// Creates a new hash. /// /// [chunkSizeInWords] represents the size of the input chunks processed by /// the algorithm, in terms of 32-bit words. HashSink(this._sink, int chunkSizeInWords, {Endian endian = Endian.big, int signatureBytes = 8}) : _endian = endian, assert(signatureBytes >= 8), _signatureBytes = signatureBytes, _currentChunk = Uint32List(chunkSizeInWords); /// Runs a single iteration of the hash computation, updating [digest] with /// the result. /// /// [chunk] is the current chunk, whose size is given by the /// `chunkSizeInWords` parameter passed to the constructor. void updateHash(Uint32List chunk); @override void add(List<int> data) { if (_isClosed) throw StateError('Hash.add() called after close().'); _lengthInBytes += data.length; _pendingData.addAll(data); _iterate(); } @override void close() { if (_isClosed) return; _isClosed = true; _finalizeData(); _iterate(); assert(_pendingData.isEmpty); _sink.add(Digest(_byteDigest())); _sink.close(); } Uint8List _byteDigest() { if (_endian == Endian.host) return digest.buffer.asUint8List(); // Cache the digest locally as `get` could be expensive. final cachedDigest = digest; final byteDigest = Uint8List(cachedDigest.lengthInBytes); final byteData = byteDigest.buffer.asByteData(); for (var i = 0; i < cachedDigest.length; i++) { byteData.setUint32(i * bytesPerWord, cachedDigest[i]); } return byteDigest; } /// Iterates through [_pendingData], updating the hash computation for each /// chunk. void _iterate() { var pendingDataBytes = _pendingData.buffer.asByteData(); var pendingDataChunks = _pendingData.length ~/ _currentChunk.lengthInBytes; for (var i = 0; i < pendingDataChunks; i++) { // Copy words from the pending data buffer into the current chunk buffer. for (var j = 0; j < _currentChunk.length; j++) { _currentChunk[j] = pendingDataBytes.getUint32( i * _currentChunk.lengthInBytes + j * bytesPerWord, _endian); } // Run the hash function on the current chunk. updateHash(_currentChunk); } // Remove all pending data up to the last clean chunk break. _pendingData.removeRange( 0, pendingDataChunks * _currentChunk.lengthInBytes); } /// Finalizes [_pendingData]. /// /// This adds a 1 bit to the end of the message, and expands it with 0 bits to /// pad it out. void _finalizeData() { // Pad out the data with 0x80, eight or sixteen 0s, and as many more 0s // as we need to land cleanly on a chunk boundary. _pendingData.add(0x80); final contentsLength = _lengthInBytes + 1 /* 0x80 */ + _signatureBytes; final finalizedLength = _roundUp(contentsLength, _currentChunk.lengthInBytes); for (var i = 0; i < finalizedLength - contentsLength; i++) { _pendingData.add(0); } if (_lengthInBytes > _maxMessageLengthInBytes) { throw UnsupportedError( 'Hashing is unsupported for messages with more than 2^53 bits.'); } var lengthInBits = _lengthInBytes * bitsPerByte; // Add the full length of the input data as a 64-bit value at the end of the // hash. Note: we're only writing out 64 bits, so skip ahead 8 if the // signature is 128-bit. final offset = _pendingData.length + (_signatureBytes - 8); _pendingData.addAll(Uint8List(_signatureBytes)); var byteData = _pendingData.buffer.asByteData(); // We're essentially doing byteData.setUint64(offset, lengthInBits, _endian) // here, but that method isn't supported on dart2js so we implement it // manually instead. var highBits = lengthInBits >> 32; var lowBits = lengthInBits & mask32; if (_endian == Endian.big) { byteData.setUint32(offset, highBits, _endian); byteData.setUint32(offset + bytesPerWord, lowBits, _endian); } else { byteData.setUint32(offset, lowBits, _endian); byteData.setUint32(offset + bytesPerWord, highBits, _endian); } } /// Rounds [val] up to the next multiple of [n], as long as [n] is a power of /// two. int _roundUp(int val, int n) => (val + n - 1) & -n; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/digest.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 'package:collection/collection.dart'; import 'package:convert/convert.dart'; /// A message digest as computed by a `Hash` or `HMAC` function. class Digest { /// The message digest as an array of bytes. final List<int> bytes; Digest(this.bytes); /// Returns whether this is equal to another digest. /// /// This should be used instead of manual comparisons to avoid leaking /// information via timing. @override bool operator ==(Object other) { if (other is Digest) { final a = bytes; final b = other.bytes; if (a.length != b.length) { return false; } final n = a.length; var mismatch = 0; for (var i = 0; i < n; i++) { mismatch |= a[i] ^ b[i]; } return mismatch == 0; } return false; } @override int get hashCode => const ListEquality().hash(bytes); /// The message digest as a string of hexadecimal digits. @override String toString() => hex.encode(bytes); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/sha512_slowsinks.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:typed_data'; import 'digest.dart'; import 'hash_sink.dart'; /// Data from a non-linear function that functions as reproducible noise. /// /// [rfc]: https://tools.ietf.org/html/rfc6234#section-5.2 final _noise32 = Uint32List.fromList([ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, // 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817, ]); abstract class _Sha64BitSink extends HashSink { int get digestBytes; @override Uint32List get digest { return Uint32List.view(_digest.buffer, 0, digestBytes); } // Initial value of the hash parts. First 64 bits of the fractional parts // of the square roots of the ninth through sixteenth prime numbers. final Uint32List _digest; /// The sixteen words from the original chunk, extended to 64 words. /// /// This is an instance variable to avoid re-allocating, but its data isn't /// used across invocations of [updateHash]. final _extended = Uint32List(160); _Sha64BitSink(Sink<Digest> sink, this._digest) : super(sink, 32, signatureBytes: 16); // The following helper functions are taken directly from // http://tools.ietf.org/html/rfc6234. void _shr( int bits, Uint32List word, int offset, Uint32List ret, int offsetR) { ret[0 + offsetR] = ((bits < 32) && (bits >= 0)) ? (word[0 + offset] >> (bits)) : 0; ret[1 + offsetR] = (bits > 32) ? (word[0 + offset] >> (bits - 32)) : (bits == 32) ? word[0 + offset] : (bits >= 0) ? ((word[0 + offset] << (32 - bits)) | (word[1 + offset] >> bits)) : 0; } void _shl( int bits, Uint32List word, int offset, Uint32List ret, int offsetR) { ret[0 + offsetR] = (bits > 32) ? (word[1 + offset] << (bits - 32)) : (bits == 32) ? word[1 + offset] : (bits >= 0) ? ((word[0 + offset] << bits) | (word[1 + offset] >> (32 - bits))) : 0; ret[1 + offsetR] = ((bits < 32) && (bits >= 0)) ? (word[1 + offset] << bits) : 0; } void _or(Uint32List word1, int offset1, Uint32List word2, int offset2, Uint32List ret, int offsetR) { ret[0 + offsetR] = word1[0 + offset1] | word2[0 + offset2]; ret[1 + offsetR] = word1[1 + offset1] | word2[1 + offset2]; } void _xor(Uint32List word1, int offset1, Uint32List word2, int offset2, Uint32List ret, int offsetR) { ret[0 + offsetR] = word1[0 + offset1] ^ word2[0 + offset2]; ret[1 + offsetR] = word1[1 + offset1] ^ word2[1 + offset2]; } void _add(Uint32List word1, int offset1, Uint32List word2, int offset2, Uint32List ret, int offsetR) { ret[1 + offsetR] = (word1[1 + offset1] + word2[1 + offset2]); ret[0 + offsetR] = word1[0 + offset1] + word2[0 + offset2] + (ret[1 + offsetR] < word1[1 + offset1] ? 1 : 0); } void _addTo2(Uint32List word1, int offset1, Uint32List word2, int offset2) { int _addTemp; _addTemp = word1[1 + offset1]; word1[1 + offset1] += word2[1 + offset2]; word1[0 + offset1] += word2[0 + offset2] + (word1[1 + offset1] < _addTemp ? 1 : 0); } static const _rotrIndex1 = 0; static const _rotrIndex2 = _rotrIndex1 + 2; static const _sigIndex1 = _rotrIndex2 + 2; static const _sigIndex2 = _sigIndex1 + 2; static const _sigIndex3 = _sigIndex2 + 2; static const _sigIndex4 = _sigIndex3 + 2; static const _aIndex = _sigIndex4 + 2; static const _bIndex = _aIndex + 2; static const _cIndex = _bIndex + 2; static const _dIndex = _cIndex + 2; static const _eIndex = _dIndex + 2; static const _fIndex = _eIndex + 2; static const _gIndex = _fIndex + 2; static const _hIndex = _gIndex + 2; static const _tmp1 = _hIndex + 2; static const _tmp2 = _tmp1 + 2; static const _tmp3 = _tmp2 + 2; static const _tmp4 = _tmp3 + 2; static const _tmp5 = _tmp4 + 2; final _nums = Uint32List(12 + 16 + 10); // SHA rotate ((word >> bits) | (word << (64-bits))) void _rotr( int bits, Uint32List word, int offset, Uint32List ret, int offsetR) { _shr(bits, word, offset, _nums, _rotrIndex1); _shl(64 - bits, word, offset, _nums, _rotrIndex2); _or(_nums, _rotrIndex1, _nums, _rotrIndex2, ret, offsetR); } void _bsig0(Uint32List word, int offset, Uint32List ret, int offsetR) { _rotr(28, word, offset, _nums, _sigIndex1); _rotr(34, word, offset, _nums, _sigIndex2); _rotr(39, word, offset, _nums, _sigIndex3); _xor(_nums, _sigIndex2, _nums, _sigIndex3, _nums, _sigIndex4); _xor(_nums, _sigIndex1, _nums, _sigIndex4, ret, offsetR); } void _bsig1(Uint32List word, int offset, Uint32List ret, int offsetR) { _rotr(14, word, offset, _nums, _sigIndex1); _rotr(18, word, offset, _nums, _sigIndex2); _rotr(41, word, offset, _nums, _sigIndex3); _xor(_nums, _sigIndex2, _nums, _sigIndex3, _nums, _sigIndex4); _xor(_nums, _sigIndex1, _nums, _sigIndex4, ret, offsetR); } void _ssig0(Uint32List word, int offset, Uint32List ret, int offsetR) { _rotr(1, word, offset, _nums, _sigIndex1); _rotr(8, word, offset, _nums, _sigIndex2); _shr(7, word, offset, _nums, _sigIndex3); _xor(_nums, _sigIndex2, _nums, _sigIndex3, _nums, _sigIndex4); _xor(_nums, _sigIndex1, _nums, _sigIndex4, ret, offsetR); } void _ssig1(Uint32List word, int offset, Uint32List ret, int offsetR) { _rotr(19, word, offset, _nums, _sigIndex1); _rotr(61, word, offset, _nums, _sigIndex2); _shr(6, word, offset, _nums, _sigIndex3); _xor(_nums, _sigIndex2, _nums, _sigIndex3, _nums, _sigIndex4); _xor(_nums, _sigIndex1, _nums, _sigIndex4, ret, offsetR); } void _ch(Uint32List x, int offsetX, Uint32List y, int offsetY, Uint32List z, int offsetZ, Uint32List ret, int offsetR) { ret[0 + offsetR] = ((x[0 + offsetX] & (y[0 + offsetY] ^ z[0 + offsetZ])) ^ z[0 + offsetZ]); ret[1 + offsetR] = ((x[1 + offsetX] & (y[1 + offsetY] ^ z[1 + offsetZ])) ^ z[1 + offsetZ]); } void _maj(Uint32List x, int offsetX, Uint32List y, int offsetY, Uint32List z, int offsetZ, Uint32List ret, int offsetR) { ret[0 + offsetR] = ((x[0 + offsetX] & (y[0 + offsetY] | z[0 + offsetZ])) | (y[0 + offsetY] & z[0 + offsetZ])); ret[1 + offsetR] = ((x[1 + offsetX] & (y[1 + offsetY] | z[1 + offsetZ])) | (y[1 + offsetY] & z[1 + offsetZ])); } @override void updateHash(Uint32List chunk) { assert(chunk.length == 32); // Prepare message schedule. for (var i = 0; i < 32; i++) { _extended[i] = chunk[i]; } for (var i = 32; i < 160; i += 2) { _ssig1(_extended, i - 2 * 2, _nums, _tmp1); _add(_nums, _tmp1, _extended, i - 7 * 2, _nums, _tmp2); _ssig0(_extended, i - 15 * 2, _nums, _tmp1); _add(_nums, _tmp1, _extended, i - 16 * 2, _nums, _tmp3); _add(_nums, _tmp2, _nums, _tmp3, _extended, i); } // Shuffle around the bits. _nums.setRange(_aIndex, _hIndex + 2, _digest); for (var i = 0; i < 160; i += 2) { // temp1 = H + SHA512_SIGMA1(E) + SHA_Ch(E,F,G) + K[t] + W[t]; _bsig1(_nums, _eIndex, _nums, _tmp1); _add(_nums, _hIndex, _nums, _tmp1, _nums, _tmp2); _ch(_nums, _eIndex, _nums, _fIndex, _nums, _gIndex, _nums, _tmp3); _add(_nums, _tmp2, _nums, _tmp3, _nums, _tmp4); _add(_noise32, i, _extended, i, _nums, _tmp5); _add(_nums, _tmp4, _nums, _tmp5, _nums, _tmp1); // temp2 = SHA512_SIGMA0(A) + SHA_Maj(A,B,C); _bsig0(_nums, _aIndex, _nums, _tmp3); _maj(_nums, _aIndex, _nums, _bIndex, _nums, _cIndex, _nums, _tmp4); _add(_nums, _tmp3, _nums, _tmp4, _nums, _tmp2); _nums[_hIndex] = _nums[_gIndex]; _nums[_hIndex + 1] = _nums[_gIndex + 1]; _nums[_gIndex] = _nums[_fIndex]; _nums[_gIndex + 1] = _nums[_fIndex + 1]; _nums[_fIndex] = _nums[_eIndex]; _nums[_fIndex + 1] = _nums[_eIndex + 1]; _add(_nums, _dIndex, _nums, _tmp1, _nums, _eIndex); _nums[_dIndex] = _nums[_cIndex]; _nums[_dIndex + 1] = _nums[_cIndex + 1]; _nums[_cIndex] = _nums[_bIndex]; _nums[_cIndex + 1] = _nums[_bIndex + 1]; _nums[_bIndex] = _nums[_aIndex]; _nums[_bIndex + 1] = _nums[_aIndex + 1]; _add(_nums, _tmp1, _nums, _tmp2, _nums, _aIndex); } // Update hash values after iteration. _addTo2(_digest, 0, _nums, _aIndex); _addTo2(_digest, 2, _nums, _bIndex); _addTo2(_digest, 4, _nums, _cIndex); _addTo2(_digest, 6, _nums, _dIndex); _addTo2(_digest, 8, _nums, _eIndex); _addTo2(_digest, 10, _nums, _fIndex); _addTo2(_digest, 12, _nums, _gIndex); _addTo2(_digest, 14, _nums, _hIndex); } } /// The concrete implementation of [Sha384]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class Sha384Sink extends _Sha64BitSink { @override final digestBytes = 12; Sha384Sink(Sink<Digest> sink) : super( sink, Uint32List.fromList([ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4, ])); } /// The concrete implementation of [Sha512]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class Sha512Sink extends _Sha64BitSink { @override final digestBytes = 16; Sha512Sink(Sink<Digest> sink) : super( sink, Uint32List.fromList([ // Initial value of the hash parts. First 64 bits of the fractional // parts of the square roots of the first eight prime numbers. 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, ])); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/sha1.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:convert'; import 'dart:typed_data'; import 'digest.dart'; import 'hash.dart'; import 'hash_sink.dart'; import 'utils.dart'; /// An instance of [Sha1]. /// /// This instance provides convenient access to the [SHA-1][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc3174 final sha1 = Sha1._(); /// An implementation of the [SHA-1][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc3174 class Sha1 extends Hash { @override final int blockSize = 16 * bytesPerWord; Sha1._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(_Sha1Sink(sink)); } /// The concrete implementation of [Sha1]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public memebers. class _Sha1Sink extends HashSink { @override final digest = Uint32List(5); /// The sixteen words from the original chunk, extended to 80 words. /// /// This is an instance variable to avoid re-allocating, but its data isn't /// used across invocations of [updateHash]. final Uint32List _extended; _Sha1Sink(Sink<Digest> sink) : _extended = Uint32List(80), super(sink, 16) { digest[0] = 0x67452301; digest[1] = 0xEFCDAB89; digest[2] = 0x98BADCFE; digest[3] = 0x10325476; digest[4] = 0xC3D2E1F0; } @override void updateHash(Uint32List chunk) { assert(chunk.length == 16); var a = digest[0]; var b = digest[1]; var c = digest[2]; var d = digest[3]; var e = digest[4]; for (var i = 0; i < 80; i++) { if (i < 16) { _extended[i] = chunk[i]; } else { _extended[i] = rotl32( _extended[i - 3] ^ _extended[i - 8] ^ _extended[i - 14] ^ _extended[i - 16], 1); } var newA = add32(add32(rotl32(a, 5), e), _extended[i]); if (i < 20) { newA = add32(add32(newA, (b & c) | (~b & d)), 0x5A827999); } else if (i < 40) { newA = add32(add32(newA, (b ^ c ^ d)), 0x6ED9EBA1); } else if (i < 60) { newA = add32(add32(newA, (b & c) | (b & d) | (c & d)), 0x8F1BBCDC); } else { newA = add32(add32(newA, b ^ c ^ d), 0xCA62C1D6); } e = d; d = c; c = rotl32(b, 30); b = a; a = newA & mask32; } digest[0] = add32(a, digest[0]); digest[1] = add32(b, digest[1]); digest[2] = add32(c, digest[2]); digest[3] = add32(d, digest[3]); digest[4] = add32(e, digest[4]); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/sha256.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:convert'; import 'dart:typed_data'; import 'digest.dart'; import 'hash.dart'; import 'hash_sink.dart'; import 'utils.dart'; /// An instance of [Sha256]. /// /// This instance provides convenient access to the [Sha256][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 final sha256 = Sha256._(); /// An instance of [Sha224]. /// /// This instance provides convenient access to the [Sha224][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 final sha224 = Sha224._(); /// An implementation of the [SHA-256][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 /// /// Note that it's almost always easier to use [sha256] rather than creating a /// new instance. class Sha256 extends Hash { @override final int blockSize = 16 * bytesPerWord; Sha256._(); Sha256 newInstance() => Sha256._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(_Sha256Sink(sink)); } /// An implementation of the [SHA-224][rfc] hash function. /// /// [rfc]: http://tools.ietf.org/html/rfc6234 /// /// Note that it's almost always easier to use [sha224] rather than creating a /// new instance. class Sha224 extends Hash { @override final int blockSize = 16 * bytesPerWord; Sha224._(); Sha224 newInstance() => Sha224._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(_Sha224Sink(sink)); } /// Data from a non-linear function that functions as reproducible noise. const List<int> _noise = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, // 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; abstract class _Sha32BitSink extends HashSink { final Uint32List _digest; /// The sixteen words from the original chunk, extended to 64 words. /// /// This is an instance variable to avoid re-allocating, but its data isn't /// used across invocations of [updateHash]. final _extended = Uint32List(64); _Sha32BitSink(Sink<Digest> sink, this._digest) : super(sink, 16); // The following helper functions are taken directly from // http://tools.ietf.org/html/rfc6234. int _rotr32(int n, int x) => (x >> n) | ((x << (32 - n)) & mask32); int _ch(int x, int y, int z) => (x & y) ^ ((~x & mask32) & z); int _maj(int x, int y, int z) => (x & y) ^ (x & z) ^ (y & z); int _bsig0(int x) => _rotr32(2, x) ^ _rotr32(13, x) ^ _rotr32(22, x); int _bsig1(int x) => _rotr32(6, x) ^ _rotr32(11, x) ^ _rotr32(25, x); int _ssig0(int x) => _rotr32(7, x) ^ _rotr32(18, x) ^ (x >> 3); int _ssig1(int x) => _rotr32(17, x) ^ _rotr32(19, x) ^ (x >> 10); @override void updateHash(Uint32List chunk) { assert(chunk.length == 16); // Prepare message schedule. for (var i = 0; i < 16; i++) { _extended[i] = chunk[i]; } for (var i = 16; i < 64; i++) { _extended[i] = add32(add32(_ssig1(_extended[i - 2]), _extended[i - 7]), add32(_ssig0(_extended[i - 15]), _extended[i - 16])); } // Shuffle around the bits. var a = _digest[0]; var b = _digest[1]; var c = _digest[2]; var d = _digest[3]; var e = _digest[4]; var f = _digest[5]; var g = _digest[6]; var h = _digest[7]; for (var i = 0; i < 64; i++) { var temp1 = add32(add32(h, _bsig1(e)), add32(_ch(e, f, g), add32(_noise[i], _extended[i]))); var temp2 = add32(_bsig0(a), _maj(a, b, c)); h = g; g = f; f = e; e = add32(d, temp1); d = c; c = b; b = a; a = add32(temp1, temp2); } // Update hash values after iteration. _digest[0] = add32(a, _digest[0]); _digest[1] = add32(b, _digest[1]); _digest[2] = add32(c, _digest[2]); _digest[3] = add32(d, _digest[3]); _digest[4] = add32(e, _digest[4]); _digest[5] = add32(f, _digest[5]); _digest[6] = add32(g, _digest[6]); _digest[7] = add32(h, _digest[7]); } } /// The concrete implementation of [Sha256]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class _Sha256Sink extends _Sha32BitSink { @override Uint32List get digest => _digest; // Initial value of the hash parts. First 32 bits of the fractional parts // of the square roots of the first 8 prime numbers. _Sha256Sink(Sink<Digest> sink) : super( sink, Uint32List.fromList([ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ])); } /// The concrete implementation of [Sha224]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class _Sha224Sink extends _Sha32BitSink { @override Uint32List get digest => _digest.buffer.asUint32List(0, 7); _Sha224Sink(Sink<Digest> sink) : super( sink, Uint32List.fromList([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, ])); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/digest_sink.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 'digest.dart'; /// A sink used to get a digest value out of `Hash.startChunkedConversion`. class DigestSink extends Sink<Digest> { /// The value added to the sink, if any. Digest get value { assert(_value != null); return _value; } Digest _value; /// Adds [value] to the sink. /// /// Unlike most sinks, this may only be called once. @override void add(Digest value) { assert(_value == null); _value = value; } @override void close() { assert(_value != null); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/hmac.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:convert'; import 'dart:typed_data'; import 'digest.dart'; import 'digest_sink.dart'; import 'hash.dart'; /// An implementation of [keyed-hash method authentication codes][rfc]. /// /// [rfc]: https://tools.ietf.org/html/rfc2104 /// /// HMAC allows messages to be cryptographically authenticated using any /// iterated cryptographic hash function. class Hmac extends Converter<List<int>, Digest> { /// The hash function used to compute the authentication digest. final Hash _hash; /// The secret key shared by the sender and the receiver. final Uint8List _key; /// Create an [Hmac] object from a [Hash] and a binary key. /// /// The key should be a secret shared between the sender and receiver of the /// message. Hmac(Hash hash, List<int> key) : _hash = hash, _key = Uint8List(hash.blockSize) { // Hash the key if it's longer than the block size of the hash. if (key.length > _hash.blockSize) key = _hash.convert(key).bytes; // If [key] is shorter than the block size, the rest of [_key] will be // 0-padded. _key.setRange(0, key.length, key); } @override Digest convert(List<int> data) { var innerSink = DigestSink(); var outerSink = startChunkedConversion(innerSink); outerSink.add(data); outerSink.close(); return innerSink.value; } @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => _HmacSink(sink, _hash, _key); } /// The concrete implementation of the HMAC algorithm. class _HmacSink extends ByteConversionSink { /// The sink for the outer hash computation. final ByteConversionSink _outerSink; /// The sink that [_innerSink]'s result will be added to when it's available. final _innerResultSink = DigestSink(); /// The sink for the inner hash computation. ByteConversionSink _innerSink; /// Whether [close] has been called. bool _isClosed = false; _HmacSink(Sink<Digest> sink, Hash hash, List<int> key) : _outerSink = hash.startChunkedConversion(sink) { _innerSink = hash.startChunkedConversion(_innerResultSink); // Compute outer padding. var padding = Uint8List(key.length); for (var i = 0; i < padding.length; i++) { padding[i] = 0x5c ^ key[i]; } _outerSink.add(padding); // Compute inner padding. for (var i = 0; i < padding.length; i++) { padding[i] = 0x36 ^ key[i]; } _innerSink.add(padding); } @override void add(List<int> data) { if (_isClosed) throw StateError('HMAC is closed'); _innerSink.add(data); } @override void addSlice(List<int> data, int start, int end, bool isLast) { if (_isClosed) throw StateError('HMAC is closed'); _innerSink.addSlice(data, start, end, isLast); } @override void close() { if (_isClosed) return; _isClosed = true; _innerSink.close(); _outerSink.add(_innerResultSink.value.bytes); _outerSink.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/utils.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. /// A bitmask that limits an integer to 32 bits. const mask32 = 0xFFFFFFFF; /// The number of bits in a byte. const bitsPerByte = 8; /// The number of bytes in a 32-bit word. const bytesPerWord = 4; /// Adds [x] and [y] with 32-bit overflow semantics. int add32(int x, int y) => (x + y) & mask32; /// Bitwise rotates [val] to the left by [shift], obeying 32-bit overflow /// semantics. int rotl32(int val, int shift) { var modShift = shift & 31; return ((val << modShift) & mask32) | ((val & mask32) >> (32 - modShift)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/hash.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'digest.dart'; import 'digest_sink.dart'; /// An interface for cryptographic hash functions. /// /// Every hash is a converter that takes a list of ints and returns a single /// digest. When used in chunked mode, it will only ever add one digest to the /// inner [Sink]. abstract class Hash extends Converter<List<int>, Digest> { /// The internal block size of the hash in bytes. /// /// This is exposed for use by the `Hmac` class, which needs to know the block /// size for the [Hash] it uses. int get blockSize; const Hash(); @override Digest convert(List<int> data) { var innerSink = DigestSink(); var outerSink = startChunkedConversion(innerSink); outerSink.add(data); outerSink.close(); return innerSink.value; } @override ByteConversionSink startChunkedConversion(Sink<Digest> sink); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/crypto/src/md5.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:convert'; import 'dart:typed_data'; import 'digest.dart'; import 'hash.dart'; import 'hash_sink.dart'; import 'utils.dart'; /// An instance of [MD5]. /// /// This instance provides convenient access to the [MD5][rfc] hash function. /// /// [rfc]: https://tools.ietf.org/html/rfc1321 /// /// **Warning**: MD5 has known collisions and should only be used when required /// for backwards compatibility. final md5 = MD5._(); /// An implementation of the [MD5][rfc] hash function. /// /// [rfc]: https://tools.ietf.org/html/rfc1321 /// /// **Warning**: MD5 has known collisions and should only be used when required /// for backwards compatibility. /// /// Note that it's almost always easier to use [md5] rather than creating a new /// instance. class MD5 extends Hash { @override final int blockSize = 16 * bytesPerWord; MD5._(); @override ByteConversionSink startChunkedConversion(Sink<Digest> sink) => ByteConversionSink.from(_MD5Sink(sink)); } /// Data from a non-linear mathematical function that functions as /// reproducible noise. const _noise = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, // 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; /// Per-round shift amounts. const _shiftAmounts = [ 07, 12, 17, 22, 07, 12, 17, 22, 07, 12, 17, 22, 07, 12, 17, 22, 05, 09, 14, // 20, 05, 09, 14, 20, 05, 09, 14, 20, 05, 09, 14, 20, 04, 11, 16, 23, 04, 11, 16, 23, 04, 11, 16, 23, 04, 11, 16, 23, 06, 10, 15, 21, 06, 10, 15, 21, 06, 10, 15, 21, 06, 10, 15, 21 ]; /// The concrete implementation of [MD5]. /// /// This is separate so that it can extend [HashSink] without leaking additional /// public members. class _MD5Sink extends HashSink { @override final digest = Uint32List(4); _MD5Sink(Sink<Digest> sink) : super(sink, 16, endian: Endian.little) { digest[0] = 0x67452301; digest[1] = 0xefcdab89; digest[2] = 0x98badcfe; digest[3] = 0x10325476; } @override void updateHash(Uint32List chunk) { assert(chunk.length == 16); var a = digest[0]; var b = digest[1]; var c = digest[2]; var d = digest[3]; int e; int f; for (var i = 0; i < 64; i++) { if (i < 16) { e = (b & c) | ((~b & mask32) & d); f = i; } else if (i < 32) { e = (d & b) | ((~d & mask32) & c); f = ((5 * i) + 1) % 16; } else if (i < 48) { e = b ^ c ^ d; f = ((3 * i) + 5) % 16; } else { e = c ^ (b | (~d & mask32)); f = (7 * i) % 16; } var temp = d; d = c; c = b; b = add32( b, rotl32(add32(add32(a, e), add32(_noise[i], chunk[f])), _shiftAmounts[i])); a = temp; } digest[0] = add32(a, digest[0]); digest[1] = add32(b, digest[1]); digest[2] = add32(c, digest[2]); digest[3] = add32(d, digest[3]); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum/fixnum.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. /// Signed 32- and 64-bit integer support. /// /// The integer implementations in this library are designed to work /// identically whether executed on the Dart VM or compiled to JavaScript. library fixnum; part 'src/intx.dart'; part 'src/int32.dart'; part 'src/int64.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum/src/int32.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 fixnum; /// An immutable 32-bit signed integer, in the range [-2^31, 2^31 - 1]. /// Arithmetic operations may overflow in order to maintain this range. class Int32 implements IntX { /// The maximum positive value attainable by an [Int32], namely /// 2147483647. static const Int32 MAX_VALUE = Int32._internal(0x7FFFFFFF); /// The minimum positive value attainable by an [Int32], namely /// -2147483648. static const Int32 MIN_VALUE = Int32._internal(-0x80000000); /// An [Int32] constant equal to 0. static const Int32 ZERO = Int32._internal(0); /// An [Int32] constant equal to 1. static const Int32 ONE = Int32._internal(1); /// An [Int32] constant equal to 2. static const Int32 TWO = Int32._internal(2); // Hex digit char codes static const int _CC_0 = 48; // '0'.codeUnitAt(0) static const int _CC_9 = 57; // '9'.codeUnitAt(0) static const int _CC_a = 97; // 'a'.codeUnitAt(0) static const int _CC_z = 122; // 'z'.codeUnitAt(0) static const int _CC_A = 65; // 'A'.codeUnitAt(0) static const int _CC_Z = 90; // 'Z'.codeUnitAt(0) static int _decodeDigit(int c) { if (c >= _CC_0 && c <= _CC_9) { return c - _CC_0; } else if (c >= _CC_a && c <= _CC_z) { return c - _CC_a + 10; } else if (c >= _CC_A && c <= _CC_Z) { return c - _CC_A + 10; } else { return -1; // bad char code } } static int _validateRadix(int radix) { if (2 <= radix && radix <= 36) return radix; throw RangeError.range(radix, 2, 36, 'radix'); } /// Parses a [String] in a given [radix] between 2 and 16 and returns an /// [Int32]. // TODO(rice) - Make this faster by converting several digits at once. static Int32 parseRadix(String s, int radix) { _validateRadix(radix); Int32 x = ZERO; for (int i = 0; i < s.length; i++) { int c = s.codeUnitAt(i); int digit = _decodeDigit(c); if (digit < 0 || digit >= radix) { throw FormatException("Non-radix code unit: $c"); } x = ((x * radix) + digit) as Int32; } return x; } /// Parses a decimal [String] and returns an [Int32]. static Int32 parseInt(String s) => Int32(int.parse(s)); /// Parses a hexadecimal [String] and returns an [Int32]. static Int32 parseHex(String s) => parseRadix(s, 16); // Assumes i is <= 32-bit. static int _bitCount(int i) { // See "Hacker's Delight", section 5-1, "Counting 1-Bits". // The basic strategy is to use "divide and conquer" to // add pairs (then quads, etc.) of bits together to obtain // sub-counts. // // A straightforward approach would look like: // // i = (i & 0x55555555) + ((i >> 1) & 0x55555555); // i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F); // i = (i & 0x00FF00FF) + ((i >> 8) & 0x00FF00FF); // i = (i & 0x0000FFFF) + ((i >> 16) & 0x0000FFFF); // // The code below removes unnecessary &'s and uses a // trick to remove one instruction in the first line. i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = ((i + (i >> 4)) & 0x0F0F0F0F); i += (i >> 8); i += (i >> 16); return (i & 0x0000003F); } // Assumes i is <= 32-bit static int _numberOfLeadingZeros(int i) { i |= i >> 1; i |= i >> 2; i |= i >> 4; i |= i >> 8; i |= i >> 16; return _bitCount(~i); } static int _numberOfTrailingZeros(int i) => _bitCount((i & -i) - 1); // The internal value, kept in the range [MIN_VALUE, MAX_VALUE]. final int _i; const Int32._internal(int i) : _i = i; /// Constructs an [Int32] from an [int]. Only the low 32 bits of the input /// are used. Int32([int i = 0]) : _i = (i & 0x7fffffff) - (i & 0x80000000); // Returns the [int] representation of the specified value. Throws // [ArgumentError] for non-integer arguments. int _toInt(val) { if (val is Int32) { return val._i; } else if (val is int) { return val; } throw ArgumentError(val); } // The +, -, * , &, |, and ^ operaters deal with types as follows: // // Int32 + int => Int32 // Int32 + Int32 => Int32 // Int32 + Int64 => Int64 // // The %, ~/ and remainder operators return an Int32 even with an Int64 // argument, since the result cannot be greater than the value on the // left-hand side: // // Int32 % int => Int32 // Int32 % Int32 => Int32 // Int32 % Int64 => Int32 IntX operator +(other) { if (other is Int64) { return this.toInt64() + other; } return Int32(_i + _toInt(other)); } IntX operator -(other) { if (other is Int64) { return this.toInt64() - other; } return Int32(_i - _toInt(other)); } Int32 operator -() => Int32(-_i); IntX operator *(other) { if (other is Int64) { return this.toInt64() * other; } // TODO(rice) - optimize return (this.toInt64() * other).toInt32(); } Int32 operator %(other) { if (other is Int64) { // Result will be Int32 return (this.toInt64() % other).toInt32(); } return Int32(_i % _toInt(other)); } Int32 operator ~/(other) { if (other is Int64) { return (this.toInt64() ~/ other).toInt32(); } return Int32(_i ~/ _toInt(other)); } Int32 remainder(other) { if (other is Int64) { Int64 t = this.toInt64(); return (t - (t ~/ other) * other).toInt32(); } return (this - (this ~/ other) * other) as Int32; } Int32 operator &(other) { if (other is Int64) { return (this.toInt64() & other).toInt32(); } return Int32(_i & _toInt(other)); } Int32 operator |(other) { if (other is Int64) { return (this.toInt64() | other).toInt32(); } return Int32(_i | _toInt(other)); } Int32 operator ^(other) { if (other is Int64) { return (this.toInt64() ^ other).toInt32(); } return Int32(_i ^ _toInt(other)); } Int32 operator ~() => Int32(~_i); Int32 operator <<(int n) { if (n < 0) { throw ArgumentError(n); } if (n >= 32) { return ZERO; } return Int32(_i << n); } Int32 operator >>(int n) { if (n < 0) { throw ArgumentError(n); } if (n >= 32) { return isNegative ? const Int32._internal(-1) : ZERO; } int value; if (_i >= 0) { value = _i >> n; } else { value = (_i >> n) | (0xffffffff << (32 - n)); } return Int32(value); } Int32 shiftRightUnsigned(int n) { if (n < 0) { throw ArgumentError(n); } if (n >= 32) { return ZERO; } int value; if (_i >= 0) { value = _i >> n; } else { value = (_i >> n) & ((1 << (32 - n)) - 1); } return Int32(value); } /// Returns [:true:] if this [Int32] has the same numeric value as the /// given object. The argument may be an [int] or an [IntX]. bool operator ==(other) { if (other is Int32) { return _i == other._i; } else if (other is Int64) { return this.toInt64() == other; } else if (other is int) { return _i == other; } return false; } int compareTo(other) { if (other is Int64) { return this.toInt64().compareTo(other); } return _i.compareTo(_toInt(other)); } bool operator <(other) { if (other is Int64) { return this.toInt64() < other; } return _i < _toInt(other); } bool operator <=(other) { if (other is Int64) { return this.toInt64() <= other; } return _i <= _toInt(other); } bool operator >(other) { if (other is Int64) { return this.toInt64() > other; } return _i > _toInt(other); } bool operator >=(other) { if (other is Int64) { return this.toInt64() >= other; } return _i >= _toInt(other); } bool get isEven => (_i & 0x1) == 0; bool get isMaxValue => _i == 2147483647; bool get isMinValue => _i == -2147483648; bool get isNegative => _i < 0; bool get isOdd => (_i & 0x1) == 1; bool get isZero => _i == 0; int get bitLength => _i.bitLength; int get hashCode => _i; Int32 abs() => _i < 0 ? Int32(-_i) : this; Int32 clamp(lowerLimit, upperLimit) { if (this < lowerLimit) { if (lowerLimit is IntX) return lowerLimit.toInt32(); if (lowerLimit is int) return Int32(lowerLimit); throw ArgumentError(lowerLimit); } else if (this > upperLimit) { if (upperLimit is IntX) return upperLimit.toInt32(); if (upperLimit is int) return Int32(upperLimit); throw ArgumentError(upperLimit); } return this; } int numberOfLeadingZeros() => _numberOfLeadingZeros(_i); int numberOfTrailingZeros() => _numberOfTrailingZeros(_i); Int32 toSigned(int width) { if (width < 1 || width > 32) throw RangeError.range(width, 1, 32); return Int32(_i.toSigned(width)); } Int32 toUnsigned(int width) { if (width < 0 || width > 32) throw RangeError.range(width, 0, 32); return Int32(_i.toUnsigned(width)); } List<int> toBytes() { List<int> result = List<int>(4); result[0] = _i & 0xff; result[1] = (_i >> 8) & 0xff; result[2] = (_i >> 16) & 0xff; result[3] = (_i >> 24) & 0xff; return result; } double toDouble() => _i.toDouble(); int toInt() => _i; Int32 toInt32() => this; Int64 toInt64() => Int64(_i); String toString() => _i.toString(); String toHexString() => _i.toRadixString(16); String toRadixString(int radix) => _i.toRadixString(radix); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum/src/intx.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 fixnum; /// A fixed-precision integer. abstract class IntX implements Comparable<dynamic> { /// Addition operator. IntX operator +(other); /// Subtraction operator. IntX operator -(other); /// Negate operator. /// /// Note that `-MIN_VALUE` is equal to `MIN_VALUE` due to overflow. IntX operator -(); /// Multiplication operator. IntX operator *(other); /// Euclidean modulo operator. /// /// Returns the remainder of the euclidean division. The euclidean division /// of two integers `a` and `b` yields two integers `q` and `r` such that /// `a == b * q + r` and `0 <= r < a.abs()`. IntX operator %(other); /// Truncating division operator. IntX operator ~/(other); /// Returns the remainder of the truncating division of this integer by /// [other]. IntX remainder(other); /// Bitwise and operator. IntX operator &(other); /// Bitwise or operator. IntX operator |(other); /// Bitwise xor operator. IntX operator ^(other); /// Bitwise negate operator. IntX operator ~(); /// Left bit-shift operator. /// /// Returns the result of shifting the bits of this integer by [shiftAmount] /// bits to the left. Low-order bits are filled with zeros. IntX operator <<(int shiftAmount); /// Right bit-shift operator. /// /// Returns the result of shifting the bits of this integer by [shiftAmount] /// bits to the right. High-order bits are filled with zero in the case where /// this integer is positive, or one in the case where it is negative. IntX operator >>(int shiftAmount); /// Unsigned right-shift operator. /// /// Returns the result of shifting the bits of this integer by [shiftAmount] /// bits to the right. High-order bits are filled with zeros. IntX shiftRightUnsigned(int shiftAmount); int compareTo(other); /// Returns `true` if and only if [other] is an int or IntX equal in /// value to this integer. bool operator ==(other); /// Relational less than operator. bool operator <(other); /// Relational less than or equal to operator. bool operator <=(other); /// Relational greater than operator. bool operator >(other); /// Relational greater than or equal to operator. bool operator >=(other); /// Returns `true` if and only if this integer is even. bool get isEven; /// Returns `true` if and only if this integer is the maximum signed value /// that can be represented within its bit size. bool get isMaxValue; /// Returns `true` if and only if this integer is the minimum signed value /// that can be represented within its bit size. bool get isMinValue; /// Returns `true` if and only if this integer is less than zero. bool get isNegative; /// Returns `true` if and only if this integer is odd. bool get isOdd; /// Returns `true` if and only if this integer is zero. bool get isZero; int get hashCode; /// Returns the absolute value of this integer. IntX abs(); /// Clamps this integer to be in the range [lowerLimit] - [upperLimit]. IntX clamp(lowerLimit, upperLimit); /// Returns the minimum number of bits required to store this integer. /// /// The number of bits excludes the sign bit, which gives the natural length /// for non-negative (unsigned) values. Negative values are complemented to /// return the bit position of the first bit that differs from the sign bit. /// /// To find the the number of bits needed to store the value as a signed value, /// add one, i.e. use `x.bitLength + 1`. int get bitLength; /// Returns the number of high-order zeros in this integer's bit /// representation. int numberOfLeadingZeros(); /// Returns the number of low-order zeros in this integer's bit representation. int numberOfTrailingZeros(); /// Returns the least significant [width] bits of this integer, extending the /// highest retained bit to the sign. This is the same as truncating the value /// to fit in [width] bits using an signed 2-s complement representation. The /// returned value has the same bit value in all positions higher than [width]. /// /// If the input value fits in [width] bits without truncation, the result is /// the same as the input. The minimum width needed to avoid truncation of `x` /// is `x.bitLength + 1`, i.e. /// /// x == x.toSigned(x.bitLength + 1); IntX toSigned(int width); /// Returns the least significant [width] bits of this integer as a /// non-negative number (i.e. unsigned representation). The returned value has /// zeros in all bit positions higher than [width]. /// /// If the input fits in [width] bits without truncation, the result is the /// same as the input. The minimum width needed to avoid truncation of `x` is /// given by `x.bitLength`, i.e. /// /// x == x.toUnsigned(x.bitLength); IntX toUnsigned(int width); /// Returns a byte-sequence representation of this integer. /// /// Returns a list of int, starting with the least significant byte. List<int> toBytes(); /// Returns the double representation of this integer. /// /// On some platforms, inputs with large absolute values (i.e., > 2^52) may /// lose some of their low-order bits. double toDouble(); /// Returns the int representation of this integer. /// /// On some platforms, inputs with large absolute values (i.e., > 2^52) may /// lose some of their low-order bits. int toInt(); /// Returns an Int32 representation of this integer. /// /// Narrower values are sign-extended and wider values have their high bits /// truncated. Int32 toInt32(); /// Returns an Int64 representation of this integer. Int64 toInt64(); /// Returns a string representing the value of this integer in decimal /// notation; example: `'13'`. String toString(); /// Returns a string representing the value of this integer in hexadecimal /// notation; example: `'0xd'`. String toHexString(); /// Returns a string representing the value of this integer in the given radix. /// /// [radix] must be an integer in the range 2 .. 16, inclusive. String toRadixString(int radix); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/fixnum/src/int64.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 fixnum; /// An immutable 64-bit signed integer, in the range [-2^63, 2^63 - 1]. /// Arithmetic operations may overflow in order to maintain this range. class Int64 implements IntX { // A 64-bit integer is represented internally as three non-negative // integers, storing the 22 low, 22 middle, and 20 high bits of the // 64-bit value. _l (low) and _m (middle) are in the range // [0, 2^22 - 1] and _h (high) is in the range [0, 2^20 - 1]. // // The values being assigned to _l, _m and _h in initialization are masked to // force them into the above ranges. Sometimes we know that the value is a // small non-negative integer but the dart2js compiler can't infer that, so a // few of the masking operations are not needed for correctness but are // helpful for dart2js code quality. final int _l, _m, _h; // Note: several functions require _BITS == 22 -- do not change this value. static const int _BITS = 22; static const int _BITS01 = 44; // 2 * _BITS static const int _BITS2 = 20; // 64 - _BITS01 static const int _MASK = 4194303; // (1 << _BITS) - 1 static const int _MASK2 = 1048575; // (1 << _BITS2) - 1 static const int _SIGN_BIT = 19; // _BITS2 - 1 static const int _SIGN_BIT_MASK = 1 << _SIGN_BIT; /// The maximum positive value attainable by an [Int64], namely /// 9,223,372,036,854,775,807. static const Int64 MAX_VALUE = Int64._bits(_MASK, _MASK, _MASK2 >> 1); /// The minimum positive value attainable by an [Int64], namely /// -9,223,372,036,854,775,808. static const Int64 MIN_VALUE = Int64._bits(0, 0, _SIGN_BIT_MASK); /// An [Int64] constant equal to 0. static const Int64 ZERO = Int64._bits(0, 0, 0); /// An [Int64] constant equal to 1. static const Int64 ONE = Int64._bits(1, 0, 0); /// An [Int64] constant equal to 2. static const Int64 TWO = Int64._bits(2, 0, 0); /// Constructs an [Int64] with a given bitwise representation. No validation /// is performed. const Int64._bits(this._l, this._m, this._h); /// Parses a [String] in a given [radix] between 2 and 36 and returns an /// [Int64]. static Int64 parseRadix(String s, int radix) { return _parseRadix(s, Int32._validateRadix(radix)); } static Int64 _parseRadix(String s, int radix) { int i = 0; bool negative = false; if (i < s.length && s[0] == '-') { negative = true; i++; } // TODO(https://github.com/dart-lang/sdk/issues/38728). Replace with "if (i // >= s.length)". if (!(i < s.length)) { throw FormatException("No digits in '$s'"); } int d0 = 0, d1 = 0, d2 = 0; // low, middle, high components. for (; i < s.length; i++) { int c = s.codeUnitAt(i); int digit = Int32._decodeDigit(c); if (digit < 0 || digit >= radix) { throw FormatException("Non-radix char code: $c"); } // [radix] and [digit] are at most 6 bits, component is 22, so we can // multiply and add within 30 bit temporary values. d0 = d0 * radix + digit; int carry = d0 >> _BITS; d0 = _MASK & d0; d1 = d1 * radix + carry; carry = d1 >> _BITS; d1 = _MASK & d1; d2 = d2 * radix + carry; d2 = _MASK2 & d2; } if (negative) return _negate(d0, d1, d2); return Int64._masked(d0, d1, d2); } /// Parses a decimal [String] and returns an [Int64]. static Int64 parseInt(String s) => _parseRadix(s, 10); /// Parses a hexadecimal [String] and returns an [Int64]. static Int64 parseHex(String s) => _parseRadix(s, 16); // // Public constructors // /// Constructs an [Int64] with a given [int] value; zero by default. factory Int64([int value = 0]) { int v0 = 0, v1 = 0, v2 = 0; bool negative = false; if (value < 0) { negative = true; value = -value; } // Avoid using bitwise operations that in JavaScript coerce their input to // 32 bits. v2 = value ~/ 17592186044416; // 2^44 value -= v2 * 17592186044416; v1 = value ~/ 4194304; // 2^22 value -= v1 * 4194304; v0 = value; return negative ? Int64._negate(_MASK & v0, _MASK & v1, _MASK2 & v2) : Int64._masked(v0, v1, v2); } factory Int64.fromBytes(List<int> bytes) { int top = bytes[7] & 0xff; top <<= 8; top |= bytes[6] & 0xff; top <<= 8; top |= bytes[5] & 0xff; top <<= 8; top |= bytes[4] & 0xff; int bottom = bytes[3] & 0xff; bottom <<= 8; bottom |= bytes[2] & 0xff; bottom <<= 8; bottom |= bytes[1] & 0xff; bottom <<= 8; bottom |= bytes[0] & 0xff; return Int64.fromInts(top, bottom); } factory Int64.fromBytesBigEndian(List<int> bytes) { int top = bytes[0] & 0xff; top <<= 8; top |= bytes[1] & 0xff; top <<= 8; top |= bytes[2] & 0xff; top <<= 8; top |= bytes[3] & 0xff; int bottom = bytes[4] & 0xff; bottom <<= 8; bottom |= bytes[5] & 0xff; bottom <<= 8; bottom |= bytes[6] & 0xff; bottom <<= 8; bottom |= bytes[7] & 0xff; return Int64.fromInts(top, bottom); } /// Constructs an [Int64] from a pair of 32-bit integers having the value /// [:((top & 0xffffffff) << 32) | (bottom & 0xffffffff):]. factory Int64.fromInts(int top, int bottom) { top &= 0xffffffff; bottom &= 0xffffffff; int d0 = _MASK & bottom; int d1 = ((0xfff & top) << 10) | (0x3ff & (bottom >> _BITS)); int d2 = _MASK2 & (top >> 12); return Int64._masked(d0, d1, d2); } // Returns the [Int64] representation of the specified value. Throws // [ArgumentError] for non-integer arguments. static Int64 _promote(value) { if (value is Int64) { return value; } else if (value is int) { return Int64(value); } else if (value is Int32) { return value.toInt64(); } throw ArgumentError.value(value); } Int64 operator +(other) { Int64 o = _promote(other); int sum0 = _l + o._l; int sum1 = _m + o._m + (sum0 >> _BITS); int sum2 = _h + o._h + (sum1 >> _BITS); return Int64._masked(sum0, sum1, sum2); } Int64 operator -(other) { Int64 o = _promote(other); return _sub(_l, _m, _h, o._l, o._m, o._h); } Int64 operator -() => _negate(_l, _m, _h); Int64 operator *(other) { Int64 o = _promote(other); // Grab 13-bit chunks. int a0 = _l & 0x1fff; int a1 = (_l >> 13) | ((_m & 0xf) << 9); int a2 = (_m >> 4) & 0x1fff; int a3 = (_m >> 17) | ((_h & 0xff) << 5); int a4 = (_h & 0xfff00) >> 8; int b0 = o._l & 0x1fff; int b1 = (o._l >> 13) | ((o._m & 0xf) << 9); int b2 = (o._m >> 4) & 0x1fff; int b3 = (o._m >> 17) | ((o._h & 0xff) << 5); int b4 = (o._h & 0xfff00) >> 8; // Compute partial products. // Optimization: if b is small, avoid multiplying by parts that are 0. int p0 = a0 * b0; // << 0 int p1 = a1 * b0; // << 13 int p2 = a2 * b0; // << 26 int p3 = a3 * b0; // << 39 int p4 = a4 * b0; // << 52 if (b1 != 0) { p1 += a0 * b1; p2 += a1 * b1; p3 += a2 * b1; p4 += a3 * b1; } if (b2 != 0) { p2 += a0 * b2; p3 += a1 * b2; p4 += a2 * b2; } if (b3 != 0) { p3 += a0 * b3; p4 += a1 * b3; } if (b4 != 0) { p4 += a0 * b4; } // Accumulate into 22-bit chunks: // .........................................c10|...................c00| // |....................|..................xxxx|xxxxxxxxxxxxxxxxxxxxxx| p0 // |....................|......................|......................| // |....................|...................c11|......c01.............| // |....................|....xxxxxxxxxxxxxxxxxx|xxxxxxxxx.............| p1 // |....................|......................|......................| // |.................c22|...............c12....|......................| // |..........xxxxxxxxxx|xxxxxxxxxxxxxxxxxx....|......................| p2 // |....................|......................|......................| // |.................c23|..c13.................|......................| // |xxxxxxxxxxxxxxxxxxxx|xxxxx.................|......................| p3 // |....................|......................|......................| // |.........c24........|......................|......................| // |xxxxxxxxxxxx........|......................|......................| p4 int c00 = p0 & 0x3fffff; int c01 = (p1 & 0x1ff) << 13; int c0 = c00 + c01; int c10 = p0 >> 22; int c11 = p1 >> 9; int c12 = (p2 & 0x3ffff) << 4; int c13 = (p3 & 0x1f) << 17; int c1 = c10 + c11 + c12 + c13; int c22 = p2 >> 18; int c23 = p3 >> 5; int c24 = (p4 & 0xfff) << 8; int c2 = c22 + c23 + c24; // Propagate high bits from c0 -> c1, c1 -> c2. c1 += c0 >> _BITS; c2 += c1 >> _BITS; return Int64._masked(c0, c1, c2); } Int64 operator %(other) => _divide(this, other, _RETURN_MOD); Int64 operator ~/(other) => _divide(this, other, _RETURN_DIV); Int64 remainder(other) => _divide(this, other, _RETURN_REM); Int64 operator &(other) { Int64 o = _promote(other); int a0 = _l & o._l; int a1 = _m & o._m; int a2 = _h & o._h; return Int64._masked(a0, a1, a2); } Int64 operator |(other) { Int64 o = _promote(other); int a0 = _l | o._l; int a1 = _m | o._m; int a2 = _h | o._h; return Int64._masked(a0, a1, a2); } Int64 operator ^(other) { Int64 o = _promote(other); int a0 = _l ^ o._l; int a1 = _m ^ o._m; int a2 = _h ^ o._h; return Int64._masked(a0, a1, a2); } Int64 operator ~() { return Int64._masked(~_l, ~_m, ~_h); } Int64 operator <<(int n) { if (n < 0) { throw ArgumentError.value(n); } if (n >= 64) { return ZERO; } int res0, res1, res2; if (n < _BITS) { res0 = _l << n; res1 = (_m << n) | (_l >> (_BITS - n)); res2 = (_h << n) | (_m >> (_BITS - n)); } else if (n < _BITS01) { res0 = 0; res1 = _l << (n - _BITS); res2 = (_m << (n - _BITS)) | (_l >> (_BITS01 - n)); } else { res0 = 0; res1 = 0; res2 = _l << (n - _BITS01); } return Int64._masked(res0, res1, res2); } Int64 operator >>(int n) { if (n < 0) { throw ArgumentError.value(n); } if (n >= 64) { return isNegative ? const Int64._bits(_MASK, _MASK, _MASK2) : ZERO; } int res0, res1, res2; // Sign extend h(a). int a2 = _h; bool negative = (a2 & _SIGN_BIT_MASK) != 0; if (negative && _MASK > _MASK2) { // Add extra one bits on the left so the sign gets shifted into the wider // lower words. a2 += (_MASK - _MASK2); } if (n < _BITS) { res2 = _shiftRight(a2, n); if (negative) { res2 |= _MASK2 & ~(_MASK2 >> n); } res1 = _shiftRight(_m, n) | (a2 << (_BITS - n)); res0 = _shiftRight(_l, n) | (_m << (_BITS - n)); } else if (n < _BITS01) { res2 = negative ? _MASK2 : 0; res1 = _shiftRight(a2, n - _BITS); if (negative) { res1 |= _MASK & ~(_MASK >> (n - _BITS)); } res0 = _shiftRight(_m, n - _BITS) | (a2 << (_BITS01 - n)); } else { res2 = negative ? _MASK2 : 0; res1 = negative ? _MASK : 0; res0 = _shiftRight(a2, n - _BITS01); if (negative) { res0 |= _MASK & ~(_MASK >> (n - _BITS01)); } } return Int64._masked(res0, res1, res2); } Int64 shiftRightUnsigned(int n) { if (n < 0) { throw ArgumentError.value(n); } if (n >= 64) { return ZERO; } int res0, res1, res2; int a2 = _MASK2 & _h; // Ensure a2 is positive. if (n < _BITS) { res2 = a2 >> n; res1 = (_m >> n) | (a2 << (_BITS - n)); res0 = (_l >> n) | (_m << (_BITS - n)); } else if (n < _BITS01) { res2 = 0; res1 = a2 >> (n - _BITS); res0 = (_m >> (n - _BITS)) | (_h << (_BITS01 - n)); } else { res2 = 0; res1 = 0; res0 = a2 >> (n - _BITS01); } return Int64._masked(res0, res1, res2); } /// Returns [:true:] if this [Int64] has the same numeric value as the /// given object. The argument may be an [int] or an [IntX]. bool operator ==(other) { Int64 o; if (other is Int64) { o = other; } else if (other is int) { if (_h == 0 && _m == 0) return _l == other; // Since we know one of [_h] or [_m] is non-zero, if [other] fits in the // low word then it can't be numerically equal. if ((_MASK & other) == other) return false; o = Int64(other); } else if (other is Int32) { o = other.toInt64(); } if (o != null) { return _l == o._l && _m == o._m && _h == o._h; } return false; } int compareTo(other) => _compareTo(other); int _compareTo(other) { Int64 o = _promote(other); int signa = _h >> (_BITS2 - 1); int signb = o._h >> (_BITS2 - 1); if (signa != signb) { return signa == 0 ? 1 : -1; } if (_h > o._h) { return 1; } else if (_h < o._h) { return -1; } if (_m > o._m) { return 1; } else if (_m < o._m) { return -1; } if (_l > o._l) { return 1; } else if (_l < o._l) { return -1; } return 0; } bool operator <(other) => _compareTo(other) < 0; bool operator <=(other) => _compareTo(other) <= 0; bool operator >(other) => this._compareTo(other) > 0; bool operator >=(other) => _compareTo(other) >= 0; bool get isEven => (_l & 0x1) == 0; bool get isMaxValue => (_h == _MASK2 >> 1) && _m == _MASK && _l == _MASK; bool get isMinValue => _h == _SIGN_BIT_MASK && _m == 0 && _l == 0; bool get isNegative => (_h & _SIGN_BIT_MASK) != 0; bool get isOdd => (_l & 0x1) == 1; bool get isZero => _h == 0 && _m == 0 && _l == 0; int get bitLength { if (isZero) return 0; int a0 = _l, a1 = _m, a2 = _h; if (isNegative) { a0 = _MASK & ~a0; a1 = _MASK & ~a1; a2 = _MASK2 & ~a2; } if (a2 != 0) return _BITS01 + a2.bitLength; if (a1 != 0) return _BITS + a1.bitLength; return a0.bitLength; } /// Returns a hash code based on all the bits of this [Int64]. int get hashCode { // TODO(sra): Should we ensure that hashCode values match corresponding int? // i.e. should `new Int64(x).hashCode == x.hashCode`? int bottom = ((_m & 0x3ff) << _BITS) | _l; int top = (_h << 12) | ((_m >> 10) & 0xfff); return bottom ^ top; } Int64 abs() { return this.isNegative ? -this : this; } Int64 clamp(lowerLimit, upperLimit) { Int64 lower = _promote(lowerLimit); Int64 upper = _promote(upperLimit); if (this < lower) return lower; if (this > upper) return upper; return this; } /// Returns the number of leading zeros in this [Int64] as an [int] /// between 0 and 64. int numberOfLeadingZeros() { int b2 = Int32._numberOfLeadingZeros(_h); if (b2 == 32) { int b1 = Int32._numberOfLeadingZeros(_m); if (b1 == 32) { return Int32._numberOfLeadingZeros(_l) + 32; } else { return b1 + _BITS2 - (32 - _BITS); } } else { return b2 - (32 - _BITS2); } } /// Returns the number of trailing zeros in this [Int64] as an [int] /// between 0 and 64. int numberOfTrailingZeros() { int zeros = Int32._numberOfTrailingZeros(_l); if (zeros < 32) { return zeros; } zeros = Int32._numberOfTrailingZeros(_m); if (zeros < 32) { return _BITS + zeros; } zeros = Int32._numberOfTrailingZeros(_h); if (zeros < 32) { return _BITS01 + zeros; } // All zeros return 64; } Int64 toSigned(int width) { if (width < 1 || width > 64) throw RangeError.range(width, 1, 64); if (width > _BITS01) { return Int64._masked(_l, _m, _h.toSigned(width - _BITS01)); } else if (width > _BITS) { int m = _m.toSigned(width - _BITS); return m.isNegative ? Int64._masked(_l, m, _MASK2) : Int64._masked(_l, m, 0); // Masking for type inferrer. } else { int l = _l.toSigned(width); return l.isNegative ? Int64._masked(l, _MASK, _MASK2) : Int64._masked(l, 0, 0); // Masking for type inferrer. } } Int64 toUnsigned(int width) { if (width < 0 || width > 64) throw RangeError.range(width, 0, 64); if (width > _BITS01) { int h = _h.toUnsigned(width - _BITS01); return Int64._masked(_l, _m, h); } else if (width > _BITS) { int m = _m.toUnsigned(width - _BITS); return Int64._masked(_l, m, 0); } else { int l = _l.toUnsigned(width); return Int64._masked(l, 0, 0); } } List<int> toBytes() { List<int> result = List<int>(8); result[0] = _l & 0xff; result[1] = (_l >> 8) & 0xff; result[2] = ((_m << 6) & 0xfc) | ((_l >> 16) & 0x3f); result[3] = (_m >> 2) & 0xff; result[4] = (_m >> 10) & 0xff; result[5] = ((_h << 4) & 0xf0) | ((_m >> 18) & 0xf); result[6] = (_h >> 4) & 0xff; result[7] = (_h >> 12) & 0xff; return result; } double toDouble() => toInt().toDouble(); int toInt() { int l = _l; int m = _m; int h = _h; // In the sum we add least significant to most significant so that in // JavaScript double arithmetic rounding occurs on only the last addition. if ((_h & _SIGN_BIT_MASK) != 0) { l = _MASK & ~_l; m = _MASK & ~_m; h = _MASK2 & ~_h; return -((1 + l) + (4194304 * m) + (17592186044416 * h)); } else { return l + (4194304 * m) + (17592186044416 * h); } } /// Returns an [Int32] containing the low 32 bits of this [Int64]. Int32 toInt32() { return Int32(((_m & 0x3ff) << _BITS) | _l); } /// Returns `this`. Int64 toInt64() => this; /// Returns the value of this [Int64] as a decimal [String]. String toString() => _toRadixString(10); // TODO(rice) - Make this faster by avoiding arithmetic. String toHexString() { if (isZero) return "0"; Int64 x = this; String hexStr = ""; while (!x.isZero) { int digit = x._l & 0xf; hexStr = "${_hexDigit(digit)}$hexStr"; x = x.shiftRightUnsigned(4); } return hexStr; } /// Returns the digits of `this` when interpreted as an unsigned 64-bit value. @pragma('dart2js:noInline') String toStringUnsigned() { return _toRadixStringUnsigned(10, _l, _m, _h, ''); } @pragma('dart2js:noInline') String toRadixStringUnsigned(int radix) { return _toRadixStringUnsigned(Int32._validateRadix(radix), _l, _m, _h, ''); } String toRadixString(int radix) { return _toRadixString(Int32._validateRadix(radix)); } String _toRadixString(int radix) { int d0 = _l; int d1 = _m; int d2 = _h; String sign = ''; if ((d2 & _SIGN_BIT_MASK) != 0) { sign = '-'; // Negate in-place. d0 = 0 - d0; int borrow = (d0 >> _BITS) & 1; d0 &= _MASK; d1 = 0 - d1 - borrow; borrow = (d1 >> _BITS) & 1; d1 &= _MASK; d2 = 0 - d2 - borrow; d2 &= _MASK2; // d2, d1, d0 now are an unsigned 64 bit integer for MIN_VALUE and an // unsigned 63 bit integer for other values. } return _toRadixStringUnsigned(radix, d0, d1, d2, sign); } static String _toRadixStringUnsigned( int radix, int d0, int d1, int d2, String sign) { if (d0 == 0 && d1 == 0 && d2 == 0) return '0'; // Rearrange components into five components where all but the most // significant are 10 bits wide. // // d4, d3, d4, d1, d0: 24 + 10 + 10 + 10 + 10 bits // // The choice of 10 bits allows a remainder of 20 bits to be scaled by 10 // bits and added during division while keeping all intermediate values // within 30 bits (unsigned small integer range for 32 bit implementations // of Dart VM and V8). // // 6 6 5 4 3 2 1 // 3210987654321098765432109876543210987654321098765432109876543210 // [--------d2--------][---------d1---------][---------d0---------] // --> // [----------d4----------][---d3---][---d2---][---d1---][---d0---] int d4 = (d2 << 4) | (d1 >> 18); int d3 = (d1 >> 8) & 0x3ff; d2 = ((d1 << 2) | (d0 >> 20)) & 0x3ff; d1 = (d0 >> 10) & 0x3ff; d0 = d0 & 0x3ff; int fatRadix = _fatRadixTable[radix]; // Generate chunks of digits. In radix 10, generate 6 digits per chunk. // // This loop generates at most 3 chunks, so we store the chunks in locals // rather than a list. We are trying to generate digits 20 bits at a time // until we have only 30 bits left. 20 + 20 + 30 > 64 would imply that we // need only two chunks, but radix values 17-19 and 33-36 generate only 15 // or 16 bits per iteration, so sometimes the third chunk is needed. String chunk1 = "", chunk2 = "", chunk3 = ""; while (!(d4 == 0 && d3 == 0)) { int q = d4 ~/ fatRadix; int r = d4 - q * fatRadix; d4 = q; d3 += r << 10; q = d3 ~/ fatRadix; r = d3 - q * fatRadix; d3 = q; d2 += r << 10; q = d2 ~/ fatRadix; r = d2 - q * fatRadix; d2 = q; d1 += r << 10; q = d1 ~/ fatRadix; r = d1 - q * fatRadix; d1 = q; d0 += r << 10; q = d0 ~/ fatRadix; r = d0 - q * fatRadix; d0 = q; assert(chunk3 == ""); chunk3 = chunk2; chunk2 = chunk1; // Adding [fatRadix] Forces an extra digit which we discard to get a fixed // width. E.g. (1000000 + 123) -> "1000123" -> "000123". An alternative // would be to pad to the left with zeroes. chunk1 = (fatRadix + r).toRadixString(radix).substring(1); } int residue = (d2 << 20) + (d1 << 10) + d0; String leadingDigits = residue == 0 ? '' : residue.toRadixString(radix); return '$sign$leadingDigits$chunk1$chunk2$chunk3'; } // Table of 'fat' radix values. Each entry for index `i` is the largest power // of `i` whose remainder fits in 20 bits. static const _fatRadixTable = <int>[ 0, 0, 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2, 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3, 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 6 * 6 * 6 * 6 * 6 * 6 * 6, 7 * 7 * 7 * 7 * 7 * 7 * 7, 8 * 8 * 8 * 8 * 8 * 8, 9 * 9 * 9 * 9 * 9 * 9, 10 * 10 * 10 * 10 * 10 * 10, 11 * 11 * 11 * 11 * 11, 12 * 12 * 12 * 12 * 12, 13 * 13 * 13 * 13 * 13, 14 * 14 * 14 * 14 * 14, 15 * 15 * 15 * 15 * 15, 16 * 16 * 16 * 16 * 16, 17 * 17 * 17 * 17, 18 * 18 * 18 * 18, 19 * 19 * 19 * 19, 20 * 20 * 20 * 20, 21 * 21 * 21 * 21, 22 * 22 * 22 * 22, 23 * 23 * 23 * 23, 24 * 24 * 24 * 24, 25 * 25 * 25 * 25, 26 * 26 * 26 * 26, 27 * 27 * 27 * 27, 28 * 28 * 28 * 28, 29 * 29 * 29 * 29, 30 * 30 * 30 * 30, 31 * 31 * 31 * 31, 32 * 32 * 32 * 32, 33 * 33 * 33, 34 * 34 * 34, 35 * 35 * 35, 36 * 36 * 36 ]; String toDebugString() { return "Int64[_l=$_l, _m=$_m, _h=$_h]"; } static Int64 _masked(int a0, int a1, int a2) => Int64._bits(_MASK & a0, _MASK & a1, _MASK2 & a2); static Int64 _sub(int a0, int a1, int a2, int b0, int b1, int b2) { int diff0 = a0 - b0; int diff1 = a1 - b1 - ((diff0 >> _BITS) & 1); int diff2 = a2 - b2 - ((diff1 >> _BITS) & 1); return _masked(diff0, diff1, diff2); } static Int64 _negate(int b0, int b1, int b2) { return _sub(0, 0, 0, b0, b1, b2); } String _hexDigit(int digit) => "0123456789ABCDEF"[digit]; // Work around dart2js bugs with negative arguments to '>>' operator. static int _shiftRight(int x, int n) { if (x >= 0) { return x >> n; } else { int shifted = x >> n; if (shifted >= 0x80000000) { shifted -= 4294967296; } return shifted; } } // Implementation of '~/', '%' and 'remainder'. static Int64 _divide(Int64 a, other, int what) { Int64 b = _promote(other); if (b.isZero) { throw const IntegerDivisionByZeroException(); } if (a.isZero) return ZERO; bool aNeg = a.isNegative; bool bNeg = b.isNegative; a = a.abs(); b = b.abs(); int a0 = a._l; int a1 = a._m; int a2 = a._h; int b0 = b._l; int b1 = b._m; int b2 = b._h; return _divideHelper(a0, a1, a2, aNeg, b0, b1, b2, bNeg, what); } static const _RETURN_DIV = 1; static const _RETURN_REM = 2; static const _RETURN_MOD = 3; static Int64 _divideHelper( // up to 64 bits unsigned in a2/a1/a0 and b2/b1/b0 int a0, int a1, int a2, bool aNeg, // input A. int b0, int b1, int b2, bool bNeg, // input B. int what) { int q0 = 0, q1 = 0, q2 = 0; // result Q. int r0 = 0, r1 = 0, r2 = 0; // result R. if (b2 == 0 && b1 == 0 && b0 < (1 << (30 - _BITS))) { // Small divisor can be handled by single-digit division within Smi range. // // Handling small divisors here helps the estimate version below by // handling cases where the estimate is off by more than a small amount. q2 = a2 ~/ b0; int carry = a2 - q2 * b0; int d1 = a1 + (carry << _BITS); q1 = d1 ~/ b0; carry = d1 - q1 * b0; int d0 = a0 + (carry << _BITS); q0 = d0 ~/ b0; r0 = d0 - q0 * b0; } else { // Approximate Q = A ~/ B and R = A - Q * B using doubles. // The floating point approximation is very close to the correct value // when floor(A/B) fits in fewer that 53 bits. // We use double arithmetic for intermediate values. Double arithmetic on // non-negative values is exact under the following conditions: // // - The values are integer values that fit in 53 bits. // - Dividing by powers of two (adjusts exponent only). // - Floor (zeroes bits with fractional weight). const double K2 = 17592186044416.0; // 2^44 const double K1 = 4194304.0; // 2^22 // Approximate double values for [a] and [b]. double ad = a0 + K1 * a1 + K2 * a2; double bd = b0 + K1 * b1 + K2 * b2; // Approximate quotient. double qd = (ad / bd).floorToDouble(); // Extract components of [qd] using double arithmetic. double q2d = (qd / K2).floorToDouble(); qd = qd - K2 * q2d; double q1d = (qd / K1).floorToDouble(); double q0d = qd - K1 * q1d; q2 = q2d.toInt(); q1 = q1d.toInt(); q0 = q0d.toInt(); assert(q0 + K1 * q1 + K2 * q2 == (ad / bd).floorToDouble()); assert(q2 == 0 || b2 == 0); // Q and B can't both be big since Q*B <= A. // P = Q * B, using doubles to hold intermediates. // We don't need all partial sums since Q*B <= A. double p0d = q0d * b0; double p0carry = (p0d / K1).floorToDouble(); p0d = p0d - p0carry * K1; double p1d = q1d * b0 + q0d * b1 + p0carry; double p1carry = (p1d / K1).floorToDouble(); p1d = p1d - p1carry * K1; double p2d = q2d * b0 + q1d * b1 + q0d * b2 + p1carry; assert(p2d <= _MASK2); // No partial sum overflow. // R = A - P int diff0 = a0 - p0d.toInt(); int diff1 = a1 - p1d.toInt() - ((diff0 >> _BITS) & 1); int diff2 = a2 - p2d.toInt() - ((diff1 >> _BITS) & 1); r0 = _MASK & diff0; r1 = _MASK & diff1; r2 = _MASK2 & diff2; // while (R < 0 || R >= B) // adjust R towards [0, B) while (r2 >= _SIGN_BIT_MASK || r2 > b2 || (r2 == b2 && (r1 > b1 || (r1 == b1 && r0 >= b0)))) { // Direction multiplier for adjustment. int m = (r2 & _SIGN_BIT_MASK) == 0 ? 1 : -1; // R = R - B or R = R + B int d0 = r0 - m * b0; int d1 = r1 - m * (b1 + ((d0 >> _BITS) & 1)); int d2 = r2 - m * (b2 + ((d1 >> _BITS) & 1)); r0 = _MASK & d0; r1 = _MASK & d1; r2 = _MASK2 & d2; // Q = Q + 1 or Q = Q - 1 d0 = q0 + m; d1 = q1 + m * ((d0 >> _BITS) & 1); d2 = q2 + m * ((d1 >> _BITS) & 1); q0 = _MASK & d0; q1 = _MASK & d1; q2 = _MASK2 & d2; } } // 0 <= R < B assert(Int64.ZERO <= Int64._bits(r0, r1, r2)); assert(r2 < b2 || // Handles case where B = -(MIN_VALUE) Int64._bits(r0, r1, r2) < Int64._bits(b0, b1, b2)); assert(what == _RETURN_DIV || what == _RETURN_MOD || what == _RETURN_REM); if (what == _RETURN_DIV) { if (aNeg != bNeg) return _negate(q0, q1, q2); return Int64._masked(q0, q1, q2); // Masking for type inferrer. } if (!aNeg) { return Int64._masked(r0, r1, r2); // Masking for type inferrer. } if (what == _RETURN_MOD) { if (r0 == 0 && r1 == 0 && r2 == 0) { return ZERO; } else { return _sub(b0, b1, b2, r0, r1, r2); } } else { return _negate(r0, r1, r2); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/external_state_snapshot.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. // TODO(ahe): Remove this file. import 'package:kernel/kernel.dart' show Library, Component; /// Helper class to work around modifications in [kernel_generator_impl.dart]. class ExternalStateSnapshot { final List<ExternalState> snapshots; ExternalStateSnapshot(Component component) : snapshots = new List<ExternalState>.from( component.libraries.map((l) => new ExternalState(l, l.isExternal))); void restore() { for (ExternalState state in snapshots) { state.restore(); } } } class ExternalState { final Library library; final bool isExternal; ExternalState(this.library, this.isExternal); void restore() { library.isExternal = isExternal; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scheme_based_file_system.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 'api_prototype/file_system.dart'; /// A [FileSystem] that delegates to other file systems based on the URI scheme. class SchemeBasedFileSystem implements FileSystem { final Map<String, FileSystem> fileSystemByScheme; SchemeBasedFileSystem(this.fileSystemByScheme); @override FileSystemEntity entityForUri(Uri uri) { FileSystem delegate = fileSystemByScheme[uri.scheme]; if (delegate == null) { throw new FileSystemException( uri, "SchemeBasedFileSystem doesn't handle URIs with " "scheme '${uri.scheme}': $uri"); } return delegate.entityForUri(uri); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/compute_platform_binaries_location.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:io" show File, Platform; import 'package:kernel/ast.dart' show Source; import 'base/processed_options.dart' show ProcessedOptions; import 'fasta/compiler_context.dart' show CompilerContext; /// Computes the location of platform binaries, that is, compiled `.dill` files /// of the platform libraries that are used to avoid recompiling those /// libraries. Uri computePlatformBinariesLocation({bool forceBuildDir: false}) { // The directory of the Dart VM executable. Uri vmDirectory = Uri.base .resolveUri(new Uri.file(Platform.resolvedExecutable)) .resolve("."); if (vmDirectory.path.endsWith("/bin/")) { // Looks like the VM is in a `/bin/` directory, so this is running from a // built SDK. return vmDirectory.resolve(forceBuildDir ? "../../" : "../lib/_internal/"); } else { // We assume this is running from a build directory (for example, // `out/ReleaseX64` or `xcodebuild/ReleaseX64`). return vmDirectory; } } /// Translates an SDK URI ("org-dartlang-sdk:///...") to a file URI. Uri translateSdk(Uri uri) { if (CompilerContext.isActive) { if (uri.scheme == "org-dartlang-sdk") { String path = uri.path; if (path.startsWith("/sdk/")) { CompilerContext context = CompilerContext.current; Uri sdkRoot = context.cachedSdkRoot; if (sdkRoot == null) { ProcessedOptions options = context.options; sdkRoot = options.sdkRoot; if (sdkRoot == null) { sdkRoot = options.librariesSpecificationUri?.resolve("../"); if (sdkRoot != null) { if (!isExistingFile(sdkRoot.resolve("lib/libraries.json"))) { sdkRoot = null; } } } if (sdkRoot == null) { sdkRoot = (options.sdkSummary ?? computePlatformBinariesLocation()) .resolve("../../"); if (sdkRoot != null) { if (!isExistingFile(sdkRoot.resolve("lib/libraries.json"))) { if (isExistingFile(sdkRoot.resolve("sdk/lib/libraries.json"))) { sdkRoot = sdkRoot.resolve("sdk/"); } else { sdkRoot = null; } } } } sdkRoot ??= Uri.parse("org-dartlang-sdk:///sdk/"); context.cachedSdkRoot = sdkRoot; } Uri candidate = sdkRoot.resolve(path.substring(5)); if (isExistingFile(candidate)) { Map<Uri, Source> uriToSource = CompilerContext.current.uriToSource; Source source = uriToSource[uri]; if (source.source.isEmpty) { uriToSource[uri] = new Source( source.lineStarts, new File.fromUri(candidate).readAsBytesSync(), source.importUri, source.fileUri); } } return candidate; } } } return uri; } bool isExistingFile(Uri uri) { if (uri.scheme == "file") { return new File.fromUri(uri).existsSync(); } else { return false; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/kernel_generator_impl.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. /// Defines the front-end API for converting source code to Dart Kernel objects. library front_end.kernel_generator_impl; import 'dart:async' show Future; import 'package:front_end/src/fasta/kernel/kernel_api.dart'; import 'package:kernel/kernel.dart' show Component, CanonicalName; import 'base/processed_options.dart' show ProcessedOptions; import 'fasta/compiler_context.dart' show CompilerContext; import 'fasta/crash.dart' show withCrashReporting; import 'fasta/dill/dill_target.dart' show DillTarget; import 'fasta/fasta_codes.dart' show LocatedMessage; import 'fasta/kernel/kernel_target.dart' show KernelTarget; import 'fasta/kernel/utils.dart' show printComponentText, serializeComponent; import 'fasta/kernel/verifier.dart' show verifyComponent; import 'fasta/loader.dart' show Loader; import 'fasta/severity.dart' show Severity; import 'fasta/uri_translator.dart' show UriTranslator; import 'api_prototype/front_end.dart' show CompilerResult; import 'api_prototype/file_system.dart' show FileSystem; /// Implementation for the /// `package:front_end/src/api_prototype/kernel_generator.dart` and /// `package:front_end/src/api_prototype/summary_generator.dart` APIs. Future<CompilerResult> generateKernel(ProcessedOptions options, {bool buildSummary: false, bool buildComponent: true, bool truncateSummary: false, bool includeOffsets: true, bool includeHierarchyAndCoreTypes: false}) async { return await CompilerContext.runWithOptions(options, (_) async { return await generateKernelInternal( buildSummary: buildSummary, buildComponent: buildComponent, truncateSummary: truncateSummary, includeOffsets: includeOffsets, includeHierarchyAndCoreTypes: includeHierarchyAndCoreTypes); }); } Future<CompilerResult> generateKernelInternal( {bool buildSummary: false, bool buildComponent: true, bool truncateSummary: false, bool includeOffsets: true, bool retainDataForTesting: false, bool includeHierarchyAndCoreTypes: false}) async { ProcessedOptions options = CompilerContext.current.options; FileSystem fs = options.fileSystem; Loader sourceLoader; return withCrashReporting<CompilerResult>(() async { UriTranslator uriTranslator = await options.getUriTranslator(); DillTarget dillTarget = new DillTarget(options.ticker, uriTranslator, options.target); Set<Uri> externalLibs(Component component) { return component.libraries .where((lib) => lib.isExternal) .map((lib) => lib.importUri) .toSet(); } Component sdkSummary = await options.loadSdkSummary(null); // By using the nameRoot of the the summary, we enable sharing the // sdkSummary between multiple invocations. CanonicalName nameRoot = sdkSummary?.root ?? new CanonicalName.root(); if (sdkSummary != null) { Set<Uri> excluded = externalLibs(sdkSummary); dillTarget.loader.appendLibraries(sdkSummary, filter: (uri) => !excluded.contains(uri)); } // TODO(sigmund): provide better error reporting if input summaries or // linked dependencies were listed out of order (or provide mechanism to // sort them). for (Component inputSummary in await options.loadInputSummaries(nameRoot)) { Set<Uri> excluded = externalLibs(inputSummary); dillTarget.loader.appendLibraries(inputSummary, filter: (uri) => !excluded.contains(uri)); } // All summaries are considered external and shouldn't include source-info. dillTarget.loader.libraries.forEach((lib) { // TODO(ahe): Don't do this, and remove [external_state_snapshot.dart]. lib.isExternal = true; }); // Linked dependencies are meant to be part of the component so they are not // marked external. for (Component dependency in await options.loadLinkDependencies(nameRoot)) { Set<Uri> excluded = externalLibs(dependency); dillTarget.loader.appendLibraries(dependency, filter: (uri) => !excluded.contains(uri)); } await dillTarget.buildOutlines(); KernelTarget kernelTarget = new KernelTarget(fs, false, dillTarget, uriTranslator); sourceLoader = kernelTarget.loader; kernelTarget.setEntryPoints(options.inputs); Component summaryComponent = await kernelTarget.buildOutlines(nameRoot: nameRoot); List<int> summary = null; if (buildSummary) { if (options.verify) { for (LocatedMessage error in verifyComponent(summaryComponent)) { options.report(error, Severity.error); } } if (options.debugDump) { printComponentText(summaryComponent, libraryFilter: kernelTarget.isSourceLibrary); } // Create the requested component ("truncating" or not). // // Note: we don't pass the library argument to the constructor to // preserve the the libraries parent pointer (it should continue to point // to the component within KernelTarget). Component trimmedSummaryComponent = new Component(nameRoot: summaryComponent.root) ..libraries.addAll(truncateSummary ? kernelTarget.loader.libraries : summaryComponent.libraries); trimmedSummaryComponent.metadata.addAll(summaryComponent.metadata); trimmedSummaryComponent.uriToSource.addAll(summaryComponent.uriToSource); // As documented, we only run outline transformations when we are building // summaries without building a full component (at this time, that's // the only need we have for these transformations). if (!buildComponent) { options.target.performOutlineTransformations(trimmedSummaryComponent); options.ticker.logMs("Transformed outline"); } // Don't include source (but do add it above to include importUris). summary = serializeComponent(trimmedSummaryComponent, includeSources: false, includeOffsets: includeOffsets); options.ticker.logMs("Generated outline"); } Component component; if (buildComponent) { component = await kernelTarget.buildComponent(verify: options.verify); if (options.debugDump) { printComponentText(component, libraryFilter: kernelTarget.isSourceLibrary); } options.ticker.logMs("Generated component"); } return new InternalCompilerResult( summary: summary, component: component, classHierarchy: includeHierarchyAndCoreTypes ? kernelTarget.loader.hierarchy : null, coreTypes: includeHierarchyAndCoreTypes ? kernelTarget.loader.coreTypes : null, deps: new List<Uri>.from(CompilerContext.current.dependencies), kernelTargetForTesting: retainDataForTesting ? kernelTarget : null); }, () => sourceLoader?.currentUriForCrashReporting ?? options.inputs.first); } /// Result object of [generateKernel]. class InternalCompilerResult implements CompilerResult { /// The generated summary bytes, if it was requested. final List<int> summary; /// The generated component, if it was requested. final Component component; /// Dependencies traversed by the compiler. Used only for generating /// dependency .GN files in the dart-sdk build system. /// Note this might be removed when we switch to compute dependencies without /// using the compiler itself. final List<Uri> deps; final ClassHierarchy classHierarchy; final CoreTypes coreTypes; /// The [KernelTarget] used to generated the component. /// /// This is only provided for use in testing. final KernelTarget kernelTargetForTesting; InternalCompilerResult( {this.summary, this.component, this.deps, this.classHierarchy, this.coreTypes, this.kernelTargetForTesting}); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/features.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 'id_testing.dart'; /// Utility class for annotated testing representing a set of features. class Features { Map<String, Object> _features = {}; Set<String> _unsorted = new Set<String>(); /// Mark the feature [key] as existing. If [value] is provided, the feature /// [key] is set to have this value. void add(String key, {var value: ''}) { _features[key] = value.toString(); } /// Add [value] as an element of the list values of feature [key]. void addElement(String key, [var value]) { List<String> list = _features.putIfAbsent(key, () => <String>[]); if (value != null) { list.add(value.toString()); } } /// Marks list values of [key] as unsorted. This prevents the [getText] /// representation from automatically sorting the values. void markAsUnsorted(String key) { _unsorted.add(key); } /// Returns `true` if feature [key] exists. bool containsKey(String key) { return _features.containsKey(key); } /// Set the feature [key] to exist with the [value]. void operator []=(String key, String value) { _features[key] = value; } /// Returns the value set for feature [key]. Object operator [](String key) => _features[key]; /// Removes the value set for feature [key]. Returns the existing value. Object remove(String key) => _features.remove(key); /// Returns `true` if this feature set is empty. bool get isEmpty => _features.isEmpty; /// Returns `true` if this feature set is non-empty. bool get isNotEmpty => _features.isNotEmpty; /// Call [f] for each feature in this feature set with its corresponding /// value. void forEach(void Function(String, Object) f) { _features.forEach(f); } /// Returns a string containing all features in a comma-separated list sorted /// by feature names. String getText() { StringBuffer sb = new StringBuffer(); bool needsComma = false; for (String name in _features.keys.toList()..sort()) { dynamic value = _features[name]; if (value != null) { if (needsComma) { sb.write(','); } sb.write(name); if (value is List<String>) { if (_unsorted.contains(name)) { value = '[${value.join(',')}]'; } else { value = '[${(value..sort()).join(',')}]'; } } if (value != '') { sb.write('='); sb.write(value); } needsComma = true; } } return sb.toString(); } @override String toString() => 'Features(${getText()})'; /// Creates a [Features] object by parse the [text] encoding. /// /// Single features will be parsed as strings and list features (features /// encoded in `[...]` will be parsed as lists of strings. static Features fromText(String text) { Features features = new Features(); if (text == null) return features; int index = 0; while (index < text.length) { int eqPos = text.indexOf('=', index); int commaPos = text.indexOf(',', index); String name; bool hasValue = false; if (eqPos != -1 && commaPos != -1) { if (eqPos < commaPos) { name = text.substring(index, eqPos); hasValue = true; index = eqPos + 1; } else { name = text.substring(index, commaPos); index = commaPos + 1; } } else if (eqPos != -1) { name = text.substring(index, eqPos); hasValue = true; index = eqPos + 1; } else if (commaPos != -1) { name = text.substring(index, commaPos); index = commaPos + 1; } else { name = text.substring(index); index = text.length; } if (hasValue) { const Map<String, String> delimiters = const { '[': ']', '{': '}', '(': ')', '<': '>' }; List<String> endDelimiters = <String>[]; bool isList = index < text.length && text.startsWith('[', index); if (isList) { features.addElement(name); endDelimiters.add(']'); index++; } int valueStart = index; while (index < text.length) { String char = text.substring(index, index + 1); if (endDelimiters.isNotEmpty && endDelimiters.last == char) { endDelimiters.removeLast(); index++; } else { String endDelimiter = delimiters[char]; if (endDelimiter != null) { endDelimiters.add(endDelimiter); index++; } else if (char == ',') { if (endDelimiters.isEmpty) { break; } else if (endDelimiters.length == 1 && isList) { String value = text.substring(valueStart, index); features.addElement(name, value); index++; valueStart = index; } else { index++; } } else { index++; } } } if (isList) { String value = text.substring(valueStart, index - 1); if (value.isNotEmpty) { features.addElement(name, value); } } else { String value = text.substring(valueStart, index); features.add(name, value: value); } index++; } else { features.add(name); } } return features; } } class FeaturesDataInterpreter implements DataInterpreter<Features> { const FeaturesDataInterpreter(); @override String isAsExpected(Features actualFeatures, String expectedData) { if (expectedData == '*') { return null; } else if (expectedData == '') { return actualFeatures.isNotEmpty ? "Expected empty data." : null; } else { List<String> errorsFound = []; Features expectedFeatures = Features.fromText(expectedData); Set<String> validatedFeatures = new Set<String>(); expectedFeatures.forEach((String key, Object expectedValue) { bool expectMatch = true; if (key.startsWith('!')) { key = key.substring(1); expectMatch = false; } validatedFeatures.add(key); Object actualValue = actualFeatures[key]; if (!expectMatch) { if (actualFeatures.containsKey(key)) { errorsFound.add('Unexpected data found for $key=$actualValue'); } } else if (!actualFeatures.containsKey(key)) { errorsFound.add('No data found for $key'); } else if (expectedValue == '') { if (actualValue != '') { errorsFound.add('Non-empty data found for $key'); } } else if (expectedValue == '*') { return; } else if (expectedValue is List) { if (actualValue is List) { List actualList = actualValue.toList(); for (Object expectedObject in expectedValue) { String expectedText = '$expectedObject'; bool matchFound = false; if (expectedText.endsWith('*')) { // Wildcard matcher. String prefix = expectedText.substring(0, expectedText.indexOf('*')); List matches = []; for (Object actualObject in actualList) { if ('$actualObject'.startsWith(prefix)) { matches.add(actualObject); matchFound = true; } } for (Object match in matches) { actualList.remove(match); } } else { for (Object actualObject in actualList) { if (expectedText == '$actualObject') { actualList.remove(actualObject); matchFound = true; break; } } } if (!matchFound) { errorsFound.add("No match found for $key=[$expectedText]"); } } if (actualList.isNotEmpty) { errorsFound .add("Extra data found $key=[${actualList.join(',')}]"); } } else { errorsFound.add("List data expected for $key: " "expected '$expectedValue', found '${actualValue}'"); } } else if (expectedValue != actualValue) { errorsFound.add("Mismatch for $key: expected '$expectedValue', " "found '${actualValue}'"); } }); actualFeatures.forEach((String key, Object value) { if (!validatedFeatures.contains(key)) { if (value == '') { errorsFound.add("Extra data found '$key'"); } else { errorsFound.add("Extra data found $key=$value"); } } }); return errorsFound.isNotEmpty ? errorsFound.join('\n ') : null; } } @override String getText(Features actualData) { return actualData.getText(); } @override bool isEmpty(Features actualData) { return actualData == null || actualData.isEmpty; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/id_testing_utils.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:kernel/ast.dart'; import '../fasta/builder/builder.dart'; import '../fasta/builder/extension_builder.dart'; import '../fasta/kernel/kernel_builder.dart'; import '../fasta/messages.dart'; import '../fasta/source/source_library_builder.dart'; import '../fasta/source/source_loader.dart'; import '../kernel_generator_impl.dart'; /// Helper methods to use in annotated tests. /// Returns a canonical simple name for [member]. String getMemberName(Member member) { if (member is Procedure && member.isSetter) return '${member.name.name}='; return member.name.name; } /// Returns the enclosing [Member] for [node]. Member getEnclosingMember(TreeNode node) { while (node is! Member) { node = node.parent; } return node; } /// Finds the first [Library] in [component] with the given import [uri]. /// /// If [required] is `true` an error is thrown if no library was found. Library lookupLibrary(Component component, Uri uri, {bool required: true}) { return component.libraries .firstWhere((Library library) => library.importUri == uri, orElse: () { if (required) { throw new ArgumentError("Library '$uri' not found."); } return null; }); } /// Finds the first [Class] in [library] with the given [className]. /// /// If [required] is `true` an error is thrown if no class was found. Class lookupClass(Library library, String className, {bool required: true}) { return library.classes.firstWhere((Class cls) => cls.name == className, orElse: () { if (required) { throw new ArgumentError("Class '$className' not found in '$library'."); } return null; }); } /// Finds the first [Extension] in [library] with the given [className]. /// /// If [required] is `true` an error is thrown if no class was found. Extension lookupExtension(Library library, String extensionName, {bool required: true}) { return library.extensions.firstWhere( (Extension extension) => extension.name == extensionName, orElse: () { if (required) { throw new ArgumentError( "Extension '$extensionName' not found in '${library.importUri}'."); } return null; }); } /// Finds the first [Member] in [library] with the given canonical simple /// [memberName] as computed by [getMemberName]. /// /// If [required] is `true` an error is thrown if no member was found. Member lookupLibraryMember(Library library, String memberName, {bool required: true}) { return library.members.firstWhere( (Member member) => getMemberName(member) == memberName, orElse: () { if (required) { throw new ArgumentError("Member '$memberName' not found in '$library'."); } return null; }); } /// Finds the first [Member] in [cls] with the given canonical simple /// [memberName] as computed by [getMemberName]. /// /// If [required] is `true` an error is thrown if no member was found. Member lookupClassMember(Class cls, String memberName, {bool required: true}) { return cls.members.firstWhere( (Member member) => getMemberName(member) == memberName, orElse: () { if (required) { throw new ArgumentError("Member '$memberName' not found in '$cls'."); } return null; }); } LibraryBuilder lookupLibraryBuilder( InternalCompilerResult compilerResult, Library library, {bool required: true}) { SourceLoader loader = compilerResult.kernelTargetForTesting.loader; SourceLibraryBuilder builder = loader.builders[library.importUri]; if (builder == null && required) { throw new ArgumentError("DeclarationBuilder for $library not found."); } return builder; } TypeParameterScopeBuilder lookupLibraryDeclarationBuilder( InternalCompilerResult compilerResult, Library library, {bool required: true}) { SourceLibraryBuilder builder = lookupLibraryBuilder(compilerResult, library, required: required); return builder.libraryDeclaration; } ClassBuilder lookupClassBuilder( InternalCompilerResult compilerResult, Class cls, {bool required: true}) { TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder( compilerResult, cls.enclosingLibrary, required: required); ClassBuilder clsBuilder = libraryBuilder.members[cls.name]; if (clsBuilder == null && required) { throw new ArgumentError("ClassBuilder for $cls not found."); } return clsBuilder; } ExtensionBuilder lookupExtensionBuilder( InternalCompilerResult compilerResult, Extension extension, {bool required: true}) { TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder( compilerResult, extension.enclosingLibrary, required: required); ExtensionBuilder extensionBuilder = libraryBuilder.members[extension.name]; if (extensionBuilder == null && required) { throw new ArgumentError("ExtensionBuilder for $extension not found."); } return extensionBuilder; } /// Look up the [MemberBuilder] for [member] through the [ClassBuilder] for /// [cls] using [memberName] as its name. MemberBuilder lookupClassMemberBuilder(InternalCompilerResult compilerResult, Class cls, Member member, String memberName, {bool required: true}) { ClassBuilder classBuilder = lookupClassBuilder(compilerResult, cls, required: required); MemberBuilder memberBuilder; if (classBuilder != null) { if (member is Constructor || member is Procedure && member.isFactory) { memberBuilder = classBuilder.constructors.local[memberName]; } else if (member is Procedure && member.isSetter) { memberBuilder = classBuilder.scope.setters[memberName]; } else { memberBuilder = classBuilder.scope.local[memberName]; } } if (memberBuilder == null && required) { throw new ArgumentError("MemberBuilder for $member not found."); } return memberBuilder; } MemberBuilder lookupMemberBuilder( InternalCompilerResult compilerResult, Member member, {bool required: true}) { MemberBuilder memberBuilder; if (member.isExtensionMember) { String memberName = member.name.name; String extensionName = memberName.substring(0, memberName.indexOf('|')); memberName = memberName.substring(extensionName.length + 1); bool isSetter = member is Procedure && member.isSetter; if (memberName.startsWith('set#')) { memberName = memberName.substring(4); isSetter = true; } else if (memberName.startsWith('get#')) { memberName = memberName.substring(4); } Extension extension = lookupExtension(member.enclosingLibrary, extensionName); memberBuilder = lookupExtensionMemberBuilder( compilerResult, extension, member, memberName, isSetter: isSetter, required: required); } else if (member.enclosingClass != null) { memberBuilder = lookupClassMemberBuilder( compilerResult, member.enclosingClass, member, member.name.name, required: required); } else { TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder( compilerResult, member.enclosingLibrary); if (member is Procedure && member.isSetter) { memberBuilder = libraryBuilder.members[member.name.name]; } else { memberBuilder = libraryBuilder.setters[member.name.name]; } } if (memberBuilder == null && required) { throw new ArgumentError("MemberBuilder for $member not found."); } return memberBuilder; } /// Look up the [MemberBuilder] for [member] through the [ExtensionBuilder] for /// [extension] using [memberName] as its name. MemberBuilder lookupExtensionMemberBuilder( InternalCompilerResult compilerResult, Extension extension, Member member, String memberName, {bool isSetter: false, bool required: true}) { ExtensionBuilder extensionBuilder = lookupExtensionBuilder(compilerResult, extension, required: required); MemberBuilder memberBuilder; if (extensionBuilder != null) { if (isSetter) { memberBuilder = extensionBuilder.scope.setters[memberName]; } else { memberBuilder = extensionBuilder.scope.local[memberName]; } } if (memberBuilder == null && required) { throw new ArgumentError("MemberBuilder for $member not found."); } return memberBuilder; } /// Returns a textual representation of the constant [node] to be used in /// testing. String constantToText(Constant node) { StringBuffer sb = new StringBuffer(); new ConstantToTextVisitor(sb).visit(node); return sb.toString(); } /// Returns a textual representation of the type [node] to be used in /// testing. String typeToText(DartType node) { StringBuffer sb = new StringBuffer(); new DartTypeToTextVisitor(sb).visit(node); return sb.toString(); } class ConstantToTextVisitor implements ConstantVisitor<void> { final StringBuffer sb; final DartTypeToTextVisitor typeToText; ConstantToTextVisitor(this.sb) : typeToText = new DartTypeToTextVisitor(sb); void visit(Constant node) => node.accept(this); void visitList(Iterable<Constant> nodes) { String comma = ''; for (Constant node in nodes) { sb.write(comma); visit(node); comma = ','; } } void defaultConstant(Constant node) => throw new UnimplementedError( 'Unexpected constant $node (${node.runtimeType})'); void visitNullConstant(NullConstant node) { sb.write('Null()'); } void visitBoolConstant(BoolConstant node) { sb.write('Bool(${node.value})'); } void visitIntConstant(IntConstant node) { sb.write('Int(${node.value})'); } void visitDoubleConstant(DoubleConstant node) { sb.write('Double(${node.value})'); } void visitStringConstant(StringConstant node) { sb.write('String(${node.value})'); } void visitSymbolConstant(SymbolConstant node) { sb.write('Symbol(${node.name})'); } void visitMapConstant(MapConstant node) { sb.write('Map<'); typeToText.visit(node.keyType); sb.write(','); typeToText.visit(node.valueType); sb.write('>('); String comma = ''; for (ConstantMapEntry entry in node.entries) { sb.write(comma); entry.key.accept(this); sb.write(':'); entry.value.accept(this); comma = ','; } sb.write(')'); } void visitListConstant(ListConstant node) { sb.write('List<'); typeToText.visit(node.typeArgument); sb.write('>('); visitList(node.entries); sb.write(')'); } void visitSetConstant(SetConstant node) { sb.write('Set<'); typeToText.visit(node.typeArgument); sb.write('>('); visitList(node.entries); sb.write(')'); } void visitInstanceConstant(InstanceConstant node) { sb.write('Instance('); sb.write(node.classNode.name); if (node.typeArguments.isNotEmpty) { sb.write('<'); typeToText.visitList(node.typeArguments); sb.write('>'); } if (node.fieldValues.isNotEmpty) { sb.write(',{'); String comma = ''; for (Reference ref in node.fieldValues.keys) { sb.write(comma); sb.write(getMemberName(ref.asField)); sb.write(':'); visit(node.fieldValues[ref]); comma = ','; } sb.write('}'); } sb.write(')'); } void visitPartialInstantiationConstant(PartialInstantiationConstant node) { sb.write('Instantiation('); sb.write(getMemberName(node.tearOffConstant.procedure)); sb.write('<'); typeToText.visitList(node.types); sb.write('>)'); } void visitTearOffConstant(TearOffConstant node) { sb.write('Function('); sb.write(getMemberName(node.procedure)); sb.write(')'); } void visitTypeLiteralConstant(TypeLiteralConstant node) { sb.write('TypeLiteral('); typeToText.visit(node.type); sb.write(')'); } void visitUnevaluatedConstant(UnevaluatedConstant node) { sb.write('Unevaluated()'); } } class DartTypeToTextVisitor implements DartTypeVisitor<void> { final StringBuffer sb; DartTypeToTextVisitor(this.sb); void visit(DartType node) => node.accept(this); void visitList(Iterable<DartType> nodes) { String comma = ''; for (DartType node in nodes) { sb.write(comma); visit(node); comma = ','; } } void defaultDartType(DartType node) => throw new UnimplementedError( 'Unexpected type $node (${node.runtimeType})'); void visitInvalidType(InvalidType node) { sb.write('<invalid>'); } void visitDynamicType(DynamicType node) { sb.write('dynamic'); } void visitVoidType(VoidType node) { sb.write('void'); } void visitBottomType(BottomType node) { sb.write('<bottom>'); } void visitInterfaceType(InterfaceType node) { sb.write(node.classNode.name); if (node.typeArguments.isNotEmpty) { sb.write('<'); visitList(node.typeArguments); sb.write('>'); } } void visitFunctionType(FunctionType node) { sb.write('('); String comma = ''; visitList(node.positionalParameters.take(node.requiredParameterCount)); if (node.requiredParameterCount > 0) { comma = ','; } if (node.requiredParameterCount < node.positionalParameters.length) { sb.write(comma); sb.write('['); visitList(node.positionalParameters.skip(node.requiredParameterCount)); sb.write(']'); comma = ','; } if (node.namedParameters.isNotEmpty) { sb.write(comma); sb.write('{'); comma = ''; for (NamedType namedParameter in node.namedParameters) { sb.write(comma); visit(namedParameter.type); sb.write(' '); sb.write(namedParameter.name); comma = ','; } sb.write('}'); } sb.write(')->'); visit(node.returnType); } void visitTypeParameterType(TypeParameterType node) { sb.write(node.parameter.name); if (node.promotedBound != null) { sb.write(' extends '); visit(node.promotedBound); } } void visitTypedefType(TypedefType node) { sb.write(node.typedefNode.name); if (node.typeArguments.isNotEmpty) { sb.write('<'); visitList(node.typeArguments); sb.write('>'); } } } /// Returns `true` if [type] is `Object` from `dart:core`. bool isObject(DartType type) { return type is InterfaceType && type.classNode.name == 'Object' && '${type.classNode.enclosingLibrary.importUri}' == 'dart:core'; } /// Returns a textual representation of the [typeParameter] to be used in /// testing. String typeParameterToText(TypeParameter typeParameter) { String name = typeParameter.name; if (!isObject(typeParameter.bound)) { return '$name extends ${typeToText(typeParameter.bound)}'; } return name; } /// Returns a textual representation of the [type] to be used in testing. String typeBuilderToText(TypeBuilder type) { StringBuffer sb = new StringBuffer(); _typeBuilderToText(type, sb); return sb.toString(); } void _typeBuilderToText(TypeBuilder type, StringBuffer sb) { if (type is NamedTypeBuilder) { sb.write(type.name); if (type.arguments != null && type.arguments.isNotEmpty) { sb.write('<'); _typeBuildersToText(type.arguments, sb); sb.write('>'); } } else { throw 'Unhandled type builder $type (${type.runtimeType})'; } } void _typeBuildersToText(Iterable<TypeBuilder> types, StringBuffer sb) { String comma = ''; for (TypeBuilder type in types) { sb.write(comma); _typeBuilderToText(type, sb); comma = ','; } } /// Returns a textual representation of the [typeVariable] to be used in /// testing. String typeVariableBuilderToText(TypeVariableBuilder typeVariable) { String name = typeVariable.name; if (typeVariable.bound != null) { return '$name extends ${typeBuilderToText(typeVariable.bound)}'; } return name; } /// Returns a textual representation of [errors] to be used in testing. String errorsToText(List<FormattedMessage> errors) { return errors.map((m) => m.message).join(','); } /// Returns a textual representation of [descriptor] to be used in testing. String extensionMethodDescriptorToText(ExtensionMemberDescriptor descriptor) { StringBuffer sb = new StringBuffer(); if (descriptor.isStatic) { sb.write('static '); } switch (descriptor.kind) { case ExtensionMemberKind.Method: break; case ExtensionMemberKind.Getter: sb.write('getter '); break; case ExtensionMemberKind.Setter: sb.write('setter '); break; case ExtensionMemberKind.Operator: sb.write('operator '); break; case ExtensionMemberKind.Field: sb.write('field '); break; case ExtensionMemberKind.TearOff: sb.write('tearoff '); break; } sb.write(descriptor.name.name); sb.write('='); Member member = descriptor.member.asMember; String name = member.name.name; if (member is Procedure && member.isSetter) { sb.write('$name='); } else { sb.write(name); } return sb.toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/id_extractor.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:kernel/ast.dart'; import 'id.dart'; /// Compute a canonical [Id] for kernel-based nodes. Id computeMemberId(Member node) { String className; if (node.enclosingClass != null) { className = node.enclosingClass.name; } String memberName = node.name.name; if (node is Procedure && node.kind == ProcedureKind.Setter) { memberName += '='; } return new MemberId.internal(memberName, className: className); } TreeNode computeTreeNodeWithOffset(TreeNode node) { while (node != null) { if (node.fileOffset != TreeNode.noOffset) { return node; } node = node.parent; } return null; } /// Abstract visitor for computing data corresponding to a node or element, /// and record it with a generic [Id] abstract class DataExtractor<T> extends Visitor with DataRegistry<T> { @override final Map<Id, ActualData<T>> actualMap; /// Implement this to compute the data corresponding to [library]. /// /// If `null` is returned, [library] has no associated data. T computeLibraryValue(Id id, Library library) => null; /// Implement this to compute the data corresponding to [cls]. /// /// If `null` is returned, [cls] has no associated data. T computeClassValue(Id id, Class cls) => null; /// Implement this to compute the data corresponding to [extension]. /// /// If `null` is returned, [extension] has no associated data. T computeExtensionValue(Id id, Extension extension) => null; /// Implement this to compute the data corresponding to [member]. /// /// If `null` is returned, [member] has no associated data. T computeMemberValue(Id id, Member member) => null; /// Implement this to compute the data corresponding to [node]. /// /// If `null` is returned, [node] has no associated data. T computeNodeValue(Id id, TreeNode node) => null; DataExtractor(this.actualMap); void computeForLibrary(Library library) { LibraryId id = new LibraryId(library.fileUri); T value = computeLibraryValue(id, library); registerValue(library.fileUri, null, id, value, library); } void computeForClass(Class cls) { ClassId id = new ClassId(cls.name); T value = computeClassValue(id, cls); TreeNode nodeWithOffset = computeTreeNodeWithOffset(cls); registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset, id, value, cls); } void computeForExtension(Extension extension) { ClassId id = new ClassId(extension.name); T value = computeExtensionValue(id, extension); TreeNode nodeWithOffset = computeTreeNodeWithOffset(extension); registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset, id, value, extension); } void computeForMember(Member member) { MemberId id = computeMemberId(member); if (id == null) return; T value = computeMemberValue(id, member); TreeNode nodeWithOffset = computeTreeNodeWithOffset(member); registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset, id, value, member); } void computeForNode(TreeNode node, NodeId id) { if (id == null) return; T value = computeNodeValue(id, node); TreeNode nodeWithOffset = computeTreeNodeWithOffset(node); registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset, id, value, node); } NodeId computeDefaultNodeId(TreeNode node, {bool skipNodeWithNoOffset: false}) { if (skipNodeWithNoOffset && node.fileOffset == TreeNode.noOffset) { return null; } assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on $node (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.node); } NodeId createInvokeId(TreeNode node) { assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on ${node} (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.invoke); } NodeId createUpdateId(TreeNode node) { assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on ${node} (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.update); } NodeId createIteratorId(ForInStatement node) { assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on ${node} (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.iterator); } NodeId createCurrentId(ForInStatement node) { assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on ${node} (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.current); } NodeId createMoveNextId(ForInStatement node) { assert(node.fileOffset != TreeNode.noOffset, "No fileOffset on ${node} (${node.runtimeType})"); return new NodeId(node.fileOffset, IdKind.moveNext); } NodeId createLabeledStatementId(LabeledStatement node) => computeDefaultNodeId(node.body); NodeId createLoopId(TreeNode node) => computeDefaultNodeId(node); NodeId createGotoId(TreeNode node) => computeDefaultNodeId(node); NodeId createSwitchId(SwitchStatement node) => computeDefaultNodeId(node); NodeId createSwitchCaseId(SwitchCase node) => new NodeId(node.expressionOffsets.first, IdKind.node); NodeId createImplicitAsId(AsExpression node) { if (node.fileOffset == TreeNode.noOffset) { // TODO(johnniwinther): Find out why we something have no offset. return null; } return new NodeId(node.fileOffset, IdKind.implicitAs); } void run(Node root) { root.accept(this); } @override defaultNode(Node node) { node.visitChildren(this); } @override visitProcedure(Procedure node) { // Avoid visiting annotations. node.function.accept(this); computeForMember(node); } @override visitConstructor(Constructor node) { // Avoid visiting annotations. visitList(node.initializers, this); node.function.accept(this); computeForMember(node); } @override visitField(Field node) { // Avoid visiting annotations. node.initializer?.accept(this); computeForMember(node); } @override visitMethodInvocation(MethodInvocation node) { TreeNode receiver = node.receiver; if (receiver is VariableGet && receiver.variable.parent is FunctionDeclaration) { // This is an invocation of a named local function. computeForNode(node, createInvokeId(node.receiver)); node.arguments.accept(this); } else if (node.name.name == '==' && receiver is VariableGet && receiver.variable.name == null) { // This is a desugared `?.`. } else if (node.name.name == '[]') { computeForNode(node, computeDefaultNodeId(node)); super.visitMethodInvocation(node); } else if (node.name.name == '[]=') { computeForNode(node, createUpdateId(node)); super.visitMethodInvocation(node); } else { computeForNode(node, createInvokeId(node)); super.visitMethodInvocation(node); } } @override visitLoadLibrary(LoadLibrary node) { computeForNode(node, createInvokeId(node)); } @override visitPropertyGet(PropertyGet node) { computeForNode(node, computeDefaultNodeId(node)); super.visitPropertyGet(node); } @override visitVariableDeclaration(VariableDeclaration node) { if (node.name != null && node.parent is! FunctionDeclaration) { // Skip synthetic variables and function declaration variables. computeForNode(node, computeDefaultNodeId(node)); } // Avoid visiting annotations. node.initializer?.accept(this); } @override visitFunctionDeclaration(FunctionDeclaration node) { computeForNode(node, computeDefaultNodeId(node)); super.visitFunctionDeclaration(node); } @override visitFunctionExpression(FunctionExpression node) { computeForNode(node, computeDefaultNodeId(node)); super.visitFunctionExpression(node); } @override visitVariableGet(VariableGet node) { if (node.variable.name != null && !node.variable.isFieldFormal) { // Skip use of synthetic variables. computeForNode(node, computeDefaultNodeId(node)); } super.visitVariableGet(node); } @override visitPropertySet(PropertySet node) { computeForNode(node, createUpdateId(node)); super.visitPropertySet(node); } @override visitVariableSet(VariableSet node) { if (node.variable.name != null) { // Skip use of synthetic variables. computeForNode(node, createUpdateId(node)); } super.visitVariableSet(node); } @override visitDoStatement(DoStatement node) { computeForNode(node, createLoopId(node)); super.visitDoStatement(node); } @override visitForStatement(ForStatement node) { computeForNode(node, createLoopId(node)); super.visitForStatement(node); } @override visitForInStatement(ForInStatement node) { computeForNode(node, createLoopId(node)); computeForNode(node, createIteratorId(node)); computeForNode(node, createCurrentId(node)); computeForNode(node, createMoveNextId(node)); super.visitForInStatement(node); } @override visitWhileStatement(WhileStatement node) { computeForNode(node, createLoopId(node)); super.visitWhileStatement(node); } @override visitLabeledStatement(LabeledStatement node) { // TODO(johnniwinther): Call computeForNode for label statements that are // not placeholders for loop and switch targets. super.visitLabeledStatement(node); } @override visitBreakStatement(BreakStatement node) { computeForNode(node, createGotoId(node)); super.visitBreakStatement(node); } @override visitSwitchStatement(SwitchStatement node) { computeForNode(node, createSwitchId(node)); super.visitSwitchStatement(node); } @override visitSwitchCase(SwitchCase node) { if (node.expressionOffsets.isNotEmpty) { computeForNode(node, createSwitchCaseId(node)); } super.visitSwitchCase(node); } @override visitContinueSwitchStatement(ContinueSwitchStatement node) { computeForNode(node, createGotoId(node)); super.visitContinueSwitchStatement(node); } @override visitConstantExpression(ConstantExpression node) { // Implicit constants (for instance omitted field initializers, implicit // default values) and synthetic constants (for instance in noSuchMethod // forwarders) have no offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitConstantExpression(node); } @override visitNullLiteral(NullLiteral node) { // Synthetic null literals, for instance in locals and fields without // initializers, have no offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitNullLiteral(node); } @override visitBoolLiteral(BoolLiteral node) { computeForNode(node, computeDefaultNodeId(node)); super.visitBoolLiteral(node); } @override visitIntLiteral(IntLiteral node) { // Synthetic ints literals, for instance in enum fields, have no offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitIntLiteral(node); } @override visitDoubleLiteral(DoubleLiteral node) { computeForNode(node, computeDefaultNodeId(node)); super.visitDoubleLiteral(node); } @override visitStringLiteral(StringLiteral node) { // Synthetic string literals, for instance in enum fields, have no offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitStringLiteral(node); } @override visitListLiteral(ListLiteral node) { // Synthetic list literals,for instance in noSuchMethod forwarders, have no // offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitListLiteral(node); } @override visitMapLiteral(MapLiteral node) { // Synthetic map literals, for instance in noSuchMethod forwarders, have no // offset. computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitMapLiteral(node); } @override visitSetLiteral(SetLiteral node) { computeForNode(node, computeDefaultNodeId(node)); super.visitSetLiteral(node); } @override visitThisExpression(ThisExpression node) { TreeNode parent = node.parent; if (node.fileOffset == TreeNode.noOffset || (parent is PropertyGet || parent is PropertySet || parent is MethodInvocation) && parent.fileOffset == node.fileOffset) { // Skip implicit this expressions. } else { computeForNode(node, computeDefaultNodeId(node)); } super.visitThisExpression(node); } @override visitAwaitExpression(AwaitExpression node) { computeForNode(node, computeDefaultNodeId(node)); super.visitAwaitExpression(node); } @override visitConstructorInvocation(ConstructorInvocation node) { // Skip synthetic constructor invocations like for enum constants. // TODO(johnniwinther): Can [skipNodeWithNoOffset] be removed when dart2js // no longer test with cfe constants? computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); super.visitConstructorInvocation(node); } @override visitStaticGet(StaticGet node) { computeForNode(node, computeDefaultNodeId(node)); super.visitStaticGet(node); } @override visitStaticSet(StaticSet node) { computeForNode(node, createUpdateId(node)); super.visitStaticSet(node); } @override visitStaticInvocation(StaticInvocation node) { computeForNode(node, createInvokeId(node)); super.visitStaticInvocation(node); } @override visitAsExpression(AsExpression node) { if (node.isTypeError) { computeForNode(node, createImplicitAsId(node)); } else { computeForNode(node, computeDefaultNodeId(node)); } return super.visitAsExpression(node); } @override visitArguments(Arguments node) { computeForNode( node, computeDefaultNodeId(node, skipNodeWithNoOffset: true)); return super.visitArguments(node); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/compiler_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. /// Common compiler options and helper functions used for testing. library front_end.testing.compiler_options_common; import 'dart:async' show Future; import 'package:kernel/ast.dart' show Library, Component; import '../api_prototype/front_end.dart' show CompilerOptions, CompilerResult, kernelForModule, kernelForProgramInternal, summaryFor; import '../api_prototype/memory_file_system.dart' show MemoryFileSystem, MemoryFileSystemEntity; import '../compute_platform_binaries_location.dart' show computePlatformBinariesLocation; import '../fasta/hybrid_file_system.dart' show HybridFileSystem; /// Generate kernel for a script. /// /// [scriptOrSources] can be a String, in which case it is the script to be /// compiled, or a Map containing source files. In which case, this function /// compiles the entry whose name is [fileName]. /// /// Wraps [kernelForProgram] with some default testing options (see [setup]). Future<CompilerResult> compileScript(dynamic scriptOrSources, {fileName: 'main.dart', List<String> inputSummaries: const [], List<String> linkedDependencies: const [], CompilerOptions options, bool retainDataForTesting: false}) async { options ??= new CompilerOptions(); Map<String, dynamic> sources; if (scriptOrSources is String) { sources = {fileName: scriptOrSources}; } else { assert(scriptOrSources is Map); sources = scriptOrSources; } await setup(options, sources, inputSummaries: inputSummaries, linkedDependencies: linkedDependencies); return await kernelForProgramInternal(toTestUri(fileName), options, retainDataForTesting: retainDataForTesting); } /// Generate a component for a modular compilation unit. /// /// Wraps [kernelForModule] with some default testing options (see [setup]). Future<Component> compileUnit(List<String> inputs, Map<String, dynamic> sources, {List<String> inputSummaries: const [], List<String> linkedDependencies: const [], CompilerOptions options}) async { options ??= new CompilerOptions(); await setup(options, sources, inputSummaries: inputSummaries, linkedDependencies: linkedDependencies); return (await kernelForModule(inputs.map(toTestUri).toList(), options)) .component; } /// Generate a summary for a modular compilation unit. /// /// Wraps [summaryFor] with some default testing options (see [setup]). Future<List<int>> summarize(List<String> inputs, Map<String, dynamic> sources, {List<String> inputSummaries: const [], CompilerOptions options, bool truncate: false}) async { options ??= new CompilerOptions(); await setup(options, sources, inputSummaries: inputSummaries); return await summaryFor(inputs.map(toTestUri).toList(), options, truncate: truncate); } /// Defines a default set of options for testing: /// /// * create a hybrid file system that stores [sources] in memory but allows /// access to the physical file system to load the SDK. [sources] can /// contain either source files (value is [String]) or .dill files (value /// is [List<int>]). /// /// * define an empty .packages file (if one isn't defined in sources) /// /// * specify the location of the sdk summaries. Future<Null> setup(CompilerOptions options, Map<String, dynamic> sources, {List<String> inputSummaries: const [], List<String> linkedDependencies: const []}) async { MemoryFileSystem fs = new MemoryFileSystem(_defaultDir); sources.forEach((name, data) { MemoryFileSystemEntity entity = fs.entityForUri(toTestUri(name)); if (data is String) { entity.writeAsStringSync(data); } else { entity.writeAsBytesSync(data); } }); MemoryFileSystemEntity dotPackagesFile = fs.entityForUri(toTestUri('.packages')); if (!await dotPackagesFile.exists()) dotPackagesFile.writeAsStringSync(''); fs .entityForUri(invalidCoreLibsSpecUri) .writeAsStringSync(_invalidLibrariesSpec); options ..verify = true ..fileSystem = new HybridFileSystem(fs) ..inputSummaries = inputSummaries.map(toTestUri).toList() ..linkedDependencies = linkedDependencies.map(toTestUri).toList() ..packagesFileUri = toTestUri('.packages'); if (options.sdkSummary == null) { options.sdkRoot = computePlatformBinariesLocation(forceBuildDir: true); } } /// A fake absolute directory used as the root of a memory-file system in the /// helpers above. Uri _defaultDir = Uri.parse('org-dartlang-test:///a/b/c/'); /// Convert relative file paths into an absolute Uri as expected by the test /// helpers above. Uri toTestUri(String relativePath) => _defaultDir.resolve(relativePath); /// Uri to a libraries specification file that purposely provides /// invalid Uris to dart:core and dart:async. Used by tests that want to ensure /// that the sdk libraries are not loaded from sources, but read from a .dill /// file. Uri invalidCoreLibsSpecUri = toTestUri('invalid_sdk_libraries.json'); String _invalidLibrariesSpec = ''' { "vm": { "libraries": { "core": {"uri": "/non_existing_file/core.dart"}, "async": {"uri": "/non_existing_file/async.dart"} } } } '''; bool isDartCoreLibrary(Library lib) => isDartCore(lib.importUri); bool isDartCore(Uri uri) => uri.scheme == 'dart' && uri.path == 'core'; /// Find a library in [component] whose Uri ends with the given [suffix] Library findLibrary(Component component, String suffix) { return component.libraries .firstWhere((lib) => lib.importUri.path.endsWith(suffix)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/id_testing_helper.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:kernel/ast.dart'; import '../api_prototype/compiler_options.dart' show CompilerOptions, DiagnosticMessage; import '../api_prototype/experimental_flags.dart' show ExperimentalFlag; import '../api_prototype/terminal_color_support.dart' show printDiagnosticMessage; import '../base/common.dart'; import '../fasta/messages.dart' show FormattedMessage; import '../fasta/severity.dart' show Severity; import '../kernel_generator_impl.dart' show InternalCompilerResult; import 'compiler_common.dart' show compileScript, toTestUri; import 'id.dart' show ActualData, ClassId, Id, IdKind, IdValue, MemberId, NodeId; import 'id_extractor.dart' show DataExtractor; import 'id_testing.dart' show CompiledData, DataInterpreter, MemberAnnotations, RunTestFunction, TestData, cfeMarker, checkCode; import 'id_testing_utils.dart'; export '../fasta/compiler_context.dart' show CompilerContext; export '../kernel_generator_impl.dart' show InternalCompilerResult; export '../fasta/messages.dart' show FormattedMessage; /// Test configuration used for testing CFE in its default state. const TestConfig defaultCfeConfig = const TestConfig(cfeMarker, 'cfe'); /// Test configuration used for testing CFE with extension methods. const TestConfig cfeExtensionMethodsConfig = const TestConfig( cfeMarker, 'cfe with extension methods', experimentalFlags: const {ExperimentalFlag.extensionMethods: true}); class TestConfig { final String marker; final String name; final Map<ExperimentalFlag, bool> experimentalFlags; final Uri librariesSpecificationUri; const TestConfig(this.marker, this.name, {this.experimentalFlags = const {}, this.librariesSpecificationUri}); void customizeCompilerOptions(CompilerOptions options) {} } // TODO(johnniwinther): Support annotations for compile-time errors. abstract class DataComputer<T> { const DataComputer(); /// Called before testing to setup flags needed for data collection. void setup() {} /// Function that computes a data mapping for [member]. /// /// Fills [actualMap] with the data. void computeMemberData(InternalCompilerResult compilerResult, Member member, Map<Id, ActualData<T>> actualMap, {bool verbose}) {} /// Function that computes a data mapping for [cls]. /// /// Fills [actualMap] with the data. void computeClassData(InternalCompilerResult compilerResult, Class cls, Map<Id, ActualData<T>> actualMap, {bool verbose}) {} /// Function that computes a data mapping for [extension]. /// /// Fills [actualMap] with the data. void computeExtensionData(InternalCompilerResult compilerResult, Extension extension, Map<Id, ActualData<T>> actualMap, {bool verbose}) {} /// Function that computes a data mapping for [library]. /// /// Fills [actualMap] with the data. void computeLibraryData(InternalCompilerResult compilerResult, Library library, Map<Id, ActualData<T>> actualMap, {bool verbose}) {} /// Returns `true` if this data computer supports tests with compile-time /// errors. /// /// Unsuccessful compilation might leave the compiler in an inconsistent /// state, so this testing feature is opt-in. bool get supportsErrors => false; /// Returns data corresponding to [error]. T computeErrorData(InternalCompilerResult compiler, Id id, List<FormattedMessage> errors) => null; /// Returns the [DataInterpreter] used to check the actual data with the /// expected data. DataInterpreter<T> get dataValidator; } class CfeCompiledData<T> extends CompiledData<T> { final InternalCompilerResult compilerResult; CfeCompiledData( this.compilerResult, Uri mainUri, Map<Uri, Map<Id, ActualData<T>>> actualMaps, Map<Id, ActualData<T>> globalData) : super(mainUri, actualMaps, globalData); @override int getOffsetFromId(Id id, Uri uri) { if (id is NodeId) return id.value; if (id is MemberId) { Library library = lookupLibrary(compilerResult.component, uri); Member member; int offset; if (id.className != null) { Class cls = lookupClass(library, id.className); member = lookupClassMember(cls, id.memberName); offset = member.fileOffset; if (offset == -1) { offset = cls.fileOffset; } } else { member = lookupLibraryMember(library, id.memberName); offset = member.fileOffset; } if (offset == -1) { offset = 0; } return offset; } else if (id is ClassId) { Library library = lookupLibrary(compilerResult.component, uri); Extension extension = lookupExtension(library, id.className, required: false); if (extension != null) { return extension.fileOffset; } Class cls = lookupClass(library, id.className); return cls.fileOffset; } return null; } @override void reportError(Uri uri, int offset, String message, {bool succinct: false}) { printMessageInLocation( compilerResult.component.uriToSource, uri, offset, message, succinct: succinct); } } abstract class CfeDataExtractor<T> extends DataExtractor<T> { final InternalCompilerResult compilerResult; CfeDataExtractor(this.compilerResult, Map<Id, ActualData<T>> actualMap) : super(actualMap); @override void report(Uri uri, int offset, String message) { printMessageInLocation( compilerResult.component.uriToSource, uri, offset, message); } @override void fail(String message) { onFailure(message); } } /// Create the testing URI used for [fileName] in annotated tests. Uri createUriForFileName(String fileName) => toTestUri(fileName); void onFailure(String message) => throw new StateError(message); /// Creates a test runner for [dataComputer] on [testedConfigs]. RunTestFunction runTestFor<T>( DataComputer<T> dataComputer, List<TestConfig> testedConfigs) { retainDataForTesting = true; return (TestData testData, {bool testAfterFailures, bool verbose, bool succinct, bool printCode}) { return runTest(testData, dataComputer, testedConfigs, testAfterFailures: testAfterFailures, verbose: verbose, succinct: succinct, printCode: printCode, onFailure: onFailure); }; } /// Runs [dataComputer] on [testData] for all [testedConfigs]. /// /// Returns `true` if an error was encountered. Future<bool> runTest<T>(TestData testData, DataComputer<T> dataComputer, List<TestConfig> testedConfigs, {bool testAfterFailures, bool verbose, bool succinct, bool printCode, bool forUserLibrariesOnly: true, Iterable<Id> globalIds: const <Id>[], void onFailure(String message)}) async { bool hasFailures = false; for (TestConfig config in testedConfigs) { if (await runTestForConfig(testData, dataComputer, config, fatalErrors: !testAfterFailures, onFailure: onFailure, verbose: verbose, succinct: succinct, printCode: printCode)) { hasFailures = true; } } return hasFailures; } /// Runs [dataComputer] on [testData] for [config]. /// /// Returns `true` if an error was encountered. Future<bool> runTestForConfig<T>( TestData testData, DataComputer<T> dataComputer, TestConfig config, {bool fatalErrors, bool verbose, bool succinct, bool printCode, bool forUserLibrariesOnly: true, Iterable<Id> globalIds: const <Id>[], void onFailure(String message)}) async { MemberAnnotations<IdValue> memberAnnotations = testData.expectedMaps[config.marker]; Iterable<Id> globalIds = memberAnnotations.globalData.keys; CompilerOptions options = new CompilerOptions(); List<FormattedMessage> errors = []; options.onDiagnostic = (DiagnosticMessage message) { if (message is FormattedMessage && message.severity == Severity.error) { errors.add(message); } if (!succinct) printDiagnosticMessage(message, print); }; options.debugDump = printCode; options.experimentalFlags.addAll(config.experimentalFlags); if (config.librariesSpecificationUri != null) { Set<Uri> testFiles = testData.memorySourceFiles.keys.map(createUriForFileName).toSet(); if (testFiles.contains(config.librariesSpecificationUri)) { options.librariesSpecificationUri = config.librariesSpecificationUri; } } config.customizeCompilerOptions(options); InternalCompilerResult compilerResult = await compileScript( testData.memorySourceFiles, options: options, retainDataForTesting: true); Component component = compilerResult.component; Map<Uri, Map<Id, ActualData<T>>> actualMaps = <Uri, Map<Id, ActualData<T>>>{}; Map<Id, ActualData<T>> globalData = <Id, ActualData<T>>{}; Map<Id, ActualData<T>> actualMapForUri(Uri uri) { return actualMaps.putIfAbsent(uri, () => <Id, ActualData<T>>{}); } if (errors.isNotEmpty) { if (!dataComputer.supportsErrors) { onFailure("Compilation with compile-time errors not supported for this " "testing setup."); } Map<Uri, Map<int, List<FormattedMessage>>> errorMap = {}; for (FormattedMessage error in errors) { Map<int, List<FormattedMessage>> map = errorMap.putIfAbsent(error.uri, () => {}); List<FormattedMessage> list = map.putIfAbsent(error.charOffset, () => []); list.add(error); } errorMap.forEach((Uri uri, Map<int, List<FormattedMessage>> map) { map.forEach((int offset, List<DiagnosticMessage> list) { NodeId id = new NodeId(offset, IdKind.error); T data = dataComputer.computeErrorData(compilerResult, id, list); if (data != null) { Map<Id, ActualData<T>> actualMap = actualMapForUri(uri); actualMap[id] = new ActualData<T>(id, data, uri, offset, list); } }); }); } Map<Id, ActualData<T>> actualMapFor(TreeNode node) { Uri uri = node is Library ? node.fileUri : (node is Member ? node.fileUri : node.location.file); return actualMaps.putIfAbsent(uri, () => <Id, ActualData<T>>{}); } void processMember(Member member, Map<Id, ActualData<T>> actualMap) { if (member.enclosingClass != null) { if (member.enclosingClass.isEnum) { if (member is Constructor || member.isInstanceMember || member.name == 'values') { return; } } if (member is Constructor && member.enclosingClass.isMixinApplication) { return; } } dataComputer.computeMemberData(compilerResult, member, actualMap, verbose: verbose); } void processClass(Class cls, Map<Id, ActualData<T>> actualMap) { dataComputer.computeClassData(compilerResult, cls, actualMap, verbose: verbose); } void processExtension(Extension extension, Map<Id, ActualData<T>> actualMap) { dataComputer.computeExtensionData(compilerResult, extension, actualMap, verbose: verbose); } bool excludeLibrary(Library library) { return forUserLibrariesOnly && (library.importUri.scheme == 'dart' || library.importUri.scheme == 'package'); } for (Library library in component.libraries) { if (excludeLibrary(library) && !testData.memorySourceFiles.containsKey(library.fileUri.path)) { continue; } dataComputer.computeLibraryData( compilerResult, library, actualMapFor(library)); for (Class cls in library.classes) { processClass(cls, actualMapFor(cls)); for (Member member in cls.members) { processMember(member, actualMapFor(member)); } } for (Member member in library.members) { processMember(member, actualMapFor(member)); } for (Extension extension in library.extensions) { processExtension(extension, actualMapFor(extension)); } } List<Uri> globalLibraries = <Uri>[ Uri.parse('dart:core'), Uri.parse('dart:collection'), Uri.parse('dart:async'), ]; Class getGlobalClass(String className) { Class cls; for (Uri uri in globalLibraries) { Library library = lookupLibrary(component, uri); if (library != null) { cls ??= lookupClass(library, className); } } if (cls == null) { throw "Global class '$className' not found in the global " "libraries: ${globalLibraries.join(', ')}"; } return cls; } Member getGlobalMember(String memberName) { Member member; for (Uri uri in globalLibraries) { Library library = lookupLibrary(component, uri); if (library != null) { member ??= lookupLibraryMember(library, memberName); } } if (member == null) { throw "Global member '$memberName' not found in the global " "libraries: ${globalLibraries.join(', ')}"; } return member; } for (Id id in globalIds) { if (id is MemberId) { Member member; if (id.className != null) { Class cls = getGlobalClass(id.className); member = lookupClassMember(cls, id.memberName); if (member == null) { throw "Global member '${id.memberName}' not found in class $cls."; } } else { member = getGlobalMember(id.memberName); } processMember(member, globalData); } else if (id is ClassId) { Class cls = getGlobalClass(id.className); processClass(cls, globalData); } else { throw new UnsupportedError("Unexpected global id: $id"); } } CfeCompiledData compiledData = new CfeCompiledData<T>( compilerResult, testData.testFileUri, actualMaps, globalData); return checkCode(config.name, testData.testFileUri, testData.code, memberAnnotations, compiledData, dataComputer.dataValidator, fatalErrors: fatalErrors, succinct: succinct, onFailure: onFailure); } void printMessageInLocation( Map<Uri, Source> uriToSource, Uri uri, int offset, String message, {bool succinct: false}) { if (uri == null) { print(message); } else { Source source = uriToSource[uri]; if (source == null) { print('$uri@$offset: $message'); } else { if (offset != null) { Location location = source.getLocation(uri, offset); print('$location: $message'); if (!succinct) { print(source.getTextLine(location.line)); print(' ' * (location.column - 1) + '^'); } } else { print('$uri: $message'); } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/id.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. enum IdKind { /// Id used for top level or class members. This is used in [MemberId]. member, /// Id used for classes. This is used in [ClassId]. cls, /// Id used for libraries. This is used in [LibraryId]. library, /// Id used for a code point at certain offset. The id represents the default /// use of the code point, often a read access. This is used in [NodeId]. node, /// Id used for an invocation at certain offset. This is used in [NodeId]. invoke, /// Id used for an assignment at certain offset. This is used in [NodeId]. update, /// Id used for the iterator expression of a for-in at certain offset. This is /// used in [NodeId]. iterator, /// Id used for the implicit call to `Iterator.current` in a for-in at certain /// offset. This is used in [NodeId]. current, /// Id used for the implicit call to `Iterator.moveNext` in a for-in at /// certain offset. This is used in [NodeId]. moveNext, /// Id used for the implicit as expression inserted by the compiler. implicitAs, /// Id used for the statement at certain offset. This is used in [NodeId]. stmt, /// Id used for the error reported at certain offset. This is used in /// [NodeId]. error, } /// Id for a code point or element. abstract class Id { IdKind get kind; /// Indicates whether the id refers to an element defined outside of the test /// case itself (e.g. some tests may need to refer to properties of elements /// in `dart:core`). bool get isGlobal; /// Display name for this id. String get descriptor; } class IdValue { final Id id; final String value; const IdValue(this.id, this.value); @override int get hashCode => id.hashCode * 13 + value.hashCode * 17; @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! IdValue) return false; return id == other.id && value == other.value; } @override String toString() => idToString(id, value); static String idToString(Id id, String value) { switch (id.kind) { case IdKind.member: MemberId elementId = id; return '$memberPrefix${elementId.name}:$value'; case IdKind.cls: ClassId classId = id; return '$classPrefix${classId.name}:$value'; case IdKind.library: return '$libraryPrefix$value'; case IdKind.node: return value; case IdKind.invoke: return '$invokePrefix$value'; case IdKind.update: return '$updatePrefix$value'; case IdKind.iterator: return '$iteratorPrefix$value'; case IdKind.current: return '$currentPrefix$value'; case IdKind.moveNext: return '$moveNextPrefix$value'; case IdKind.implicitAs: return '$implicitAsPrefix$value'; case IdKind.stmt: return '$stmtPrefix$value'; case IdKind.error: return '$errorPrefix$value'; } throw new UnsupportedError("Unexpected id kind: ${id.kind}"); } static const String globalPrefix = "global#"; static const String memberPrefix = "member: "; static const String classPrefix = "class: "; static const String libraryPrefix = "library: "; static const String invokePrefix = "invoke: "; static const String updatePrefix = "update: "; static const String iteratorPrefix = "iterator: "; static const String currentPrefix = "current: "; static const String moveNextPrefix = "moveNext: "; static const String implicitAsPrefix = "as: "; static const String stmtPrefix = "stmt: "; static const String errorPrefix = "error: "; static IdValue decode(Uri sourceUri, int offset, String text) { Id id; String expected; if (text.startsWith(memberPrefix)) { text = text.substring(memberPrefix.length); int colonPos = text.indexOf(':'); if (colonPos == -1) throw "Invalid member id: '$text'"; String name = text.substring(0, colonPos); bool isGlobal = name.startsWith(globalPrefix); if (isGlobal) { name = name.substring(globalPrefix.length); } id = new MemberId(name, isGlobal: isGlobal); expected = text.substring(colonPos + 1); } else if (text.startsWith(classPrefix)) { text = text.substring(classPrefix.length); int colonPos = text.indexOf(':'); if (colonPos == -1) throw "Invalid class id: '$text'"; String name = text.substring(0, colonPos); bool isGlobal = name.startsWith(globalPrefix); if (isGlobal) { name = name.substring(globalPrefix.length); } id = new ClassId(name, isGlobal: isGlobal); expected = text.substring(colonPos + 1); } else if (text.startsWith(libraryPrefix)) { id = new LibraryId(sourceUri); expected = text.substring(libraryPrefix.length); } else if (text.startsWith(invokePrefix)) { id = new NodeId(offset, IdKind.invoke); expected = text.substring(invokePrefix.length); } else if (text.startsWith(updatePrefix)) { id = new NodeId(offset, IdKind.update); expected = text.substring(updatePrefix.length); } else if (text.startsWith(iteratorPrefix)) { id = new NodeId(offset, IdKind.iterator); expected = text.substring(iteratorPrefix.length); } else if (text.startsWith(currentPrefix)) { id = new NodeId(offset, IdKind.current); expected = text.substring(currentPrefix.length); } else if (text.startsWith(moveNextPrefix)) { id = new NodeId(offset, IdKind.moveNext); expected = text.substring(moveNextPrefix.length); } else if (text.startsWith(implicitAsPrefix)) { id = new NodeId(offset, IdKind.implicitAs); expected = text.substring(implicitAsPrefix.length); } else if (text.startsWith(stmtPrefix)) { id = new NodeId(offset, IdKind.stmt); expected = text.substring(stmtPrefix.length); } else if (text.startsWith(errorPrefix)) { id = new NodeId(offset, IdKind.error); expected = text.substring(errorPrefix.length); } else { id = new NodeId(offset, IdKind.node); expected = text; } // Remove newlines. expected = expected.replaceAll(new RegExp(r'\s*(\n\s*)+\s*'), ''); return new IdValue(id, expected); } } /// Id for an member element. class MemberId implements Id { final String className; final String memberName; @override final bool isGlobal; factory MemberId(String text, {bool isGlobal: false}) { int dotPos = text.indexOf('.'); if (dotPos != -1) { return new MemberId.internal(text.substring(dotPos + 1), className: text.substring(0, dotPos), isGlobal: isGlobal); } else { return new MemberId.internal(text, isGlobal: isGlobal); } } MemberId.internal(this.memberName, {this.className, this.isGlobal: false}); @override int get hashCode => className.hashCode * 13 + memberName.hashCode * 17; @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! MemberId) return false; return className == other.className && memberName == other.memberName; } @override IdKind get kind => IdKind.member; String get name => className != null ? '$className.$memberName' : memberName; @override String get descriptor => 'member $name'; @override String toString() => 'member:$name'; } /// Id for a class. class ClassId implements Id { final String className; @override final bool isGlobal; ClassId(this.className, {this.isGlobal: false}); @override int get hashCode => className.hashCode * 13; @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! ClassId) return false; return className == other.className; } @override IdKind get kind => IdKind.cls; String get name => className; @override String get descriptor => 'class $name'; @override String toString() => 'class:$name'; } /// Id for a library. class LibraryId implements Id { final Uri uri; LibraryId(this.uri); // TODO(johnniwinther): Support global library annotations. @override bool get isGlobal => false; @override int get hashCode => uri.hashCode * 13; @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! LibraryId) return false; return uri == other.uri; } @override IdKind get kind => IdKind.library; String get name => uri.toString(); @override String get descriptor => 'library $name'; @override String toString() => 'library:$name'; } /// Id for a code point defined by a kind and a code offset. class NodeId implements Id { final int value; @override final IdKind kind; const NodeId(this.value, this.kind); @override bool get isGlobal => false; @override int get hashCode => value.hashCode * 13 + kind.hashCode * 17; @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! NodeId) return false; return value == other.value && kind == other.kind; } @override String get descriptor => 'offset $value ($kind)'; @override String toString() => '$kind:$value'; } class ActualData<T> { final Id id; final T value; final Uri uri; final int _offset; final Object object; ActualData(this.id, this.value, this.uri, this._offset, this.object); int get offset { if (id is NodeId) { NodeId nodeId = id; return nodeId.value; } else { return _offset; } } String get objectText { return 'object `${'$object'.replaceAll('\n', '')}` (${object.runtimeType})'; } @override String toString() => 'ActualData(id=$id,value=$value,uri=$uri,' 'offset=$offset,object=$objectText)'; } abstract class DataRegistry<T> { Map<Id, ActualData<T>> get actualMap; /// Registers [value] with [id] in [actualMap]. /// /// Checks for duplicate data for [id]. void registerValue(Uri uri, int offset, Id id, T value, Object object) { if (value != null) { ActualData<T> newData = new ActualData<T>(id, value, uri, offset, object); if (actualMap.containsKey(id)) { ActualData<T> existingData = actualMap[id]; ActualData<T> mergedData = mergeData(existingData, newData); if (mergedData != null) { actualMap[id] = mergedData; } else { report( uri, offset, "Duplicate id ${id}, value=$value, object=$object " "(${object.runtimeType})"); report( uri, offset, "Duplicate id ${id}, value=${existingData.value}, " "object=${existingData.object} " "(${existingData.object.runtimeType})"); fail("Duplicate id $id."); } } else { actualMap[id] = newData; } } } ActualData<T> mergeData(ActualData<T> value1, ActualData<T> value2) => null; /// Called to report duplicate errors. void report(Uri uri, int offset, String message); /// Called to raise an exception on duplicate errors. void fail(String message); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/id_testing.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'annotated_code_helper.dart'; import 'id.dart'; import '../fasta/colors.dart' as colors; const String cfeMarker = 'cfe'; const String dart2jsMarker = 'dart2js'; const String analyzerMarker = 'analyzer'; /// Markers used in annotated tests shard by CFE, analyzer and dart2js. const List<String> sharedMarkers = [ cfeMarker, dart2jsMarker, analyzerMarker, ]; /// `true` if ANSI colors are supported by stdout. bool useColors = stdout.supportsAnsiEscapes; /// Colorize a message [text], if ANSI colors are supported. String colorizeMessage(String text) { if (useColors) { return '${colors.YELLOW_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize a matching annotation [text], if ANSI colors are supported. String colorizeMatch(String text) { if (useColors) { return '${colors.BLUE_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize a single annotation [text], if ANSI colors are supported. String colorizeSingle(String text) { if (useColors) { return '${colors.GREEN_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize the actual annotation [text], if ANSI colors are supported. String colorizeActual(String text) { if (useColors) { return '${colors.RED_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize an expected annotation [text], if ANSI colors are supported. String colorizeExpected(String text) { if (useColors) { return '${colors.GREEN_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize delimiter [text], if ANSI colors are supported. String colorizeDelimiter(String text) { if (useColors) { return '${colors.YELLOW_COLOR}${text}${colors.DEFAULT_COLOR}'; } else { return text; } } /// Colorize diffs [expected] and [actual] and [delimiter], if ANSI colors are /// supported. String colorizeDiff(String expected, String delimiter, String actual) { return '${colorizeExpected(expected)}' '${colorizeDelimiter(delimiter)}${colorizeActual(actual)}'; } /// Colorize annotation delimiters [start] and [end] surrounding [text], if /// ANSI colors are supported. String colorizeAnnotation(String start, String text, String end) { return '${colorizeDelimiter(start)}$text${colorizeDelimiter(end)}'; } /// Encapsulates the member data computed for each source file of interest. /// It's a glorified wrapper around a map of maps, but written this way to /// provide a little more information about what it's doing. [DataType] refers /// to the type this map is holding -- it is either [IdValue] or [ActualData]. class MemberAnnotations<DataType> { /// For each Uri, we create a map associating an element id with its /// corresponding annotations. final Map<Uri, Map<Id, DataType>> _computedDataForEachFile = new Map<Uri, Map<Id, DataType>>(); /// Member or class annotations that don't refer to any of the user files. final Map<Id, DataType> globalData = <Id, DataType>{}; void operator []=(Uri file, Map<Id, DataType> computedData) { _computedDataForEachFile[file] = computedData; } void forEach(void f(Uri file, Map<Id, DataType> computedData)) { _computedDataForEachFile.forEach(f); } Map<Id, DataType> operator [](Uri file) { if (!_computedDataForEachFile.containsKey(file)) { _computedDataForEachFile[file] = <Id, DataType>{}; } return _computedDataForEachFile[file]; } @override String toString() { StringBuffer sb = new StringBuffer(); sb.write('MemberAnnotations('); String comma = ''; if (_computedDataForEachFile.isNotEmpty && (_computedDataForEachFile.length > 1 || _computedDataForEachFile.values.single.isNotEmpty)) { sb.write('data:{'); _computedDataForEachFile.forEach((Uri uri, Map<Id, DataType> data) { sb.write(comma); sb.write('$uri:'); sb.write(data); comma = ','; }); sb.write('}'); } if (globalData.isNotEmpty) { sb.write(comma); sb.write('global:'); sb.write(globalData); } sb.write(')'); return sb.toString(); } } /// Compute a [MemberAnnotations] object from [code] for each marker in [maps] /// specifying the expected annotations. /// /// If an annotation starts with a marker, it is only expected for the /// corresponding test configuration. Otherwise it is expected for all /// configurations. // TODO(johnniwinther): Support an empty marker set. void computeExpectedMap(Uri sourceUri, String filename, AnnotatedCode code, Map<String, MemberAnnotations<IdValue>> maps, {void onFailure(String message)}) { List<String> mapKeys = maps.keys.toList(); Map<String, AnnotatedCode> split = splitByPrefixes(code, mapKeys); split.forEach((String marker, AnnotatedCode code) { MemberAnnotations<IdValue> fileAnnotations = maps[marker]; assert(fileAnnotations != null, "No annotations for $marker in $maps"); Map<Id, IdValue> expectedValues = fileAnnotations[sourceUri]; for (Annotation annotation in code.annotations) { String text = annotation.text; IdValue idValue = IdValue.decode(sourceUri, annotation.offset, text); if (idValue.id.isGlobal) { if (fileAnnotations.globalData.containsKey(idValue.id)) { onFailure("Error in test '$filename': " "Duplicate annotations for ${idValue.id} in $marker: " "${idValue} and ${fileAnnotations.globalData[idValue.id]}."); } fileAnnotations.globalData[idValue.id] = idValue; } else { if (expectedValues.containsKey(idValue.id)) { onFailure("Error in test '$filename': " "Duplicate annotations for ${idValue.id} in $marker: " "${idValue} and ${expectedValues[idValue.id]}."); } expectedValues[idValue.id] = idValue; } } }); } /// Creates a [TestData] object for the annotated test in [testFile]. /// /// If [testFile] is a file, use that directly. If it's a directory include /// everything in that directory. /// /// If [testLibDirectory] is not `null`, files in [testLibDirectory] with the /// [testFile] name as a prefix are included. TestData computeTestData(FileSystemEntity testFile, {Iterable<String> supportedMarkers, Uri createUriForFileName(String fileName), void onFailure(String message)}) { Uri entryPoint = createUriForFileName('main.dart'); String testName; File mainTestFile; Uri testFileUri = testFile.uri; Map<String, File> additionalFiles; if (testFile is File) { testName = testFileUri.pathSegments.last; mainTestFile = testFile; } else if (testFile is Directory) { testName = testFileUri.pathSegments[testFileUri.pathSegments.length - 2]; additionalFiles = new Map<String, File>(); for (FileSystemEntity entry in testFile.listSync(recursive: true)) { if (entry is! File) continue; if (entry.uri.pathSegments.last == "main.dart") { mainTestFile = entry; } else { additionalFiles[entry.uri.path.substring(testFile.uri.path.length)] = entry; } } assert( mainTestFile != null, "No 'main.dart' test file found for $testFile."); } String annotatedCode = new File.fromUri(mainTestFile.uri).readAsStringSync(); Map<Uri, AnnotatedCode> code = { entryPoint: new AnnotatedCode.fromText(annotatedCode, commentStart, commentEnd) }; Map<String, MemberAnnotations<IdValue>> expectedMaps = {}; for (String testMarker in supportedMarkers) { expectedMaps[testMarker] = new MemberAnnotations<IdValue>(); } computeExpectedMap(entryPoint, testFile.uri.pathSegments.last, code[entryPoint], expectedMaps, onFailure: onFailure); Map<String, String> memorySourceFiles = { entryPoint.path: code[entryPoint].sourceCode }; if (additionalFiles != null) { for (MapEntry<String, File> additionalFileData in additionalFiles.entries) { String libFileName = additionalFileData.key; File libEntity = additionalFileData.value; Uri libFileUri = createUriForFileName(libFileName); String libCode = libEntity.readAsStringSync(); AnnotatedCode annotatedLibCode = new AnnotatedCode.fromText(libCode, commentStart, commentEnd); memorySourceFiles[libFileUri.path] = annotatedLibCode.sourceCode; code[libFileUri] = annotatedLibCode; computeExpectedMap( libFileUri, libFileName, annotatedLibCode, expectedMaps, onFailure: onFailure); } } return new TestData( testName, testFileUri, entryPoint, memorySourceFiles, code, expectedMaps); } /// Data for an annotated test. class TestData { final String name; final Uri testFileUri; final Uri entryPoint; final Map<String, String> memorySourceFiles; final Map<Uri, AnnotatedCode> code; final Map<String, MemberAnnotations<IdValue>> expectedMaps; TestData(this.name, this.testFileUri, this.entryPoint, this.memorySourceFiles, this.code, this.expectedMaps); } /// The actual result computed for an annotated test. abstract class CompiledData<T> { final Uri mainUri; /// For each Uri, a map associating an element id with the instrumentation /// data we've collected for it. final Map<Uri, Map<Id, ActualData<T>>> actualMaps; /// Collected instrumentation data that doesn't refer to any of the user /// files. (E.g. information the test has collected about files in /// `dart:core`). final Map<Id, ActualData<T>> globalData; CompiledData(this.mainUri, this.actualMaps, this.globalData); Map<int, List<String>> computeAnnotations(Uri uri) { Map<Id, ActualData<T>> actualMap = actualMaps[uri]; Map<int, List<String>> annotations = <int, List<String>>{}; actualMap.forEach((Id id, ActualData<T> data) { String value1 = '${data.value}'; annotations .putIfAbsent(data.offset, () => []) .add(colorizeActual(value1)); }); return annotations; } Map<int, List<String>> computeDiffAnnotationsAgainst( Map<Id, ActualData<T>> thisMap, Map<Id, ActualData<T>> otherMap, Uri uri, {bool includeMatches: false}) { Map<int, List<String>> annotations = <int, List<String>>{}; thisMap.forEach((Id id, ActualData<T> thisData) { ActualData<T> otherData = otherMap[id]; String thisValue = '${thisData.value}'; if (thisData.value != otherData?.value) { String otherValue = '${otherData?.value ?? '---'}'; annotations .putIfAbsent(thisData.offset, () => []) .add(colorizeDiff(thisValue, ' | ', otherValue)); } else if (includeMatches) { annotations .putIfAbsent(thisData.offset, () => []) .add(colorizeMatch(thisValue)); } }); otherMap.forEach((Id id, ActualData<T> otherData) { if (!thisMap.containsKey(id)) { String thisValue = '---'; String otherValue = '${otherData.value}'; annotations .putIfAbsent(otherData.offset, () => []) .add(colorizeDiff(thisValue, ' | ', otherValue)); } }); return annotations; } int getOffsetFromId(Id id, Uri uri); void reportError(Uri uri, int offset, String message, {bool succinct: false}); } /// Interface used for interpreting annotations. abstract class DataInterpreter<T> { /// Returns `null` if [actualData] satisfies the [expectedData] annotation. /// Otherwise, a message is returned contain the information about the /// problems found. String isAsExpected(T actualData, String expectedData); /// Returns `true` if [actualData] corresponds to empty data. bool isEmpty(T actualData); /// Returns a textual representation of [actualData]. String getText(T actualData); } /// Default data interpreter for string data. class StringDataInterpreter implements DataInterpreter<String> { const StringDataInterpreter(); @override String isAsExpected(String actualData, String expectedData) { actualData ??= ''; expectedData ??= ''; if (actualData != expectedData) { return "Expected $expectedData, found $actualData"; } return null; } @override bool isEmpty(String actualData) { return actualData == ''; } @override String getText(String actualData) { return actualData; } } String withAnnotations(String sourceCode, Map<int, List<String>> annotations) { StringBuffer sb = new StringBuffer(); int end = 0; for (int offset in annotations.keys.toList()..sort()) { if (offset >= sourceCode.length) { sb.write('...'); return sb.toString(); } if (offset > end) { sb.write(sourceCode.substring(end, offset)); } for (String annotation in annotations[offset]) { sb.write(colorizeAnnotation('/*', annotation, '*/')); } end = offset; } if (end < sourceCode.length) { sb.write(sourceCode.substring(end)); } return sb.toString(); } /// Computed and expected data for an annotated test. This is used for checking /// and displaying results of an annotated test. class IdData<T> { final Map<Uri, AnnotatedCode> code; final MemberAnnotations<IdValue> expectedMaps; final CompiledData<T> _compiledData; final MemberAnnotations<ActualData<T>> _actualMaps = new MemberAnnotations(); IdData(this.code, this.expectedMaps, this._compiledData) { for (Uri uri in code.keys) { _actualMaps[uri] = _compiledData.actualMaps[uri] ?? <Id, ActualData<T>>{}; } _actualMaps.globalData.addAll(_compiledData.globalData); } Uri get mainUri => _compiledData.mainUri; MemberAnnotations<ActualData<T>> get actualMaps => _actualMaps; String actualCode(Uri uri) { Map<int, List<String>> annotations = <int, List<String>>{}; actualMaps[uri].forEach((Id id, ActualData<T> data) { annotations.putIfAbsent(data.offset, () => []).add('${data.value}'); }); return withAnnotations(code[uri].sourceCode, annotations); } String diffCode(Uri uri, DataInterpreter<T> dataValidator) { Map<int, List<String>> annotations = <int, List<String>>{}; actualMaps[uri].forEach((Id id, ActualData<T> data) { IdValue expectedValue = expectedMaps[uri][id]; T actualValue = data.value; String unexpectedMessage = dataValidator.isAsExpected(actualValue, expectedValue?.value); if (unexpectedMessage != null) { String expected = expectedValue?.toString() ?? ''; String actual = dataValidator.getText(actualValue); int offset = getOffsetFromId(id, uri); if (offset != null) { String value1 = '${expected}'; String value2 = IdValue.idToString(id, '${actual}'); annotations .putIfAbsent(offset, () => []) .add(colorizeDiff(value1, ' | ', value2)); } } }); expectedMaps[uri].forEach((Id id, IdValue expected) { if (!actualMaps[uri].containsKey(id)) { int offset = getOffsetFromId(id, uri); if (offset != null) { String value1 = '${expected}'; String value2 = '---'; annotations .putIfAbsent(offset, () => []) .add(colorizeDiff(value1, ' | ', value2)); } } }); return withAnnotations(code[uri].sourceCode, annotations); } int getOffsetFromId(Id id, Uri uri) { return _compiledData.getOffsetFromId(id, uri); } } /// Checks [compiledData] against the expected data in [expectedMaps] derived /// from [code]. Future<bool> checkCode<T>( String modeName, Uri mainFileUri, Map<Uri, AnnotatedCode> code, MemberAnnotations<IdValue> expectedMaps, CompiledData<T> compiledData, DataInterpreter<T> dataValidator, {bool filterActualData(IdValue expected, ActualData<T> actualData), bool fatalErrors: true, bool succinct: false, void onFailure(String message)}) async { IdData<T> data = new IdData<T>(code, expectedMaps, compiledData); bool hasFailure = false; Set<Uri> neededDiffs = new Set<Uri>(); void checkActualMap( Map<Id, ActualData<T>> actualMap, Map<Id, IdValue> expectedMap, [Uri uri]) { bool hasLocalFailure = false; actualMap.forEach((Id id, ActualData<T> actualData) { T actual = actualData.value; String actualText = dataValidator.getText(actual); if (!expectedMap.containsKey(id)) { if (!dataValidator.isEmpty(actual)) { String actualValueText = IdValue.idToString(id, actualText); compiledData.reportError( actualData.uri, actualData.offset, succinct ? 'EXTRA $modeName DATA for ${id.descriptor}' : 'EXTRA $modeName DATA for ${id.descriptor}:\n ' 'object : ${actualData.objectText}\n ' 'actual : ${colorizeActual(actualValueText)}\n ' 'Data was expected for these ids: ${expectedMap.keys}', succinct: succinct); if (filterActualData == null || filterActualData(null, actualData)) { hasLocalFailure = true; } } } else { IdValue expected = expectedMap[id]; String unexpectedMessage = dataValidator.isAsExpected(actual, expected.value); if (unexpectedMessage != null) { String actualValueText = IdValue.idToString(id, actualText); compiledData.reportError( actualData.uri, actualData.offset, succinct ? 'UNEXPECTED $modeName DATA for ${id.descriptor}' : 'UNEXPECTED $modeName DATA for ${id.descriptor}:\n ' 'detail : ${colorizeMessage(unexpectedMessage)}\n ' 'object : ${actualData.objectText}\n ' 'expected: ${colorizeExpected('$expected')}\n ' 'actual : ${colorizeActual(actualValueText)}', succinct: succinct); if (filterActualData == null || filterActualData(expected, actualData)) { hasLocalFailure = true; } } } }); if (hasLocalFailure) { hasFailure = true; if (uri != null) { neededDiffs.add(uri); } } } data.actualMaps.forEach((Uri uri, Map<Id, ActualData<T>> actualMap) { checkActualMap(actualMap, data.expectedMaps[uri], uri); }); checkActualMap(data.actualMaps.globalData, data.expectedMaps.globalData); Set<Id> missingIds = new Set<Id>(); void checkMissing( Map<Id, IdValue> expectedMap, Map<Id, ActualData<T>> actualMap, [Uri uri]) { expectedMap.forEach((Id id, IdValue expected) { if (!actualMap.containsKey(id)) { missingIds.add(id); String message = 'MISSING $modeName DATA for ${id.descriptor}: ' 'Expected ${colorizeExpected('$expected')}'; if (uri != null) { compiledData.reportError( uri, compiledData.getOffsetFromId(id, uri), message, succinct: succinct); } else { print(message); } } }); if (missingIds.isNotEmpty && uri != null) { neededDiffs.add(uri); } } data.expectedMaps.forEach((Uri uri, Map<Id, IdValue> expectedMap) { checkMissing(expectedMap, data.actualMaps[uri], uri); }); checkMissing(data.expectedMaps.globalData, data.actualMaps.globalData); if (!succinct) { for (Uri uri in neededDiffs) { print('--annotations diff [${uri.pathSegments.last}]-------------'); print(data.diffCode(uri, dataValidator)); print('----------------------------------------------------------'); } } if (missingIds.isNotEmpty) { print("MISSING ids: ${missingIds}."); hasFailure = true; } if (hasFailure && fatalErrors) { onFailure('Errors found.'); } return hasFailure; } typedef Future<bool> RunTestFunction(TestData testData, {bool testAfterFailures, bool verbose, bool succinct, bool printCode}); /// Check code for all tests in [dataDir] using [runTest]. Future runTests(Directory dataDir, {List<String> args: const <String>[], int shards: 1, int shardIndex: 0, void onTest(Uri uri), Iterable<String> supportedMarkers, Uri createUriForFileName(String fileName), void onFailure(String message), RunTestFunction runTest}) async { // TODO(johnniwinther): Support --show to show actual data for an input. args = args.toList(); bool verbose = args.remove('-v'); bool succinct = args.remove('-s'); bool shouldContinue = args.remove('-c'); bool testAfterFailures = args.remove('-a'); bool printCode = args.remove('-p'); bool continued = false; bool hasFailures = false; String relativeDir = dataDir.uri.path.replaceAll(Uri.base.path, ''); print('Data dir: ${relativeDir}'); List<FileSystemEntity> entities = dataDir.listSync(); if (shards > 1) { int start = entities.length * shardIndex ~/ shards; int end = entities.length * (shardIndex + 1) ~/ shards; entities = entities.sublist(start, end); } int testCount = 0; for (FileSystemEntity entity in entities) { String name = entity.uri.pathSegments.last; if (entity is Directory) { name = entity.uri.pathSegments[entity.uri.pathSegments.length - 2]; } if (args.isNotEmpty && !args.contains(name) && !continued) continue; if (shouldContinue) continued = true; testCount++; if (onTest != null) { onTest(entity.uri); } print('----------------------------------------------------------------'); TestData testData = computeTestData(entity, supportedMarkers: supportedMarkers, createUriForFileName: createUriForFileName, onFailure: onFailure); print('Test: ${testData.testFileUri}'); if (await runTest(testData, testAfterFailures: testAfterFailures, verbose: verbose, succinct: succinct, printCode: printCode)) { hasFailures = true; } } if (hasFailures) { onFailure('Errors found.'); } if (testCount == 0) { onFailure("No files were tested."); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/testing/annotated_code_helper.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. const int _LF = 0x0A; const int _CR = 0x0D; const Pattern atBraceStart = '@{'; const Pattern braceEnd = '}'; final Pattern commentStart = new RegExp(r'/\*'); final Pattern commentEnd = new RegExp(r'\*/\s*'); class Annotation { /// 1-based line number of the annotation. final int lineNo; /// 1-based column number of the annotation. final int columnNo; /// 0-based character offset of the annotation within the source text. final int offset; /// The text in the annotation. final String text; Annotation(this.lineNo, this.columnNo, this.offset, this.text); String toString() => 'Annotation(lineNo=$lineNo,columnNo=$columnNo,offset=$offset,text=$text)'; } /// A source code text with annotated positions. /// /// An [AnnotatedCode] can be created from a [String] of source code where /// annotated positions are embedded, by default using the syntax `@{text}`. /// For instance /// /// main() { /// @{foo-call}foo(); /// bar@{bar-args}(); /// } /// /// the position of `foo` call will hold an annotation with text 'foo-call' and /// the position of `bar` arguments will hold an annotation with text /// 'bar-args'. /// /// Annotation text cannot span multiple lines and cannot contain '}'. class AnnotatedCode { /// The source code without annotations. final String sourceCode; /// The annotations for the source code. final List<Annotation> annotations; List<int> _lineStarts; AnnotatedCode(this.sourceCode, this.annotations); AnnotatedCode.internal(this.sourceCode, this.annotations, this._lineStarts); /// Creates an [AnnotatedCode] by processing [annotatedCode]. Annotation /// delimited by [start] and [end] are converted into [Annotation]s and /// removed from the [annotatedCode] to produce the source code. factory AnnotatedCode.fromText(String annotatedCode, [Pattern start = atBraceStart, Pattern end = braceEnd]) { StringBuffer codeBuffer = new StringBuffer(); List<Annotation> annotations = <Annotation>[]; int index = 0; int offset = 0; int lineNo = 1; int columnNo = 1; List<int> lineStarts = <int>[]; lineStarts.add(offset); while (index < annotatedCode.length) { Match startMatch = start.matchAsPrefix(annotatedCode, index); if (startMatch != null) { int startIndex = startMatch.end; Iterable<Match> endMatches = end.allMatches(annotatedCode, startMatch.end); if (!endMatches.isEmpty) { Match endMatch = endMatches.first; annotatedCode.indexOf(end, startIndex); String text = annotatedCode.substring(startMatch.end, endMatch.start); annotations.add(new Annotation(lineNo, columnNo, offset, text)); index = endMatch.end; continue; } } int charCode = annotatedCode.codeUnitAt(index); switch (charCode) { case _LF: codeBuffer.write('\n'); offset++; lineStarts.add(offset); lineNo++; columnNo = 1; break; case _CR: if (index + 1 < annotatedCode.length && annotatedCode.codeUnitAt(index + 1) == _LF) { index++; } codeBuffer.write('\n'); offset++; lineStarts.add(offset); lineNo++; columnNo = 1; break; default: codeBuffer.writeCharCode(charCode); offset++; columnNo++; } index++; } lineStarts.add(offset); return new AnnotatedCode.internal( codeBuffer.toString(), annotations, lineStarts); } void _ensureLineStarts() { if (_lineStarts == null) { int index = 0; int offset = 0; _lineStarts = <int>[]; _lineStarts.add(offset); while (index < sourceCode.length) { int charCode = sourceCode.codeUnitAt(index); switch (charCode) { case _LF: offset++; _lineStarts.add(offset); break; case _CR: if (index + 1 < sourceCode.length && sourceCode.codeUnitAt(index + 1) == _LF) { index++; } offset++; _lineStarts.add(offset); break; default: offset++; } index++; } _lineStarts.add(offset); } } void addAnnotation(int lineNo, int columnNo, String text) { _ensureLineStarts(); int offset = _lineStarts[lineNo - 1] + (columnNo - 1); annotations.add(new Annotation(lineNo, columnNo, offset, text)); } String toText() { StringBuffer sb = new StringBuffer(); List<Annotation> list = annotations.toList() ..sort((a, b) => a.offset.compareTo(b.offset)); int offset = 0; for (Annotation annotation in list) { sb.write(sourceCode.substring(offset, annotation.offset)); sb.write('@{${annotation.text}}'); offset = annotation.offset; } sb.write(sourceCode.substring(offset)); return sb.toString(); } } /// Split the annotations in [annotatedCode] by [prefixes]. /// /// Returns a map containing an [AnnotatedCode] object for each prefix, /// containing only the annotations whose text started with the given prefix. /// If no prefix match the annotation text, the annotation is added to all /// [AnnotatedCode] objects. /// /// The prefixes are removed from the annotation texts in the returned /// [AnnotatedCode] objects. Map<String, AnnotatedCode> splitByPrefixes( AnnotatedCode annotatedCode, Iterable<String> prefixes) { Set<String> prefixSet = prefixes.toSet(); Map<String, List<Annotation>> map = <String, List<Annotation>>{}; for (String prefix in prefixSet) { map[prefix] = <Annotation>[]; } outer: for (Annotation annotation in annotatedCode.annotations) { int dotPos = annotation.text.indexOf('.'); if (dotPos != -1) { String annotationPrefix = annotation.text.substring(0, dotPos); String annotationText = annotation.text.substring(dotPos + 1); List<String> markers = annotationPrefix.split('|').toList(); if (prefixSet.containsAll(markers)) { for (String part in markers) { map[part].add(new Annotation(annotation.lineNo, annotation.columnNo, annotation.offset, annotationText)); } continue outer; } } for (String prefix in prefixSet) { map[prefix].add(annotation); } } Map<String, AnnotatedCode> split = <String, AnnotatedCode>{}; map.forEach((String prefix, List<Annotation> annotations) { split[prefix] = new AnnotatedCode(annotatedCode.sourceCode, annotations); }); return split; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/hybrid_file_system.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. /// A memory + physical file system used to mock input for tests but provide /// sdk sources from disk. library front_end.src.hybrid_file_system; import 'dart:async'; import '../api_prototype/file_system.dart'; import '../api_prototype/memory_file_system.dart'; import '../api_prototype/standard_file_system.dart'; /// A file system that mixes files from memory and a physical file system. All /// memory entities take priority over file system entities. class HybridFileSystem implements FileSystem { final MemoryFileSystem memory; final FileSystem physical; HybridFileSystem(this.memory, [FileSystem _physical]) : physical = _physical ?? StandardFileSystem.instance; @override FileSystemEntity entityForUri(Uri uri) => new HybridFileSystemEntity(uri, this); } /// Entity that delegates to an underlying memory or physical file system /// entity. class HybridFileSystemEntity implements FileSystemEntity { final Uri uri; FileSystemEntity _delegate; final HybridFileSystem _fs; HybridFileSystemEntity(this.uri, this._fs); Future<FileSystemEntity> get delegate async { if (_delegate != null) return _delegate; FileSystemEntity entity = _fs.memory.entityForUri(uri); if (((uri.scheme != 'file' && uri.scheme != 'data') && _fs.physical is StandardFileSystem) || await entity.exists()) { _delegate = entity; return _delegate; } return _delegate = _fs.physical.entityForUri(uri); } @override Future<bool> exists() async => (await delegate).exists(); @override Future<List<int>> readAsBytes() async => (await delegate).readAsBytes(); @override Future<String> readAsString() async => (await delegate).readAsString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/blacklisted_classes.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. // List of special classes in dart:core that can't be subclassed. const List<String> blacklistedCoreClasses = [ "bool", "int", "num", "double", "String", "Null" ];
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/ticker.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. library fasta.ticker; class Ticker { final Stopwatch sw = new Stopwatch()..start(); bool isVerbose; Duration previousTick; Ticker({this.isVerbose: true}) { previousTick = sw.elapsed; } void logMs(Object message) { log((Duration elapsed, Duration sinceStart) { print("$sinceStart: $message in ${elapsed.inMilliseconds}ms."); }); } void log(void f(Duration elapsed, Duration sinceStart)) { Duration elapsed = sw.elapsed; try { if (isVerbose) f(elapsed - previousTick, elapsed); } finally { previousTick = sw.elapsed; } } void reset() { sw.reset(); previousTick = sw.elapsed; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder_graph.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. library fasta.builder_graph; import 'package:kernel/kernel.dart' show LibraryDependency, LibraryPart; import 'package:kernel/util/graph.dart' show Graph; import 'builder/builder.dart' show LibraryBuilder; import 'export.dart' show Export; import 'import.dart' show Import; import 'dill/dill_library_builder.dart' show DillLibraryBuilder; import 'source/source_library_builder.dart' show SourceLibraryBuilder; class BuilderGraph implements Graph<Uri> { final Map<Uri, LibraryBuilder> builders; BuilderGraph(this.builders); Iterable<Uri> get vertices => builders.keys; Iterable<Uri> neighborsOf(Uri vertex) sync* { LibraryBuilder library = builders[vertex]; if (library == null) { throw "Library not found: $vertex"; } if (library is SourceLibraryBuilder) { for (Import import in library.imports) { // 'imported' can be null for fake imports, such as dart-ext:. if (import.imported != null) { Uri uri = import.imported.uri; if (builders.containsKey(uri)) { yield uri; } } } for (Export export in library.exports) { Uri uri = export.exported.uri; if (builders.containsKey(uri)) { yield uri; } } for (SourceLibraryBuilder part in library.parts) { Uri uri = part.uri; if (builders.containsKey(uri)) { yield uri; } } } else if (library is DillLibraryBuilder) { // Imports and exports for (LibraryDependency dependency in library.library.dependencies) { Uri uri = dependency.targetLibrary.importUri; if (builders.containsKey(uri)) { yield uri; } } // Parts for (LibraryPart part in library.library.parts) { Uri uri = library.uri.resolve(part.partUri); if (builders.containsKey(uri)) { yield uri; } } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/identifiers.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. library fasta.qualified_name; import 'package:kernel/ast.dart' show Expression; import 'problems.dart' show unhandled, unsupported; import 'scanner.dart' show Token; class Identifier { final String name; final int charOffset; Identifier(Token token) : name = token.lexeme, charOffset = token.charOffset; Identifier._(this.name, this.charOffset); factory Identifier.preserveToken(Token token) { return new _TokenIdentifier(token); } Expression get initializer => null; int get endCharOffset => charOffset + name.length; QualifiedName withQualifier(Object qualifier) { return new QualifiedName._(qualifier, name, charOffset); } @override String toString() => "identifier($name)"; } class _TokenIdentifier implements Identifier { final Token token; _TokenIdentifier(this.token); @override String get name => token.lexeme; @override int get charOffset => token.charOffset; @override Expression get initializer => null; @override int get endCharOffset => charOffset + name.length; @override QualifiedName withQualifier(Object qualifier) { return new _TokenQualifiedName(qualifier, token); } @override String toString() => "token-identifier($name)"; } class InitializedIdentifier extends _TokenIdentifier { @override final Expression initializer; InitializedIdentifier(_TokenIdentifier identifier, this.initializer) : super(identifier.token); @override QualifiedName withQualifier(Object qualifier) { return unsupported("withQualifier", charOffset, null); } @override String toString() => "initialized-identifier($name, $initializer)"; } class QualifiedName extends Identifier { final Object qualifier; QualifiedName(this.qualifier, Token suffix) : super(suffix); QualifiedName._(this.qualifier, String name, int charOffset) : super._(name, charOffset); @override QualifiedName withQualifier(Object qualifier) { return unsupported("withQualifier", charOffset, null); } @override String toString() => "qualified-name($qualifier, $name)"; } class _TokenQualifiedName extends _TokenIdentifier implements QualifiedName { @override final Object qualifier; _TokenQualifiedName(this.qualifier, Token suffix) : assert(qualifier is! Identifier || qualifier is _TokenIdentifier), super(suffix); @override QualifiedName withQualifier(Object qualifier) { return unsupported("withQualifier", charOffset, null); } @override String toString() => "token-qualified-name($qualifier, $name)"; } void flattenQualifiedNameOn( QualifiedName name, StringBuffer buffer, int charOffset, Uri fileUri) { final Object qualifier = name.qualifier; if (qualifier is QualifiedName) { flattenQualifiedNameOn(qualifier, buffer, charOffset, fileUri); } else if (qualifier is Identifier) { buffer.write(qualifier.name); } else if (qualifier is String) { buffer.write(qualifier); } else { unhandled("${qualifier.runtimeType}", "flattenQualifiedNameOn", charOffset, fileUri); } buffer.write("."); buffer.write(name.name); } String flattenName(Object name, int charOffset, Uri fileUri) { if (name is String) { return name; } else if (name is QualifiedName) { StringBuffer buffer = new StringBuffer(); flattenQualifiedNameOn(name, buffer, charOffset, fileUri); return "$buffer"; } else if (name is Identifier) { return name.name; } else { return unhandled("${name.runtimeType}", "flattenName", charOffset, fileUri); } } Token deprecated_extractToken(Identifier identifier) { _TokenIdentifier tokenIdentifier = identifier; return tokenIdentifier?.token; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/parser.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.md file. library fasta.parser; import '../scanner/token.dart' show Token; import 'parser/listener.dart' show Listener; import 'parser/parser.dart' show Parser; import 'parser/parser_error.dart' show ParserError; import 'fasta_codes.dart' show Message, messageNativeClauseShouldBeAnnotation; export 'parser/assert.dart' show Assert; export 'parser/class_member_parser.dart' show ClassMemberParser; export 'parser/formal_parameter_kind.dart' show FormalParameterKind; export 'parser/identifier_context.dart' show IdentifierContext; export 'parser/listener.dart' show Listener; export 'parser/declaration_kind.dart' show DeclarationKind; export 'parser/member_kind.dart' show MemberKind; export 'parser/parser.dart' show Parser; export 'parser/parser_error.dart' show ParserError; export 'parser/top_level_parser.dart' show TopLevelParser; export 'parser/util.dart' show lengthForToken, lengthOfSpan, offsetForToken, optional; class ErrorCollectingListener extends Listener { final List<ParserError> recoverableErrors = <ParserError>[]; void handleRecoverableError( Message message, Token startToken, Token endToken) { /// TODO(danrubel): Ignore this error until we deprecate `native` support. if (message == messageNativeClauseShouldBeAnnotation) { return; } recoverableErrors .add(new ParserError.fromTokens(startToken, endToken, message)); } } List<ParserError> parse(Token tokens) { ErrorCollectingListener listener = new ErrorCollectingListener(); Parser parser = new Parser(listener); parser.parseUnit(tokens); return listener.recoverableErrors; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/constant_context.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. library fasta.constant_context; enum ConstantContext { /// Not in a constant context. /// /// This means that `Object()` and `[]` are equivalent to `new Object()` and /// `[]` respectively. `new Object()` is **not** a compile-time error. /// /// TODO(ahe): Update the above specification and corresponding /// implementation because `Object()` is a compile-time constant. See [magic /// const]( /// ../../../../../../docs/language/informal/docs/language/informal/implicit-creation.md /// ). none, /// In a context where constant expressions are required, and `const` may be /// inferred. /// /// This means that `Object()` and `[]` are equivalent to `const Object()` and /// `const []` respectively. `new Object()` is a compile-time error. inferred, /// In a context where constant expressions are required, but `const` is not /// inferred. This includes default values of optional parameters and /// initializing expressions on fields in classes with a `const` constructor. required, }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/get_dependencies.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. library fasta.get_dependencies; import 'dart:async' show Future; import 'package:kernel/kernel.dart' show Component, loadComponentFromBytes; import 'package:kernel/target/targets.dart' show Target; import '../api_prototype/compiler_options.dart' show CompilerOptions; import '../api_prototype/file_system.dart' show FileSystem; import '../base/processed_options.dart' show ProcessedOptions; import 'compiler_context.dart' show CompilerContext; import 'dill/dill_target.dart' show DillTarget; import 'kernel/kernel_target.dart' show KernelTarget; import 'uri_translator.dart' show UriTranslator; Future<List<Uri>> getDependencies(Uri script, {Uri sdk, Uri packages, Uri platform, bool verbose: false, Target target}) async { CompilerOptions options = new CompilerOptions() ..target = target ..verbose = verbose ..packagesFileUri = packages ..sdkSummary = platform ..sdkRoot = sdk; ProcessedOptions pOptions = new ProcessedOptions(options: options, inputs: <Uri>[script]); return await CompilerContext.runWithOptions(pOptions, (CompilerContext c) async { FileSystem fileSystem = c.options.fileSystem; UriTranslator uriTranslator = await c.options.getUriTranslator(); c.options.ticker.logMs("Read packages file"); DillTarget dillTarget = new DillTarget(c.options.ticker, uriTranslator, c.options.target); if (platform != null) { List<int> bytes = await fileSystem.entityForUri(platform).readAsBytes(); Component platformComponent = loadComponentFromBytes(bytes); dillTarget.loader.appendLibraries(platformComponent); } KernelTarget kernelTarget = new KernelTarget(fileSystem, false, dillTarget, uriTranslator); kernelTarget.setEntryPoints(<Uri>[script]); await dillTarget.buildOutlines(); await kernelTarget.loader.buildOutlines(); return new List<Uri>.from(c.dependencies); }); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/modifier.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. library fasta.modifier; import 'problems.dart' show unhandled; enum ModifierEnum { Abstract, Const, Covariant, External, Final, Static, // Not a real modifier. Var, } const int abstractMask = 1; const int constMask = abstractMask << 1; const int covariantMask = constMask << 1; const int externalMask = covariantMask << 1; const int finalMask = externalMask << 1; const int staticMask = finalMask << 1; const int lateMask = staticMask << 1; const int requiredMask = lateMask << 1; const int namedMixinApplicationMask = requiredMask << 1; /// Not a modifier, used for mixins declared explicitly by using the `mixin` /// keyword. const int mixinDeclarationMask = namedMixinApplicationMask << 1; /// Not a modifier, used by fields to track if they have an initializer. const int hasInitializerMask = mixinDeclarationMask << 1; /// Not a modifier, used by formal parameters to track if they are initializing. const int initializingFormalMask = hasInitializerMask << 1; /// Not a modifier, used by classes to track if the class has a const /// constructor. const int hasConstConstructorMask = initializingFormalMask << 1; /// Not a real modifier, and by setting it to zero, it is automatically ignored /// by [Modifier.validate] below. const int varMask = 0; const Modifier Abstract = const Modifier(ModifierEnum.Abstract, abstractMask); const Modifier Const = const Modifier(ModifierEnum.Const, constMask); const Modifier Covariant = const Modifier(ModifierEnum.Covariant, covariantMask); const Modifier External = const Modifier(ModifierEnum.External, externalMask); const Modifier Final = const Modifier(ModifierEnum.Final, finalMask); const Modifier Static = const Modifier(ModifierEnum.Static, staticMask); /// Not a real modifier. const Modifier Var = const Modifier(ModifierEnum.Var, varMask); class Modifier { final ModifierEnum kind; final int mask; const Modifier(this.kind, this.mask); factory Modifier.fromString(String string) { if (identical('abstract', string)) return Abstract; if (identical('const', string)) return Const; if (identical('covariant', string)) return Covariant; if (identical('external', string)) return External; if (identical('final', string)) return Final; if (identical('static', string)) return Static; if (identical('var', string)) return Var; return unhandled(string, "Modifier.fromString", -1, null); } toString() => "modifier(${'$kind'.substring('ModifierEnum.'.length)})"; static int validate(List<Modifier> modifiers, {bool isAbstract: false}) { // TODO(ahe): Rename this method, validation is now taken care of by the // parser. int result = isAbstract ? abstractMask : 0; if (modifiers == null) return result; for (Modifier modifier in modifiers) { result |= modifier.mask; } return result; } static int validateVarFinalOrConst(String lexeme) { if (lexeme == null) return 0; if (identical('const', lexeme)) return Const.mask; if (identical('final', lexeme)) return Final.mask; if (identical('var', lexeme)) return Var.mask; return unhandled(lexeme, "Modifier.validateVarFinalOrConst", -1, null); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/compiler_context.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. library fasta.compiler_context; import 'dart:async' show Future, Zone, runZoned; import 'package:kernel/ast.dart' show Source; import '../api_prototype/file_system.dart' show FileSystem; import '../base/processed_options.dart' show ProcessedOptions; import 'scanner/token.dart' show StringToken; import 'command_line_reporting.dart' as command_line_reporting; import 'colors.dart' show computeEnableColors; import 'fasta_codes.dart' show LocatedMessage, Message, messageInternalProblemMissingContext; import 'severity.dart' show Severity; final Object compilerContextKey = new Object(); /// Shared context used throughout the compiler. /// /// The compiler works with a single instance of this class. To avoid /// passing it around as an argument everywhere, it is stored as a zone-value. /// /// For convenience the static getter [CompilerContext.current] retrieves the /// context stored in the current zone. class CompilerContext { // TODO(sigmund): Move here any method in ProcessedOptions that doesn't seem // appropriate as an "option", or consider merging ProcessedOptions entirely // within this class, and depend only on the raw options here. final ProcessedOptions options; /// Sources seen by the compiler. /// /// This is populated as the compiler reads files, and it is used for error /// reporting and to generate source location information in the compiled /// programs. final Map<Uri, Source> uriToSource = <Uri, Source>{}; // TODO(ahe): Remove this. final List<Object> errors = <Object>[]; final List<Uri> dependencies = <Uri>[]; FileSystem get fileSystem => options.fileSystem; bool enableColorsCached = null; Uri cachedSdkRoot = null; bool compilingPlatform = false; CompilerContext(this.options); void disableColors() { enableColorsCached = false; } /// Report [message], for example, by printing it. void report(LocatedMessage message, Severity severity, {List<LocatedMessage> context}) { options.report(message, severity, context: context); } /// Report [message], for example, by printing it. // TODO(askesc): Remove this and direct callers directly to report. void reportWithoutLocation(Message message, Severity severity) { options.reportWithoutLocation(message, severity); } /// Format [message] as a text string that can be included in generated code. String format(LocatedMessage message, Severity severity) { return command_line_reporting.format(message, severity); } /// Format [message] as a text string that can be included in generated code. // TODO(askesc): Remove this and direct callers directly to format. String formatWithoutLocation(Message message, Severity severity) { return command_line_reporting.format(message.withoutLocation(), severity); } // TODO(ahe): Remove this. void logError(Object message, Severity severity) { errors.add(message); errors.add(severity); } static void recordDependency(Uri uri) { if (uri.scheme != "file") { throw new ArgumentError("Expected a file-URI, but got: '$uri'."); } CompilerContext context = Zone.current[compilerContextKey]; if (context != null) { context.dependencies.add(uri); } } static CompilerContext get current { CompilerContext context = Zone.current[compilerContextKey]; if (context == null) { // Note: we throw directly and don't use internalProblem, because // internalProblem depends on having a compiler context available. String message = messageInternalProblemMissingContext.message; String tip = messageInternalProblemMissingContext.tip; throw "Internal problem: $message\nTip: $tip"; } return context; } static bool get isActive => Zone.current[compilerContextKey] != null; /// Perform [action] in a [Zone] where [this] will be available as /// `CompilerContext.current`. Future<T> runInContext<T>(Future<T> action(CompilerContext c)) { return runZoned( () => new Future<T>.sync(() => action(this)).whenComplete(clear), zoneValues: {compilerContextKey: this}); } /// Perform [action] in a [Zone] where [options] will be available as /// `CompilerContext.current.options`. static Future<T> runWithOptions<T>( ProcessedOptions options, Future<T> action(CompilerContext c), {bool errorOnMissingInput: true}) { return new CompilerContext(options) .runInContext<T>((CompilerContext c) async { await options.validateOptions(errorOnMissingInput: errorOnMissingInput); return action(c); }); } static Future<T> runWithDefaultOptions<T>( Future<T> action(CompilerContext c)) { return new CompilerContext(new ProcessedOptions()).runInContext<T>(action); } static bool get enableColors { return current.enableColorsCached ??= computeEnableColors(current); } void clear() { StringToken.canonicalizer.clear(); errors.clear(); dependencies.clear(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/severity.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. library fasta.severity; enum Severity { context, error, // TODO(johnniwinther): Remove legacy warning. errorLegacyWarning, ignored, internalProblem, warning, } const Map<String, String> severityEnumNames = const <String, String>{ 'CONTEXT': 'context', 'ERROR': 'error', 'ERROR_LEGACY_WARNING': 'errorLegacyWarning', 'IGNORED': 'ignored', 'INTERNAL_PROBLEM': 'internalProblem', 'WARNING': 'warning', }; const Map<String, Severity> severityEnumValues = const <String, Severity>{ 'CONTEXT': Severity.context, 'ERROR': Severity.error, 'ERROR_LEGACY_WARNING': Severity.errorLegacyWarning, 'IGNORED': Severity.ignored, 'INTERNAL_PROBLEM': Severity.internalProblem, 'WARNING': Severity.warning, }; const Map<Severity, String> severityPrefixes = const <Severity, String>{ Severity.error: "Error", Severity.internalProblem: "Internal problem", Severity.warning: "Warning", Severity.context: "Context", }; const Map<Severity, String> severityTexts = const <Severity, String>{ Severity.error: "error", Severity.internalProblem: "internal problem", Severity.warning: "warning", Severity.context: "context", };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/ignored_parser_errors.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. library fasta.ignored_parser_errors; import 'fasta_codes.dart' show Code, codeNonPartOfDirectiveInPart; import 'parser.dart' show optional; import 'scanner.dart' show Token; bool isIgnoredParserError(Code<Object> code, Token token) { if (code == codeNonPartOfDirectiveInPart) { // Ignored. This error is handled in the outline phase (part resolution). return optional("part", token); } else { return false; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/command_line_reporting.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. /// Provides a default implementation of the report and format methods of /// [CompilerContext] that are suitable for command-line tools. The methods in /// this library aren't intended to be called directly, instead, one should use /// [CompilerContext]. library fasta.command_line_reporting; import 'dart:math' show min; import 'dart:typed_data' show Uint8List; import 'package:kernel/ast.dart' show Location, TreeNode; import '../compute_platform_binaries_location.dart' show translateSdk; import 'colors.dart' show green, magenta, red; import 'compiler_context.dart' show CompilerContext; import 'crash.dart' show Crash, safeToString; import 'fasta_codes.dart' show LocatedMessage; import 'messages.dart' show getLocation, getSourceLine; import 'problems.dart' show unhandled; import 'resolve_input_uri.dart' show isWindows; import 'severity.dart' show Severity, severityPrefixes; import 'scanner/characters.dart' show $CARET, $SPACE, $TAB; import 'util/relativize.dart' show relativizeUri; const bool hideWarnings = false; /// Formats [message] as a string that is suitable for output from a /// command-line tool. This includes source snippets and different colors based /// on [severity]. String format(LocatedMessage message, Severity severity, {Location location}) { try { int length = message.length; if (length < 1) { // TODO(ahe): Throw in this situation. It is normally an error caused by // empty names. length = 1; } String prefix = severityPrefixes[severity]; String messageText = prefix == null ? message.message : "$prefix: ${message.message}"; if (message.tip != null) { messageText += "\n${message.tip}"; } if (CompilerContext.enableColors) { switch (severity) { case Severity.error: case Severity.internalProblem: messageText = red(messageText); break; case Severity.warning: messageText = magenta(messageText); break; case Severity.context: messageText = green(messageText); break; default: return unhandled("$severity", "format", -1, null); } } if (message.uri != null) { String path = relativizeUri(Uri.base, translateSdk(message.uri), isWindows); int offset = message.charOffset; location ??= (offset == -1 ? null : getLocation(message.uri, offset)); if (location?.line == TreeNode.noOffset) { location = null; } String sourceLine = getSourceLine(location); return formatErrorMessage( sourceLine, location, length, path, messageText); } else { return messageText; } } catch (error, trace) { print("Crash when formatting: " "[${message.code.name}] ${safeToString(message.message)}\n" "${safeToString(error)}\n" "$trace"); throw new Crash(message.uri, message.charOffset, error, trace); } } String formatErrorMessage(String sourceLine, Location location, int squigglyLength, String path, String messageText) { if (sourceLine == null) { sourceLine = ""; } else if (sourceLine.isNotEmpty) { // TODO(askesc): Much more could be done to indent properly in the // presence of all sorts of unicode weirdness. // This handling covers the common case of single-width characters // indented with spaces and/or tabs, using no surrogates. int indentLength = location.column - 1; Uint8List indentation = new Uint8List(indentLength + squigglyLength) ..fillRange(0, indentLength, $SPACE) ..fillRange(indentLength, indentLength + squigglyLength, $CARET); int lengthInSourceLine = min(indentation.length, sourceLine.length); for (int i = 0; i < lengthInSourceLine; i++) { if (sourceLine.codeUnitAt(i) == $TAB) { indentation[i] = $TAB; } } String pointer = new String.fromCharCodes(indentation); if (pointer.length > sourceLine.length) { // Truncate the carets to handle messages that span multiple lines. int pointerLength = sourceLine.length; // Add one to cover the case of a parser error pointing to EOF when // the last line doesn't end with a newline. For messages spanning // multiple lines, this also provides a minor visual clue that can be // useful for debugging Fasta. pointerLength += 1; pointer = pointer.substring(0, pointerLength); pointer += "..."; } sourceLine = "\n$sourceLine\n$pointer"; } String position = location == null ? "" : ":${location.line}:${location.column}"; return "$path$position: $messageText$sourceLine"; } /// Are problems of [severity] suppressed? bool isHidden(Severity severity) { switch (severity) { case Severity.error: case Severity.internalProblem: case Severity.context: return false; case Severity.warning: return hideWarnings; default: return unhandled("$severity", "isHidden", -1, null); } } /// Are problems of [severity] fatal? That is, should the compiler terminate /// immediately? bool shouldThrowOn(Severity severity) { switch (severity) { case Severity.error: return CompilerContext.current.options.throwOnErrorsForDebugging; case Severity.internalProblem: return true; case Severity.warning: return CompilerContext.current.options.throwOnWarningsForDebugging; case Severity.context: return false; default: return unhandled("$severity", "shouldThrowOn", -1, null); } } bool isCompileTimeError(Severity severity) { switch (severity) { case Severity.error: case Severity.internalProblem: return true; case Severity.errorLegacyWarning: return true; case Severity.warning: case Severity.context: return false; case Severity.ignored: break; // Fall-through to unhandled below. } return unhandled("$severity", "isCompileTimeError", -1, null); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/uri_translator.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. library fasta.uri_translator; import 'package:package_config/packages.dart' show Packages; import '../base/libraries_specification.dart' show TargetLibrariesSpecification; import 'compiler_context.dart' show CompilerContext; import 'fasta_codes.dart'; import 'severity.dart' show Severity; class UriTranslator { final TargetLibrariesSpecification dartLibraries; final Packages packages; UriTranslator(this.dartLibraries, this.packages); List<Uri> getDartPatches(String libraryName) => dartLibraries.libraryInfoFor(libraryName)?.patches; bool isPlatformImplementation(Uri uri) { if (uri.scheme != "dart") return false; String path = uri.path; return dartLibraries.libraryInfoFor(path) == null || path.startsWith("_"); } // TODO(sigmund, ahe): consider expanding this API to include an error // callback, so we can provide an error location when one is available. For // example, if the error occurs in an `import`. Uri translate(Uri uri, [bool reportMessage = true]) { if (uri.scheme == "dart") return _translateDartUri(uri); if (uri.scheme == "package") { return _translatePackageUri(uri, reportMessage); } return null; } /// For a package uri, get the fragment of the uri specified for that package. String getPackageFragment(Uri uri) { if (packages == null) return null; if (uri.scheme != "package") return null; int firstSlash = uri.path.indexOf('/'); if (firstSlash == -1) return null; String packageName = uri.path.substring(0, firstSlash); Uri packageBaseUri = packages.asMap()[packageName]; if (packageBaseUri == null) return null; return packageBaseUri.fragment; } /// Get the fragment for the package specified as the default package, if any. String getDefaultPackageFragment() { Uri emptyPackageRedirect = packages.asMap()[""]; if (emptyPackageRedirect == null) return null; String packageName = emptyPackageRedirect.toString(); Uri packageBaseUri = packages.asMap()[packageName]; if (packageBaseUri == null) return null; return packageBaseUri.fragment; } bool isLibrarySupported(String libraryName) { // TODO(sigmund): change this to `?? false` when all backends provide the // `libraries.json` file by default (Issue #32657). return dartLibraries.libraryInfoFor(libraryName)?.isSupported ?? true; } Uri _translateDartUri(Uri uri) { if (!uri.isScheme('dart')) return null; return dartLibraries.libraryInfoFor(uri.path)?.uri; } Uri _translatePackageUri(Uri uri, bool reportMessage) { try { // TODO(sigmund): once we remove the `parse` API, we can ensure that // packages will never be null and get rid of `?` below. return packages?.resolve(uri, notFound: reportMessage ? _packageUriNotFound : _packageUriNotFoundNoReport); } on ArgumentError catch (e) { // TODO(sigmund): catch a more precise error when // https://github.com/dart-lang/package_config/issues/40 is fixed. if (reportMessage) { CompilerContext.current.reportWithoutLocation( templateInvalidPackageUri.withArguments(uri, '$e'), Severity.error); } return null; } } static Uri _packageUriNotFound(Uri uri) { String name = uri.pathSegments.first; CompilerContext.current.reportWithoutLocation( templatePackageNotFound.withArguments(name, uri), Severity.error); // TODO(sigmund, ahe): ensure we only report an error once, // this null result will likely cause another error further down in the // compiler. return null; } static Uri _packageUriNotFoundNoReport(Uri uri) { return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/library_graph.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. library fasta.library_graph; import 'package:kernel/kernel.dart' show Library, LibraryDependency, LibraryPart; import 'package:kernel/util/graph.dart' show Graph; class LibraryGraph implements Graph<Uri> { final Map<Uri, Library> libraries; LibraryGraph(this.libraries); Iterable<Uri> get vertices => libraries.keys; Iterable<Uri> neighborsOf(Uri vertex) sync* { Library library = libraries[vertex]; if (library == null) { throw "Library not found: $vertex"; } // Imports and exports. for (LibraryDependency dependency in library.dependencies) { Uri uri1 = dependency.targetLibrary.importUri; Uri uri2 = dependency.targetLibrary.fileUri; if (libraries.containsKey(uri1)) { yield uri1; } else if (uri2 != null) { if (libraries.containsKey(uri2)) { yield uri2; } } } // Parts. // Normally there won't be libraries for these, but if, for instance, // the part didn't exist there will be a synthetic library. for (LibraryPart part in library.parts) { Uri partUri = library.importUri.resolve(part.partUri); Uri fileUri = library.fileUri.resolve(part.partUri); if (libraries.containsKey(partUri)) { yield partUri; } else if (fileUri != partUri && libraries.containsKey(fileUri)) { yield fileUri; } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/fasta_codes.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. library fasta.codes; import 'dart:convert' show JsonEncoder, json; import 'package:kernel/ast.dart' show Constant, DartType, demangleMixinApplicationName; import '../api_prototype/diagnostic_message.dart' show DiagnosticMessage; import '../scanner/token.dart' show Token; import 'kernel/type_labeler.dart'; import 'severity.dart' show Severity; import 'resolve_input_uri.dart' show isWindows; import 'util/relativize.dart' as util show relativizeUri; part 'fasta_codes_generated.dart'; const int noLength = 1; class Code<T> { final String name; /// The unique positive integer associated with this code, /// or `-1` if none. This index is used when translating /// this error to its corresponding Analyzer error. final int index; final Template<T> template; final List<String> analyzerCodes; final Severity severity; const Code(this.name, this.template, {int index, this.analyzerCodes, this.severity: Severity.error}) : this.index = index ?? -1; String toString() => name; } class Message { final Code<dynamic> code; final String message; final String tip; final Map<String, dynamic> arguments; const Message(this.code, {this.message, this.tip, this.arguments}); LocatedMessage withLocation(Uri uri, int charOffset, int length) { return new LocatedMessage(uri, charOffset, length, this); } LocatedMessage withoutLocation() { return new LocatedMessage(null, -1, noLength, this); } } class MessageCode extends Code<Null> implements Message { final String message; final String tip; const MessageCode(String name, {int index, List<String> analyzerCodes, Severity severity: Severity.error, this.message, this.tip}) : super(name, null, index: index, analyzerCodes: analyzerCodes, severity: severity); Map<String, dynamic> get arguments => const <String, dynamic>{}; Code<dynamic> get code => this; @override LocatedMessage withLocation(Uri uri, int charOffset, int length) { return new LocatedMessage(uri, charOffset, length, this); } LocatedMessage withoutLocation() { return new LocatedMessage(null, -1, noLength, this); } } class Template<T> { final String messageTemplate; final String tipTemplate; final T withArguments; const Template({this.messageTemplate, this.tipTemplate, this.withArguments}); } class LocatedMessage implements Comparable<LocatedMessage> { final Uri uri; final int charOffset; final int length; final Message messageObject; const LocatedMessage( this.uri, this.charOffset, this.length, this.messageObject); Code<dynamic> get code => messageObject.code; String get message => messageObject.message; String get tip => messageObject.tip; Map<String, dynamic> get arguments => messageObject.arguments; int compareTo(LocatedMessage other) { int result = "${uri}".compareTo("${other.uri}"); if (result != 0) return result; result = charOffset.compareTo(other.charOffset); if (result != 0) return result; return message.compareTo(message); } FormattedMessage withFormatting(String formatted, int line, int column, Severity severity, List<FormattedMessage> relatedInformation) { return new FormattedMessage( this, formatted, line, column, severity, relatedInformation); } } class FormattedMessage implements DiagnosticMessage { final LocatedMessage locatedMessage; final String formatted; final int line; final int column; @override final Severity severity; final List<FormattedMessage> relatedInformation; const FormattedMessage(this.locatedMessage, this.formatted, this.line, this.column, this.severity, this.relatedInformation); Code<dynamic> get code => locatedMessage.code; String get message => locatedMessage.message; String get tip => locatedMessage.tip; Map<String, dynamic> get arguments => locatedMessage.arguments; Uri get uri => locatedMessage.uri; int get charOffset => locatedMessage.charOffset; int get length => locatedMessage.length; @override Iterable<String> get ansiFormatted sync* { yield formatted; if (relatedInformation != null) { for (FormattedMessage m in relatedInformation) { yield m.formatted; } } } @override Iterable<String> get plainTextFormatted { // TODO(ahe): Implement this correctly. return ansiFormatted; } Map<String, Object> toJson() { // This should be kept in sync with package:kernel/problems.md return <String, Object>{ "ansiFormatted": ansiFormatted.toList(), "plainTextFormatted": plainTextFormatted.toList(), "severity": severity.index, "uri": uri.toString(), }; } String toJsonString() { JsonEncoder encoder = new JsonEncoder.withIndent(" "); return encoder.convert(this); } } class DiagnosticMessageFromJson implements DiagnosticMessage { @override final Iterable<String> ansiFormatted; @override final Iterable<String> plainTextFormatted; @override final Severity severity; final Uri uri; DiagnosticMessageFromJson( this.ansiFormatted, this.plainTextFormatted, this.severity, this.uri); factory DiagnosticMessageFromJson.fromJson(String jsonString) { Map<String, Object> decoded = json.decode(jsonString); List<String> ansiFormatted = new List<String>.from(decoded["ansiFormatted"]); List<String> plainTextFormatted = new List<String>.from(decoded["plainTextFormatted"]); Severity severity = Severity.values[decoded["severity"]]; Uri uri = Uri.parse(decoded["uri"]); return new DiagnosticMessageFromJson( ansiFormatted, plainTextFormatted, severity, uri); } Map<String, Object> toJson() { // This should be kept in sync with package:kernel/problems.md return <String, Object>{ "ansiFormatted": ansiFormatted.toList(), "plainTextFormatted": plainTextFormatted.toList(), "severity": severity.index, "uri": uri.toString(), }; } String toJsonString() { JsonEncoder encoder = new JsonEncoder.withIndent(" "); return encoder.convert(this); } } String relativizeUri(Uri uri) { // We have this method here for two reasons: // // 1. It allows us to implement #uri message argument without using it // (otherwise, we might get an `UNUSED_IMPORT` warning). // // 2. We can change `base` argument here if needed. return uri == null ? null : util.relativizeUri(Uri.base, uri, isWindows); } typedef SummaryTemplate = Message Function(int, int, num, num, num); String itemizeNames(List<String> names) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < names.length - 1; i++) { buffer.write(" - "); buffer.writeln(names[i]); } buffer.write(" - "); buffer.write(names.last); return "$buffer"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/incremental_compiler.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. library fasta.incremental_compiler; import 'dart:async' show Future; import 'package:front_end/src/fasta/dill/dill_class_builder.dart' show DillClassBuilder; import 'package:kernel/binary/ast_from_binary.dart' show BinaryBuilderWithMetadata, CanonicalNameError, CanonicalNameSdkError, InvalidKernelVersionError; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy, ClosedWorldClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/kernel.dart' show Class, Component, DartType, Expression, FunctionNode, Library, LibraryDependency, LibraryPart, Name, Procedure, ProcedureKind, ReturnStatement, Source, Supertype, TreeNode, TypeParameter; import 'package:kernel/kernel.dart' as kernel show Combinator; import '../api_prototype/file_system.dart' show FileSystemEntity; import '../api_prototype/incremental_kernel_generator.dart' show IncrementalKernelGenerator, isLegalIdentifier; import '../api_prototype/memory_file_system.dart' show MemoryFileSystem; import 'builder/builder.dart' show Builder, ClassBuilder, LibraryBuilder; import 'builder_graph.dart' show BuilderGraph; import 'combinator.dart' show Combinator; import 'compiler_context.dart' show CompilerContext; import 'dill/dill_library_builder.dart' show DillLibraryBuilder; import 'dill/dill_target.dart' show DillTarget; import 'util/error_reporter_file_copier.dart' show saveAsGzip; import 'fasta_codes.dart' show DiagnosticMessageFromJson, templateInitializeFromDillNotSelfContained, templateInitializeFromDillNotSelfContainedNoDump, templateInitializeFromDillUnknownProblem, templateInitializeFromDillUnknownProblemNoDump; import 'hybrid_file_system.dart' show HybridFileSystem; import 'kernel/kernel_builder.dart' show ClassHierarchyBuilder; import 'kernel/kernel_shadow_ast.dart' show VariableDeclarationImpl; import 'kernel/kernel_target.dart' show KernelTarget; import 'library_graph.dart' show LibraryGraph; import 'messages.dart' show Message; import 'source/source_library_builder.dart' show SourceLibraryBuilder; import 'ticker.dart' show Ticker; import 'uri_translator.dart' show UriTranslator; class IncrementalCompiler implements IncrementalKernelGenerator { final CompilerContext context; final Ticker ticker; final bool outlineOnly; bool trackNeededDillLibraries = false; Set<Library> neededDillLibraries; Set<Uri> invalidatedUris = new Set<Uri>(); DillTarget dillLoadedData; List<LibraryBuilder> platformBuilders; Map<Uri, LibraryBuilder> userBuilders; final Uri initializeFromDillUri; final Component componentToInitializeFrom; bool initializedFromDill = false; Uri previousPackagesUri; Map<String, Uri> previousPackagesMap; Map<String, Uri> currentPackagesMap; bool hasToCheckPackageUris = false; Map<Uri, List<DiagnosticMessageFromJson>> remainingComponentProblems = new Map<Uri, List<DiagnosticMessageFromJson>>(); List<Component> modulesToLoad; static final Uri debugExprUri = new Uri(scheme: "org-dartlang-debug", path: "synthetic_debug_expression"); KernelTarget userCode; IncrementalCompiler.fromComponent( this.context, Component this.componentToInitializeFrom, [bool outlineOnly]) : ticker = context.options.ticker, initializeFromDillUri = null, this.outlineOnly = outlineOnly ?? false; IncrementalCompiler(this.context, [this.initializeFromDillUri, bool outlineOnly]) : ticker = context.options.ticker, componentToInitializeFrom = null, this.outlineOnly = outlineOnly ?? false; @override Future<Component> computeDelta( {List<Uri> entryPoints, bool fullComponent: false}) async { ticker.reset(); entryPoints ??= context.options.inputs; return context.runInContext<Component>((CompilerContext c) async { IncrementalCompilerData data = new IncrementalCompilerData(); bool bypassCache = false; if (!identical(previousPackagesUri, c.options.packagesUriRaw)) { previousPackagesUri = c.options.packagesUriRaw; bypassCache = true; } else if (this.invalidatedUris.contains(c.options.packagesUri)) { bypassCache = true; } hasToCheckPackageUris = hasToCheckPackageUris || bypassCache; UriTranslator uriTranslator = await c.options.getUriTranslator(bypassCache: bypassCache); previousPackagesMap = currentPackagesMap; currentPackagesMap = uriTranslator.packages.asMap(); ticker.logMs("Read packages file"); if (dillLoadedData == null) { int bytesLength = 0; if (componentToInitializeFrom != null) { // If initializing from a component it has to include the sdk, // so we explicitly don't load it here. initializeFromComponent(uriTranslator, c, data); } else { List<int> summaryBytes = await c.options.loadSdkSummaryBytes(); bytesLength = prepareSummary(summaryBytes, uriTranslator, c, data); if (initializeFromDillUri != null) { try { bytesLength += await initializeFromDill(uriTranslator, c, data); } catch (e, st) { // We might have loaded x out of y libraries into the component. // To avoid any unforeseen problems start over. bytesLength = prepareSummary(summaryBytes, uriTranslator, c, data); if (e is InvalidKernelVersionError || e is PackageChangedError || e is CanonicalNameSdkError) { // Don't report any warning. } else { Uri gzInitializedFrom; if (c.options.writeFileOnCrashReport) { gzInitializedFrom = saveAsGzip( data.initializationBytes, "initialize_from.dill"); recordTemporaryFileForTesting(gzInitializedFrom); } if (e is CanonicalNameError) { Message message = gzInitializedFrom != null ? templateInitializeFromDillNotSelfContained .withArguments(initializeFromDillUri.toString(), gzInitializedFrom) : templateInitializeFromDillNotSelfContainedNoDump .withArguments(initializeFromDillUri.toString()); dillLoadedData.loader .addProblem(message, TreeNode.noOffset, 1, null); } else { // Unknown error: Report problem as such. Message message = gzInitializedFrom != null ? templateInitializeFromDillUnknownProblem.withArguments( initializeFromDillUri.toString(), "$e", "$st", gzInitializedFrom) : templateInitializeFromDillUnknownProblemNoDump .withArguments( initializeFromDillUri.toString(), "$e", "$st"); dillLoadedData.loader .addProblem(message, TreeNode.noOffset, 1, null); } } } } } appendLibraries(data, bytesLength); await dillLoadedData.buildOutlines(); userBuilders = <Uri, LibraryBuilder>{}; platformBuilders = <LibraryBuilder>[]; dillLoadedData.loader.builders.forEach((uri, builder) { if (builder.uri.scheme == "dart") { platformBuilders.add(builder); } else { userBuilders[uri] = builder; } }); if (userBuilders.isEmpty) userBuilders = null; } data.initializationBytes = null; Set<Uri> invalidatedUris = this.invalidatedUris.toSet(); invalidateNotKeptUserBuilders(invalidatedUris); ClassHierarchy hierarchy = userCode?.loader?.hierarchy; Set<LibraryBuilder> notReusedLibraries = new Set<LibraryBuilder>(); List<LibraryBuilder> reusedLibraries = computeReusedLibraries( invalidatedUris, uriTranslator, notReused: notReusedLibraries); bool removedDillBuilders = false; for (LibraryBuilder builder in notReusedLibraries) { CompilerContext.current.uriToSource.remove(builder.fileUri); LibraryBuilder dillBuilder = dillLoadedData.loader.builders.remove(builder.uri); if (dillBuilder != null) { removedDillBuilders = true; userBuilders?.remove(builder.uri); } // Remove component problems for libraries we don't reuse. if (remainingComponentProblems.isNotEmpty) { Library lib = builder.library; removeLibraryFromRemainingComponentProblems(lib, uriTranslator); } } if (removedDillBuilders) { dillLoadedData.loader.libraries.clear(); for (LibraryBuilder builder in dillLoadedData.loader.builders.values) { dillLoadedData.loader.libraries.add(builder.library); } } if (hasToCheckPackageUris) { // The package file was changed. // Make sure the dill loader is on the same page. DillTarget oldDillLoadedData = dillLoadedData; dillLoadedData = new DillTarget(ticker, uriTranslator, c.options.target); for (DillLibraryBuilder library in oldDillLoadedData.loader.builders.values) { library.loader = dillLoadedData.loader; dillLoadedData.loader.builders[library.uri] = library; if (library.uri.scheme == "dart" && library.uri.path == "core") { dillLoadedData.loader.coreLibrary = library; } } dillLoadedData.loader.first = oldDillLoadedData.loader.first; dillLoadedData.loader.libraries .addAll(oldDillLoadedData.loader.libraries); } if (hierarchy != null) { List<Library> removedLibraries = new List<Library>(); for (LibraryBuilder builder in notReusedLibraries) { Library lib = builder.library; removedLibraries.add(lib); } hierarchy.applyTreeChanges(removedLibraries, const []); } notReusedLibraries = null; if (userCode != null) { ticker.logMs("Decided to reuse ${reusedLibraries.length}" " of ${userCode.loader.builders.length} libraries"); } await loadEnsureLoadedComponents(reusedLibraries); KernelTarget userCodeOld = userCode; userCode = new KernelTarget( new HybridFileSystem( new MemoryFileSystem( new Uri(scheme: "org-dartlang-debug", path: "/")), c.fileSystem), false, dillLoadedData, uriTranslator); userCode.loader.hierarchy = hierarchy; if (trackNeededDillLibraries) { // Reset dill loaders and kernel class hierarchy. for (LibraryBuilder builder in dillLoadedData.loader.builders.values) { if (builder is DillLibraryBuilder) { if (builder.isBuiltAndMarked) { // Clear cached calculations in classes which upon calculation can // mark things as needed. for (Builder builder in builder.scope.local.values) { if (builder is DillClassBuilder) { builder.supertype = null; builder.interfaces = null; } } builder.isBuiltAndMarked = false; } } } if (hierarchy is ClosedWorldClassHierarchy) { hierarchy.resetUsed(); } } for (LibraryBuilder library in reusedLibraries) { userCode.loader.builders[library.uri] = library; if (library.uri.scheme == "dart" && library.uri.path == "core") { userCode.loader.coreLibrary = library; } } entryPoints = userCode.setEntryPoints(entryPoints); if (userCode.loader.first == null && userCode.loader.builders[entryPoints.first] != null) { userCode.loader.first = userCode.loader.builders[entryPoints.first]; } Component componentWithDill = await userCode.buildOutlines(); // This is not the full component. It is the component consisting of all // newly compiled libraries and all libraries loaded from .dill files or // directly from components. // Technically, it's the combination of userCode.loader.libraries and // dillLoadedData.loader.libraries. if (!outlineOnly) { componentWithDill = await userCode.buildComponent(verify: c.options.verify); } hierarchy ??= userCode.loader.hierarchy; recordNonFullComponentForTesting(componentWithDill); if (trackNeededDillLibraries) { // Which dill builders were built? neededDillLibraries = new Set<Library>(); for (LibraryBuilder builder in dillLoadedData.loader.builders.values) { if (builder is DillLibraryBuilder) { if (builder.isBuiltAndMarked) { neededDillLibraries.add(builder.library); } } } updateNeededDillLibrariesWithHierarchy( hierarchy, userCode.loader.builderHierarchy); } if (componentWithDill != null) { this.invalidatedUris.clear(); hasToCheckPackageUris = false; userCodeOld?.loader?.releaseAncillaryResources(); userCodeOld?.loader?.builders?.clear(); userCodeOld = null; } List<Library> compiledLibraries = new List<Library>.from(userCode.loader.libraries); Procedure mainMethod = componentWithDill == null ? data.userLoadedUriMain : componentWithDill.mainMethod; List<Library> outputLibraries; Set<Library> allLibraries; Map<Uri, Source> uriToSource = componentWithDill?.uriToSource; if (data.component != null || fullComponent) { outputLibraries = computeTransitiveClosure( compiledLibraries, entryPoints, reusedLibraries, hierarchy, uriTranslator, uriToSource); allLibraries = outputLibraries.toSet(); if (!c.options.omitPlatform) { for (int i = 0; i < platformBuilders.length; i++) { Library lib = platformBuilders[i].library; outputLibraries.add(lib); } } } else { outputLibraries = new List<Library>(); allLibraries = computeTransitiveClosure( compiledLibraries, entryPoints, reusedLibraries, hierarchy, uriTranslator, uriToSource, outputLibraries) .toSet(); } List<String> problemsAsJson = reissueComponentProblems(componentWithDill); reissueLibraryProblems(allLibraries, compiledLibraries); if (componentWithDill == null) { userCode.loader.builders.clear(); userCode = userCodeOld; } // This is the incremental component. return context.options.target.configureComponent( new Component(libraries: outputLibraries, uriToSource: uriToSource)) ..mainMethod = mainMethod ..problemsAsJson = problemsAsJson; }); } @override CoreTypes getCoreTypes() => userCode?.loader?.coreTypes; @override ClassHierarchy getClassHierarchy() => userCode?.loader?.hierarchy; /// Allows for updating the list of needed libraries. /// /// Useful if a class hierarchy has been used externally. /// Currently there are two different class hierarchies which is unfortunate. /// For now this method allows the 'ClassHierarchyBuilder' to be null. /// /// TODO(jensj,CFE in general): Eventually we should get to a point where we /// only have one class hierarchy. /// TODO(jensj): This could probably be a utility method somewhere instead /// (though handling of the case where all bets are off should probably still /// live locally). void updateNeededDillLibrariesWithHierarchy( ClassHierarchy hierarchy, ClassHierarchyBuilder builderHierarchy) { if (hierarchy is ClosedWorldClassHierarchy && !hierarchy.allBetsOff) { neededDillLibraries ??= new Set<Library>(); Set<Class> classes = new Set<Class>(); List<Class> worklist = new List<Class>(); // Get all classes touched by kernel class hierarchy. List<Class> usedClasses = hierarchy.getUsedClasses(); worklist.addAll(usedClasses); classes.addAll(usedClasses); // Get all classes touched by fasta class hierarchy. if (builderHierarchy != null) { for (Class c in builderHierarchy.nodes.keys) { if (classes.add(c)) worklist.add(c); } } // Get all supers etc. while (worklist.isNotEmpty) { Class c = worklist.removeLast(); for (Supertype supertype in c.implementedTypes) { if (classes.add(supertype.classNode)) { worklist.add(supertype.classNode); } } if (c.mixedInType != null) { if (classes.add(c.mixedInType.classNode)) { worklist.add(c.mixedInType.classNode); } } if (c.supertype != null) { if (classes.add(c.supertype.classNode)) { worklist.add(c.supertype.classNode); } } } // Add any libraries that was used or was in the "parent-chain" of a // used class. for (Class c in classes) { Library library = c.enclosingLibrary; // Only add if loaded from a dill file. if (dillLoadedData.loader.builders.containsKey(library.importUri)) { neededDillLibraries.add(library); } } } else { // Cannot track in other kernel class hierarchies or // if all bets are off: Add everything. neededDillLibraries = new Set<Library>(); for (LibraryBuilder builder in dillLoadedData.loader.builders.values) { if (builder is DillLibraryBuilder) { neededDillLibraries.add(builder.library); } } } } /// Internal method. void invalidateNotKeptUserBuilders(Set<Uri> invalidatedUris) { if (modulesToLoad != null && userBuilders != null) { Set<Library> loadedNotKept = new Set<Library>(); for (LibraryBuilder builder in userBuilders.values) { loadedNotKept.add(builder.library); } for (Component module in modulesToLoad) { loadedNotKept.removeAll(module.libraries); } for (Library lib in loadedNotKept) { invalidatedUris.add(lib.importUri); } } } /// Internal method. Future<void> loadEnsureLoadedComponents( List<LibraryBuilder> reusedLibraries) async { if (modulesToLoad != null) { bool loadedAnything = false; for (Component module in modulesToLoad) { bool usedComponent = false; for (Library lib in module.libraries) { if (!dillLoadedData.loader.builders.containsKey(lib.importUri)) { dillLoadedData.loader.libraries.add(lib); dillLoadedData.addLibrary(lib); reusedLibraries.add(dillLoadedData.loader.read(lib.importUri, -1)); usedComponent = true; } } if (usedComponent) { dillLoadedData.uriToSource.addAll(module.uriToSource); loadedAnything = true; } } if (loadedAnything) { await dillLoadedData.buildOutlines(); userBuilders = <Uri, LibraryBuilder>{}; platformBuilders = <LibraryBuilder>[]; dillLoadedData.loader.builders.forEach((uri, builder) { if (builder.uri.scheme == "dart") { platformBuilders.add(builder); } else { userBuilders[uri] = builder; } }); if (userBuilders.isEmpty) { userBuilders = null; } } modulesToLoad = null; } } /// Internal method. void reissueLibraryProblems( Set<Library> allLibraries, List<Library> compiledLibraries) { // The newly-compiled libraries have issued problems already. Re-issue // problems for the libraries that weren't re-compiled (ignore compile // expression problems) allLibraries.removeAll(compiledLibraries); for (Library library in allLibraries) { if (library.problemsAsJson?.isNotEmpty == true) { for (String jsonString in library.problemsAsJson) { DiagnosticMessageFromJson message = new DiagnosticMessageFromJson.fromJson(jsonString); if (message.uri == debugExprUri) { continue; } context.options.reportDiagnosticMessage(message); } } } } /// Internal method. /// Re-issue problems on the component and return the filtered list. List<String> reissueComponentProblems(Component componentWithDill) { // These problems have already been reported. Set<String> issuedProblems = new Set<String>(); if (componentWithDill?.problemsAsJson != null) { issuedProblems.addAll(componentWithDill.problemsAsJson); } // Report old problems that wasn't reported again. for (List<DiagnosticMessageFromJson> messages in remainingComponentProblems.values) { for (int i = 0; i < messages.length; i++) { DiagnosticMessageFromJson message = messages[i]; if (issuedProblems.add(message.toJsonString())) { context.options.reportDiagnosticMessage(message); } } } // Save any new component-problems. if (componentWithDill?.problemsAsJson != null) { for (String jsonString in componentWithDill.problemsAsJson) { DiagnosticMessageFromJson message = new DiagnosticMessageFromJson.fromJson(jsonString); List<DiagnosticMessageFromJson> messages = remainingComponentProblems[message.uri] ??= new List<DiagnosticMessageFromJson>(); messages.add(message); } } return new List<String>.from(issuedProblems); } /// Internal method. Uri getPartFileUri( Uri parentFileUri, LibraryPart part, UriTranslator uriTranslator) { Uri fileUri = parentFileUri.resolve(part.partUri); if (fileUri.scheme == "package") { // Part was specified via package URI and the resolve above thus // did not go as expected. Translate the package URI to get the // actual file URI. fileUri = uriTranslator.translate(fileUri, false); } return fileUri; } /// Internal method. /// Compute the transitive closure. /// /// As a side-effect, this also cleans-up now-unreferenced builders as well as /// any saved component problems for such builders. List<Library> computeTransitiveClosure( List<Library> inputLibraries, List<Uri> entries, List<LibraryBuilder> reusedLibraries, ClassHierarchy hierarchy, UriTranslator uriTranslator, Map<Uri, Source> uriToSource, [List<Library> inputLibrariesFiltered]) { List<Library> result = new List<Library>(); Map<Uri, Library> libraryMap = <Uri, Library>{}; Map<Uri, Library> potentiallyReferencedLibraries = <Uri, Library>{}; Map<Uri, Library> potentiallyReferencedInputLibraries = <Uri, Library>{}; for (Library library in inputLibraries) { libraryMap[library.importUri] = library; if (library.importUri.scheme == "dart") { result.add(library); inputLibrariesFiltered?.add(library); } else { potentiallyReferencedLibraries[library.importUri] = library; potentiallyReferencedInputLibraries[library.importUri] = library; } } List<Uri> worklist = new List<Uri>(); worklist.addAll(entries); for (LibraryBuilder libraryBuilder in reusedLibraries) { if (libraryBuilder.uri.scheme == "dart" && !libraryBuilder.isSynthetic) { continue; } Library lib = libraryBuilder.library; potentiallyReferencedLibraries[libraryBuilder.uri] = lib; libraryMap[libraryBuilder.uri] = lib; } LibraryGraph graph = new LibraryGraph(libraryMap); while (worklist.isNotEmpty && potentiallyReferencedLibraries.isNotEmpty) { Uri uri = worklist.removeLast(); if (libraryMap.containsKey(uri)) { for (Uri neighbor in graph.neighborsOf(uri)) { worklist.add(neighbor); } libraryMap.remove(uri); Library library = potentiallyReferencedLibraries.remove(uri); if (library != null) { result.add(library); if (potentiallyReferencedInputLibraries.remove(uri) != null) { inputLibrariesFiltered?.add(library); } } } } List<Library> removedLibraries = new List<Library>(); for (Uri uri in potentiallyReferencedLibraries.keys) { if (uri.scheme == "package") continue; LibraryBuilder builder = userCode.loader.builders.remove(uri); if (builder != null) { Library lib = builder.library; removedLibraries.add(lib); dillLoadedData.loader.builders.remove(uri); CompilerContext.current.uriToSource.remove(uri); uriToSource.remove(uri); userBuilders?.remove(uri); removeLibraryFromRemainingComponentProblems(lib, uriTranslator); } } hierarchy?.applyTreeChanges(removedLibraries, const []); return result; } /// Internal method. void removeLibraryFromRemainingComponentProblems( Library lib, UriTranslator uriTranslator) { remainingComponentProblems.remove(lib.fileUri); // Remove parts too. for (LibraryPart part in lib.parts) { Uri partFileUri = getPartFileUri(lib.fileUri, part, uriTranslator); remainingComponentProblems.remove(partFileUri); } } /// Internal method. int prepareSummary(List<int> summaryBytes, UriTranslator uriTranslator, CompilerContext c, IncrementalCompilerData data) { dillLoadedData = new DillTarget(ticker, uriTranslator, c.options.target); int bytesLength = 0; if (summaryBytes != null) { ticker.logMs("Read ${c.options.sdkSummary}"); data.component = c.options.target.configureComponent(new Component()); new BinaryBuilderWithMetadata(summaryBytes, disableLazyReading: false, disableLazyClassReading: true) .readComponent(data.component); ticker.logMs("Deserialized ${c.options.sdkSummary}"); bytesLength += summaryBytes.length; } return bytesLength; } /// Internal method. // This procedure will try to load the dill file and will crash if it cannot. Future<int> initializeFromDill(UriTranslator uriTranslator, CompilerContext c, IncrementalCompilerData data) async { int bytesLength = 0; FileSystemEntity entity = c.options.fileSystem.entityForUri(initializeFromDillUri); if (await entity.exists()) { List<int> initializationBytes = await entity.readAsBytes(); if (initializationBytes != null && initializationBytes.isNotEmpty) { ticker.logMs("Read $initializeFromDillUri"); data.initializationBytes = initializationBytes; // We're going to output all we read here so lazy loading it // doesn't make sense. new BinaryBuilderWithMetadata(initializationBytes, disableLazyReading: true) .readComponent(data.component, checkCanonicalNames: true); // Check the any package-urls still point to the same file // (e.g. the package still exists and hasn't been updated). for (Library lib in data.component.libraries) { if (lib.importUri.scheme == "package" && uriTranslator.translate(lib.importUri, false) != lib.fileUri) { // Package has been removed or updated. // This library should be thrown away. // Everything that depends on it should be thrown away. // TODO(jensj): Anything that doesn't depend on it can be kept. // For now just don't initialize from this dill. throw const PackageChangedError(); } } initializedFromDill = true; bytesLength += initializationBytes.length; data.userLoadedUriMain = data.component.mainMethod; saveComponentProblems(data); } } return bytesLength; } /// Internal method. void saveComponentProblems(IncrementalCompilerData data) { if (data.component.problemsAsJson != null) { for (String jsonString in data.component.problemsAsJson) { DiagnosticMessageFromJson message = new DiagnosticMessageFromJson.fromJson(jsonString); List<DiagnosticMessageFromJson> messages = remainingComponentProblems[message.uri] ??= new List<DiagnosticMessageFromJson>(); messages.add(message); } } } /// Internal method. // This procedure will set up compiler from [componentToInitializeFrom]. void initializeFromComponent(UriTranslator uriTranslator, CompilerContext c, IncrementalCompilerData data) { ticker.logMs("About to initializeFromComponent"); dillLoadedData = new DillTarget(ticker, uriTranslator, c.options.target); data.component = new Component( libraries: componentToInitializeFrom.libraries, uriToSource: componentToInitializeFrom.uriToSource) ..mainMethod = componentToInitializeFrom.mainMethod; data.userLoadedUriMain = componentToInitializeFrom.mainMethod; saveComponentProblems(data); bool foundDartCore = false; for (int i = 0; i < data.component.libraries.length; i++) { Library library = data.component.libraries[i]; if (library.importUri.scheme == "dart" && library.importUri.path == "core") { foundDartCore = true; break; } } if (!foundDartCore) { throw const InitializeFromComponentError("Did not find dart:core when " "tried to initialize from component."); } ticker.logMs("Ran initializeFromComponent"); } /// Internal method. void appendLibraries(IncrementalCompilerData data, int bytesLength) { if (data.component != null) { dillLoadedData.loader .appendLibraries(data.component, byteCount: bytesLength); } ticker.logMs("Appended libraries"); } @override Future<Procedure> compileExpression( String expression, Map<String, DartType> definitions, List<TypeParameter> typeDefinitions, String syntheticProcedureName, Uri libraryUri, [String className, bool isStatic = false]) async { assert(dillLoadedData != null && userCode != null); return await context.runInContext((_) async { LibraryBuilder libraryBuilder = userCode.loader.read(libraryUri, -1, accessor: userCode.loader.first); Class cls; if (className != null) { ClassBuilder classBuilder = libraryBuilder.scopeBuilder[className]; cls = classBuilder?.cls; if (cls == null) return null; } userCode.loader.seenMessages.clear(); for (TypeParameter typeParam in typeDefinitions) { if (!isLegalIdentifier(typeParam.name)) return null; } for (String name in definitions.keys) { if (!isLegalIdentifier(name)) return null; } SourceLibraryBuilder debugLibrary = new SourceLibraryBuilder( libraryUri, debugExprUri, userCode.loader, null, scope: libraryBuilder.scope.createNestedScope("expression"), nameOrigin: libraryBuilder.library, ); debugLibrary.setLanguageVersion( libraryBuilder.library.languageVersionMajor, libraryBuilder.library.languageVersionMinor); if (libraryBuilder is DillLibraryBuilder) { for (LibraryDependency dependency in libraryBuilder.library.dependencies) { if (!dependency.isImport) continue; List<Combinator> combinators; for (kernel.Combinator combinator in dependency.combinators) { combinators ??= <Combinator>[]; combinators.add(combinator.isShow ? new Combinator.show(combinator.names, combinator.fileOffset, libraryBuilder.fileUri) : new Combinator.hide(combinator.names, combinator.fileOffset, libraryBuilder.fileUri)); } debugLibrary.addImport( null, dependency.importedLibraryReference.canonicalName.name, null, dependency.name, combinators, dependency.isDeferred, -1, -1, -1, -1); } debugLibrary.addImportsToScope(); } HybridFileSystem hfs = userCode.fileSystem; MemoryFileSystem fs = hfs.memory; fs.entityForUri(debugExprUri).writeAsStringSync(expression); FunctionNode parameters = new FunctionNode(null, typeParameters: typeDefinitions, positionalParameters: definitions.keys .map((name) => new VariableDeclarationImpl(name, 0)) .toList()); debugLibrary.build(userCode.loader.coreLibrary, modifyTarget: false); Expression compiledExpression = await userCode.loader.buildExpression( debugLibrary, className, className != null && !isStatic, parameters); Procedure procedure = new Procedure( new Name(syntheticProcedureName), ProcedureKind.Method, parameters, isStatic: isStatic); parameters.body = new ReturnStatement(compiledExpression) ..parent = parameters; procedure.fileUri = debugLibrary.fileUri; procedure.parent = className != null ? cls : libraryBuilder.library; userCode.uriToSource.remove(debugExprUri); userCode.loader.sourceBytes.remove(debugExprUri); // Make sure the library has a canonical name. Component c = new Component(libraries: [debugLibrary.library]); c.computeCanonicalNames(); userCode.runProcedureTransformations(procedure); return procedure; }); } /// Internal method. List<LibraryBuilder> computeReusedLibraries( Set<Uri> invalidatedUris, UriTranslator uriTranslator, {Set<LibraryBuilder> notReused}) { List<LibraryBuilder> result = <LibraryBuilder>[]; result.addAll(platformBuilders); if (userCode == null && userBuilders == null) { return result; } // Maps all non-platform LibraryBuilders from their import URI. Map<Uri, LibraryBuilder> builders = <Uri, LibraryBuilder>{}; // Invalidated URIs translated back to their import URI (package:, dart:, // etc.). List<Uri> invalidatedImportUris = <Uri>[]; bool isInvalidated(Uri importUri, Uri fileUri) { if (invalidatedUris.contains(importUri)) return true; if (importUri != fileUri && invalidatedUris.contains(fileUri)) { return true; } if (hasToCheckPackageUris && importUri.scheme == "package") { // Get package name, check if the base URI has changed for the package, // if it has, translate the URI again, // otherwise the URI cannot have changed. String path = importUri.path; int firstSlash = path.indexOf('/'); String packageName = path.substring(0, firstSlash); if (previousPackagesMap == null || (previousPackagesMap[packageName] != currentPackagesMap[packageName])) { Uri newFileUri = uriTranslator.translate(importUri, false); if (newFileUri != fileUri) { return true; } } } if (builders[importUri]?.isSynthetic ?? false) return true; return false; } addBuilderAndInvalidateUris(Uri uri, LibraryBuilder libraryBuilder) { if (uri.scheme == "dart" && !libraryBuilder.isSynthetic) { result.add(libraryBuilder); return; } builders[uri] = libraryBuilder; if (isInvalidated(uri, libraryBuilder.library.fileUri)) { invalidatedImportUris.add(uri); } if (libraryBuilder is SourceLibraryBuilder) { for (LibraryBuilder part in libraryBuilder.parts) { if (isInvalidated(part.uri, part.fileUri)) { invalidatedImportUris.add(part.uri); builders[part.uri] = part; } } } else if (libraryBuilder is DillLibraryBuilder) { for (LibraryPart part in libraryBuilder.library.parts) { Uri partUri = libraryBuilder.uri.resolve(part.partUri); Uri fileUri = getPartFileUri( libraryBuilder.library.fileUri, part, uriTranslator); if (isInvalidated(partUri, fileUri)) { invalidatedImportUris.add(partUri); builders[partUri] = libraryBuilder; } } } } if (userCode != null) { // userCode already contains the builders from userBuilders. userCode.loader.builders.forEach(addBuilderAndInvalidateUris); } else { // userCode was null so we explicitly have to add the builders from // userBuilders (which cannot be null as we checked initially that one of // them was non-null). userBuilders.forEach(addBuilderAndInvalidateUris); } recordInvalidatedImportUrisForTesting(invalidatedImportUris); BuilderGraph graph = new BuilderGraph(builders); // Compute direct dependencies for each import URI (the reverse of the // edges returned by `graph.neighborsOf`). Map<Uri, Set<Uri>> directDependencies = <Uri, Set<Uri>>{}; for (Uri vertex in graph.vertices) { for (Uri neighbor in graph.neighborsOf(vertex)) { (directDependencies[neighbor] ??= new Set<Uri>()).add(vertex); } } // Remove all dependencies of [invalidatedImportUris] from builders. List<Uri> workList = invalidatedImportUris; while (workList.isNotEmpty) { Uri removed = workList.removeLast(); LibraryBuilder current = builders.remove(removed); // [current] is null if the corresponding key (URI) has already been // removed. if (current != null) { Set<Uri> s = directDependencies[current.uri]; if (current.uri != removed) { if (s == null) { s = directDependencies[removed]; } else { s.addAll(directDependencies[removed]); } } if (s != null) { // [s] is null for leaves. for (Uri dependency in s) { workList.add(dependency); } } notReused?.add(current); } } // Builders contain mappings from part uri to builder, meaning the same // builder can exist multiple times in the values list. Set<Uri> seenUris = new Set<Uri>(); for (LibraryBuilder builder in builders.values) { if (builder.isPart) continue; // TODO(jensj/ahe): This line can probably go away once // https://dart-review.googlesource.com/47442 lands. if (builder.isPatch) continue; if (!seenUris.add(builder.uri)) continue; result.add(builder); } return result; } @override void invalidate(Uri uri) { invalidatedUris.add(uri); } @override void invalidateAllSources() { if (userCode != null) { Set<Uri> uris = new Set<Uri>.from(userCode.loader.builders.keys); uris.removeAll(dillLoadedData.loader.builders.keys); invalidatedUris.addAll(uris); } } @override void setModulesToLoadOnNextComputeDelta(List<Component> components) { modulesToLoad = components.toList(); } /// Internal method. void recordNonFullComponentForTesting(Component component) {} /// Internal method. void recordInvalidatedImportUrisForTesting(List<Uri> uris) {} /// Internal method. void recordTemporaryFileForTesting(Uri uri) {} } class PackageChangedError { const PackageChangedError(); } class InitializeFromComponentError { final String message; const InitializeFromComponentError(this.message); String toString() => message; } class IncrementalCompilerData { Procedure userLoadedUriMain = null; Component component = null; List<int> initializationBytes = null; }
0